Debian Codegraph @

core/java/android/os/Process.java

raw symbols SCIP
1 /*
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
17 package android.os;
18
19 import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
20
21 import android.annotation.ElapsedRealtimeLong;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.SystemApi;
25 import android.annotation.TestApi;
26 import android.annotation.UptimeMillisLong;
27 import android.compat.annotation.UnsupportedAppUsage;
28 import android.os.Build.VERSION_CODES;
29 import android.sysprop.MemoryProperties;
30 import android.system.ErrnoException;
31 import android.system.Os;
32 import android.system.OsConstants;
33 import android.system.StructPollfd;
34 import android.util.Pair;
35 import android.webkit.WebViewZygote;
36
37 import dalvik.system.VMRuntime;
38
39 import libcore.io.IoUtils;
40
41 import java.io.FileDescriptor;
42 import java.io.IOException;
43 import java.util.Map;
44 import java.util.concurrent.TimeoutException;
45
46 /**
47 * Tools for managing OS processes.
48 */
49 public class Process {
50 private static final String LOG_TAG = "Process";
51
52 /**
53 * An invalid UID value.
54 */
55 public static final int INVALID_UID = -1;
56
57 /**
58 * Defines the root UID.
59 */
60 public static final int ROOT_UID = 0;
61
62 /**
63 * Defines the UID/GID under which system code runs.
64 */
65 public static final int SYSTEM_UID = 1000;
66
67 /**
68 * Defines the UID/GID under which the telephony code runs.
69 */
70 public static final int PHONE_UID = 1001;
71
72 /**
73 * Defines the UID/GID for the user shell.
74 */
75 public static final int SHELL_UID = 2000;
76
77 /**
78 * Defines the UID/GID for the log group.
79 * @hide
80 */
81 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
82 public static final int LOG_UID = 1007;
83
84 /**
85 * Defines the UID/GID for the WIFI native processes like wificond, supplicant, hostapd,
86 * vendor HAL, etc.
87 */
88 public static final int WIFI_UID = 1010;
89
90 /**
91 * Defines the UID/GID for the mediaserver process.
92 * @hide
93 */
94 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
95 public static final int MEDIA_UID = 1013;
96
97 /**
98 * Defines the UID/GID for the DRM process.
99 * @hide
100 */
101 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
102 public static final int DRM_UID = 1019;
103
104 /**
105 * Defines the GID for the group that allows write access to the internal media storage.
106 * @hide
107 */
108 public static final int SDCARD_RW_GID = 1015;
109
110 /**
111 * Defines the UID/GID for the group that controls VPN services.
112 * @hide
113 */
114 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
115 @SystemApi(client = MODULE_LIBRARIES)
116 public static final int VPN_UID = 1016;
117
118 /**
119 * Defines the UID/GID for keystore.
120 * @hide
121 */
122 public static final int KEYSTORE_UID = 1017;
123
124 /**
125 * Defines the UID/GID for credstore.
126 * @hide
127 */
128 public static final int CREDSTORE_UID = 1076;
129
130 /**
131 * Defines the UID/GID for the NFC service process.
132 * @hide
133 */
134 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
135 @TestApi
136 @SystemApi(client = MODULE_LIBRARIES)
137 public static final int NFC_UID = 1027;
138
139 /**
140 * Defines the UID/GID for the clatd process.
141 * @hide
142 * */
143 public static final int CLAT_UID = 1029;
144
145 /**
146 * Defines the UID/GID for the Bluetooth service process.
147 */
148 public static final int BLUETOOTH_UID = 1002;
149
150 /**
151 * Defines the GID for the group that allows write access to the internal media storage.
152 * @hide
153 */
154 public static final int MEDIA_RW_GID = 1023;
155
156 /**
157 * Access to installed package details
158 * @hide
159 */
160 public static final int PACKAGE_INFO_GID = 1032;
161
162 /**
163 * Defines the UID/GID for the shared RELRO file updater process.
164 * @hide
165 */
166 public static final int SHARED_RELRO_UID = 1037;
167
168 /**
169 * Defines the UID/GID for the audioserver process.
170 * @hide
171 */
172 public static final int AUDIOSERVER_UID = 1041;
173
174 /**
175 * Defines the UID/GID for the cameraserver process
176 * @hide
177 */
178 public static final int CAMERASERVER_UID = 1047;
179
180 /**
181 * Defines the UID/GID for the tethering DNS resolver (currently dnsmasq).
182 * @hide
183 */
184 public static final int DNS_TETHER_UID = 1052;
185
186 /**
187 * Defines the UID/GID for the WebView zygote process.
188 * @hide
189 */
190 public static final int WEBVIEW_ZYGOTE_UID = 1053;
191
192 /**
193 * Defines the UID used for resource tracking for OTA updates.
194 * @hide
195 */
196 public static final int OTA_UPDATE_UID = 1061;
197
198 /**
199 * Defines the UID used for statsd
200 * @hide
201 */
202 public static final int STATSD_UID = 1066;
203
204 /**
205 * Defines the UID used for incidentd.
206 * @hide
207 */
208 public static final int INCIDENTD_UID = 1067;
209
210 /**
211 * Defines the UID/GID for the Secure Element service process.
212 * @hide
213 */
214 public static final int SE_UID = 1068;
215
216 /**
217 * Defines the UID/GID for the iorapd.
218 * @hide
219 */
220 public static final int IORAPD_UID = 1071;
221
222 /**
223 * Defines the UID/GID for the NetworkStack app.
224 * @hide
225 */
226 public static final int NETWORK_STACK_UID = 1073;
227
228 /**
229 * Defines the UID/GID for fs-verity certificate ownership in keystore.
230 * @hide
231 */
232 public static final int FSVERITY_CERT_UID = 1075;
233
234 /**
235 * GID that gives access to USB OTG (unreliable) volumes on /mnt/media_rw/<vol name>
236 * @hide
237 */
238 public static final int EXTERNAL_STORAGE_GID = 1077;
239
240 /**
241 * GID that gives write access to app-private data directories on external
242 * storage (used on devices without sdcardfs only).
243 * @hide
244 */
245 public static final int EXT_DATA_RW_GID = 1078;
246
247 /**
248 * GID that gives write access to app-private OBB directories on external
249 * storage (used on devices without sdcardfs only).
250 * @hide
251 */
252 public static final int EXT_OBB_RW_GID = 1079;
253
254 /**
255 * Defines the UID/GID for the Uwb service process.
256 * @hide
257 */
258 public static final int UWB_UID = 1083;
259
260 /**
261 * Defines a virtual UID that is used to aggregate data related to SDK sandbox UIDs.
262 * {@see SdkSandboxManager}
263 * @hide
264 */
265 @TestApi
266 public static final int SDK_SANDBOX_VIRTUAL_UID = 1090;
267
268 /**
269 * GID that corresponds to the INTERNET permission.
270 * Must match the value of AID_INET.
271 * @hide
272 */
273 public static final int INET_GID = 3003;
274
275 /** {@hide} */
276 public static final int NOBODY_UID = 9999;
277
278 /**
279 * Defines the start of a range of UIDs (and GIDs), going from this
280 * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
281 * to applications.
282 */
283 public static final int FIRST_APPLICATION_UID = 10000;
284
285 /**
286 * Last of application-specific UIDs starting at
287 * {@link #FIRST_APPLICATION_UID}.
288 */
289 public static final int LAST_APPLICATION_UID = 19999;
290
291 /**
292 * Defines the start of a range of UIDs going from this number to
293 * {@link #LAST_SDK_SANDBOX_UID} that are reserved for assigning to
294 * sdk sandbox processes. There is a 1-1 mapping between a sdk sandbox
295 * process UID and the app that it belongs to, which can be computed by
296 * subtracting (FIRST_SDK_SANDBOX_UID - FIRST_APPLICATION_UID) from the
297 * uid of a sdk sandbox process.
298 *
299 * Note that there are no GIDs associated with these processes; storage
300 * attribution for them will be done using project IDs.
301 * @hide
302 */
303 public static final int FIRST_SDK_SANDBOX_UID = 20000;
304
305 /**
306 * Last UID that is used for sdk sandbox processes.
307 * @hide
308 */
309 public static final int LAST_SDK_SANDBOX_UID = 29999;
310
311 /**
312 * First uid used for fully isolated sandboxed processes spawned from an app zygote
313 * @hide
314 */
315 @TestApi
316 public static final int FIRST_APP_ZYGOTE_ISOLATED_UID = 90000;
317
318 /**
319 * Number of UIDs we allocate per application zygote
320 * @hide
321 */
322 @TestApi
323 public static final int NUM_UIDS_PER_APP_ZYGOTE = 100;
324
325 /**
326 * Last uid used for fully isolated sandboxed processes spawned from an app zygote
327 * @hide
328 */
329 @TestApi
330 public static final int LAST_APP_ZYGOTE_ISOLATED_UID = 98999;
331
332 /**
333 * First uid used for fully isolated sandboxed processes (with no permissions of their own)
334 * @hide
335 */
336 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
337 @TestApi
338 public static final int FIRST_ISOLATED_UID = 99000;
339
340 /**
341 * Last uid used for fully isolated sandboxed processes (with no permissions of their own)
342 * @hide
343 */
344 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
345 @TestApi
346 public static final int LAST_ISOLATED_UID = 99999;
347
348 /**
349 * Defines the gid shared by all applications running under the same profile.
350 * @hide
351 */
352 public static final int SHARED_USER_GID = 9997;
353
354 /**
355 * First gid for applications to share resources. Used when forward-locking
356 * is enabled but all UserHandles need to be able to read the resources.
357 * @hide
358 */
359 public static final int FIRST_SHARED_APPLICATION_GID = 50000;
360
361 /**
362 * Last gid for applications to share resources. Used when forward-locking
363 * is enabled but all UserHandles need to be able to read the resources.
364 * @hide
365 */
366 public static final int LAST_SHARED_APPLICATION_GID = 59999;
367
368 /** {@hide} */
369 public static final int FIRST_APPLICATION_CACHE_GID = 20000;
370 /** {@hide} */
371 public static final int LAST_APPLICATION_CACHE_GID = 29999;
372
373 /**
374 * Standard priority of application threads.
375 * Use with {@link #setThreadPriority(int)} and
376 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
377 * {@link java.lang.Thread} class.
378 */
379 public static final int THREAD_PRIORITY_DEFAULT = 0;
380
381 /*
382 * ***************************************
383 * ** Keep in sync with utils/threads.h **
384 * ***************************************
385 */
386
387 /**
388 * Lowest available thread priority. Only for those who really, really
389 * don't want to run if anything else is happening.
390 * Use with {@link #setThreadPriority(int)} and
391 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
392 * {@link java.lang.Thread} class.
393 */
394 public static final int THREAD_PRIORITY_LOWEST = 19;
395
396 /**
397 * Standard priority background threads. This gives your thread a slightly
398 * lower than normal priority, so that it will have less chance of impacting
399 * the responsiveness of the user interface.
400 * Use with {@link #setThreadPriority(int)} and
401 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
402 * {@link java.lang.Thread} class.
403 */
404 public static final int THREAD_PRIORITY_BACKGROUND = 10;
405
406 /**
407 * Standard priority of threads that are currently running a user interface
408 * that the user is interacting with. Applications can not normally
409 * change to this priority; the system will automatically adjust your
410 * application threads as the user moves through the UI.
411 * Use with {@link #setThreadPriority(int)} and
412 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
413 * {@link java.lang.Thread} class.
414 */
415 public static final int THREAD_PRIORITY_FOREGROUND = -2;
416
417 /**
418 * Standard priority of system display threads, involved in updating
419 * the user interface. Applications can not
420 * normally change to this priority.
421 * Use with {@link #setThreadPriority(int)} and
422 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
423 * {@link java.lang.Thread} class.
424 */
425 public static final int THREAD_PRIORITY_DISPLAY = -4;
426
427 /**
428 * Standard priority of the most important display threads, for compositing
429 * the screen and retrieving input events. Applications can not normally
430 * change to this priority.
431 * Use with {@link #setThreadPriority(int)} and
432 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
433 * {@link java.lang.Thread} class.
434 */
435 public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
436
437 /**
438 * Standard priority of video threads. Applications can not normally
439 * change to this priority.
440 * Use with {@link #setThreadPriority(int)} and
441 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
442 * {@link java.lang.Thread} class.
443 */
444 public static final int THREAD_PRIORITY_VIDEO = -10;
445
446 /**
447 * Priority we boost main thread and RT of top app to.
448 * @hide
449 */
450 public static final int THREAD_PRIORITY_TOP_APP_BOOST = -10;
451
452 /**
453 * Standard priority of audio threads. Applications can not normally
454 * change to this priority.
455 * Use with {@link #setThreadPriority(int)} and
456 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
457 * {@link java.lang.Thread} class.
458 */
459 public static final int THREAD_PRIORITY_AUDIO = -16;
460
461 /**
462 * Standard priority of the most important audio threads.
463 * Applications can not normally change to this priority.
464 * Use with {@link #setThreadPriority(int)} and
465 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
466 * {@link java.lang.Thread} class.
467 */
468 public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
469
470 /**
471 * Minimum increment to make a priority more favorable.
472 */
473 public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
474
475 /**
476 * Minimum increment to make a priority less favorable.
477 */
478 public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
479
480 /**
481 * Default scheduling policy
482 * @hide
483 */
484 public static final int SCHED_OTHER = 0;
485
486 /**
487 * First-In First-Out scheduling policy
488 * @hide
489 */
490 public static final int SCHED_FIFO = 1;
491
492 /**
493 * Round-Robin scheduling policy
494 * @hide
495 */
496 public static final int SCHED_RR = 2;
497
498 /**
499 * Batch scheduling policy
500 * @hide
501 */
502 public static final int SCHED_BATCH = 3;
503
504 /**
505 * Idle scheduling policy
506 * @hide
507 */
508 public static final int SCHED_IDLE = 5;
509
510 /**
511 * Reset scheduler choice on fork.
512 * @hide
513 */
514 public static final int SCHED_RESET_ON_FORK = 0x40000000;
515
516 // Keep in sync with SP_* constants of enum type SchedPolicy
517 // declared in system/core/include/cutils/sched_policy.h,
518 // except THREAD_GROUP_DEFAULT does not correspond to any SP_* value.
519
520 /**
521 * Default thread group -
522 * has meaning with setProcessGroup() only, cannot be used with setThreadGroup().
523 * When used with setProcessGroup(), the group of each thread in the process
524 * is conditionally changed based on that thread's current priority, as follows:
525 * threads with priority numerically less than THREAD_PRIORITY_BACKGROUND
526 * are moved to foreground thread group. All other threads are left unchanged.
527 * @hide
528 */
529 public static final int THREAD_GROUP_DEFAULT = -1;
530
531 /**
532 * Background thread group - All threads in
533 * this group are scheduled with a reduced share of the CPU.
534 * Value is same as constant SP_BACKGROUND of enum SchedPolicy.
535 * @hide
536 */
537 public static final int THREAD_GROUP_BACKGROUND = 0;
538
539 /**
540 * Foreground thread group - All threads in
541 * this group are scheduled with a normal share of the CPU.
542 * Value is same as constant SP_FOREGROUND of enum SchedPolicy.
543 * Not used at this level.
544 * @hide
545 **/
546 private static final int THREAD_GROUP_FOREGROUND = 1;
547
548 /**
549 * System thread group.
550 * @hide
551 **/
552 public static final int THREAD_GROUP_SYSTEM = 2;
553
554 /**
555 * Application audio thread group.
556 * @hide
557 **/
558 public static final int THREAD_GROUP_AUDIO_APP = 3;
559
560 /**
561 * System audio thread group.
562 * @hide
563 **/
564 public static final int THREAD_GROUP_AUDIO_SYS = 4;
565
566 /**
567 * Thread group for top foreground app.
568 * @hide
569 **/
570 public static final int THREAD_GROUP_TOP_APP = 5;
571
572 /**
573 * Thread group for RT app.
574 * @hide
575 **/
576 public static final int THREAD_GROUP_RT_APP = 6;
577
578 /**
579 * Thread group for bound foreground services that should
580 * have additional CPU restrictions during screen off
581 * @hide
582 **/
583 public static final int THREAD_GROUP_RESTRICTED = 7;
584
585 public static final int SIGNAL_QUIT = 3;
586 public static final int SIGNAL_KILL = 9;
587 public static final int SIGNAL_USR1 = 10;
588
589 /**
590 * When the process started and ActivityThread.handleBindApplication() was executed.
591 */
592 private static long sStartElapsedRealtime;
593
594 /**
595 * When the process started and ActivityThread.handleBindApplication() was executed.
596 */
597 private static long sStartUptimeMillis;
598
599 /**
600 * When the activity manager was about to ask zygote to fork.
601 */
602 private static long sStartRequestedElapsedRealtime;
603
604 /**
605 * When the activity manager was about to ask zygote to fork.
606 */
607 private static long sStartRequestedUptimeMillis;
608
609 private static final int PIDFD_UNKNOWN = 0;
610 private static final int PIDFD_SUPPORTED = 1;
611 private static final int PIDFD_UNSUPPORTED = 2;
612
613 /**
614 * Whether or not the underlying OS supports pidfd
615 */
616 private static int sPidFdSupported = PIDFD_UNKNOWN;
617
618 /**
619 * Value used to indicate that there is no special information about an application launch. App
620 * launches with this policy will occur through the primary or secondary Zygote with no special
621 * treatment.
622 *
623 * @hide
624 */
625 public static final int ZYGOTE_POLICY_FLAG_EMPTY = 0;
626
627 /**
628 * Flag used to indicate that an application launch is user-visible and latency sensitive. Any
629 * launch with this policy will use a Unspecialized App Process Pool if the target Zygote
630 * supports it.
631 *
632 * @hide
633 */
634 public static final int ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE = 1 << 0;
635
636 /**
637 * Flag used to indicate that the launch is one in a series of app launches that will be
638 * performed in quick succession. For future use.
639 *
640 * @hide
641 */
642 public static final int ZYGOTE_POLICY_FLAG_BATCH_LAUNCH = 1 << 1;
643
644 /**
645 * Flag used to indicate that the current launch event is for a system process. All system
646 * processes are equally important, so none of them should be prioritized over the others.
647 *
648 * @hide
649 */
650 public static final int ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS = 1 << 2;
651
652 /**
653 * State associated with the zygote process.
654 * @hide
655 */
656 public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();
657
658
659 /**
660 * The process name set via {@link #setArgV0(String)}.
661 */
662 private static String sArgV0;
663
664 /**
665 * Start a new process.
666 *
667 * <p>If processes are enabled, a new process is created and the
668 * static main() function of a <var>processClass</var> is executed there.
669 * The process will continue running after this function returns.
670 *
671 * <p>If processes are not enabled, a new thread in the caller's
672 * process is created and main() of <var>processClass</var> called there.
673 *
674 * <p>The niceName parameter, if not an empty string, is a custom name to
675 * give to the process instead of using processClass. This allows you to
676 * make easily identifyable processes even if you are using the same base
677 * <var>processClass</var> to start them.
678 *
679 * When invokeWith is not null, the process will be started as a fresh app
680 * and not a zygote fork. Note that this is only allowed for uid 0 or when
681 * runtimeFlags contains DEBUG_ENABLE_DEBUGGER.
682 *
683 * @param processClass The class to use as the process's main entry
684 * point.
685 * @param niceName A more readable name to use for the process.
686 * @param uid The user-id under which the process will run.
687 * @param gid The group-id under which the process will run.
688 * @param gids Additional group-ids associated with the process.
689 * @param runtimeFlags Additional flags for the runtime.
690 * @param targetSdkVersion The target SDK version for the app.
691 * @param seInfo null-ok SELinux information for the new process.
692 * @param abi non-null the ABI this app should be started with.
693 * @param instructionSet null-ok the instruction set to use.
694 * @param appDataDir null-ok the data directory of the app.
695 * @param invokeWith null-ok the command to invoke with.
696 * @param packageName null-ok the name of the package this process belongs to.
697 * @param zygotePolicyFlags Flags used to determine how to launch the application
698 * @param isTopApp whether the process starts for high priority application.
699 * @param disabledCompatChanges null-ok list of disabled compat changes for the process being
700 * started.
701 * @param pkgDataInfoMap Map from related package names to private data directory
702 * volume UUID and inode number.
703 * @param whitelistedDataInfoMap Map from allowlisted package names to private data directory
704 * volume UUID and inode number.
705 * @param bindMountAppsData whether zygote needs to mount CE and DE data.
706 * @param bindMountAppStorageDirs whether zygote needs to mount Android/obb and Android/data.
707 * @param zygoteArgs Additional arguments to supply to the zygote process.
708 * @return An object that describes the result of the attempt to start the process.
709 * @throws RuntimeException on fatal start failure
710 *
711 * {@hide}
712 */
713 public static ProcessStartResult start(@NonNull final String processClass,
714 @Nullable final String niceName,
715 int uid, int gid, @Nullable int[] gids,
716 int runtimeFlags,
717 int mountExternal,
718 int targetSdkVersion,
719 @Nullable String seInfo,
720 @NonNull String abi,
721 @Nullable String instructionSet,
722 @Nullable String appDataDir,
723 @Nullable String invokeWith,
724 @Nullable String packageName,
725 int zygotePolicyFlags,
726 boolean isTopApp,
727 @Nullable long[] disabledCompatChanges,
728 @Nullable Map<String, Pair<String, Long>>
729 pkgDataInfoMap,
730 @Nullable Map<String, Pair<String, Long>>
731 whitelistedDataInfoMap,
732 boolean bindMountAppsData,
733 boolean bindMountAppStorageDirs,
734 @Nullable String[] zygoteArgs) {
735 return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
736 runtimeFlags, mountExternal, targetSdkVersion, seInfo,
737 abi, instructionSet, appDataDir, invokeWith, packageName,
738 zygotePolicyFlags, isTopApp, disabledCompatChanges,
739 pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData,
740 bindMountAppStorageDirs, zygoteArgs);
741 }
742
743 /** @hide */
744 public static ProcessStartResult startWebView(@NonNull final String processClass,
745 @Nullable final String niceName,
746 int uid, int gid, @Nullable int[] gids,
747 int runtimeFlags,
748 int mountExternal,
749 int targetSdkVersion,
750 @Nullable String seInfo,
751 @NonNull String abi,
752 @Nullable String instructionSet,
753 @Nullable String appDataDir,
754 @Nullable String invokeWith,
755 @Nullable String packageName,
756 @Nullable long[] disabledCompatChanges,
757 @Nullable String[] zygoteArgs) {
758 // Webview zygote can't access app private data files, so doesn't need to know its data
759 // info.
760 return WebViewZygote.getProcess().start(processClass, niceName, uid, gid, gids,
761 runtimeFlags, mountExternal, targetSdkVersion, seInfo,
762 abi, instructionSet, appDataDir, invokeWith, packageName,
763 /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, /*isTopApp=*/ false,
764 disabledCompatChanges, /* pkgDataInfoMap */ null,
765 /* whitelistedDataInfoMap */ null, false, false, zygoteArgs);
766 }
767
768 /**
769 * Returns elapsed milliseconds of the time this process has run.
770 * @return Returns the number of milliseconds this process has return.
771 */
772 public static final native long getElapsedCpuTime();
773
774 /**
775 * Return the {@link SystemClock#elapsedRealtime()} at which this process was started,
776 * but before any of the application code was executed.
777 */
778 @ElapsedRealtimeLong
779 public static long getStartElapsedRealtime() {
780 return sStartElapsedRealtime;
781 }
782
783 /**
784 * Return the {@link SystemClock#uptimeMillis()} at which this process was started,
785 * but before any of the application code was executed.
786 */
787 @UptimeMillisLong
788 public static long getStartUptimeMillis() {
789 return sStartUptimeMillis;
790 }
791
792 /**
793 * Return the {@link SystemClock#elapsedRealtime()} at which the system was about to
794 * start this process. i.e. before a zygote fork.
795 *
796 * <p>More precisely, the system may start app processes before there's a start request,
797 * in order to reduce the process start up latency, in which case this is set when the system
798 * decides to "specialize" the process into a requested app.
799 */
800 @ElapsedRealtimeLong
801 public static long getStartRequestedElapsedRealtime() {
802 return sStartRequestedElapsedRealtime;
803 }
804
805 /**
806 * Return the {@link SystemClock#uptimeMillis()} at which the system was about to
807 * start this process. i.e. before a zygote fork.
808 *
809 * <p>More precisely, the system may start app processes before there's a start request,
810 * in order to reduce the process start up latency, in which case this is set when the system
811 * decides to "specialize" the process into a requested app.
812 */
813 @UptimeMillisLong
814 public static long getStartRequestedUptimeMillis() {
815 return sStartRequestedUptimeMillis;
816 }
817
818 /** @hide */
819 public static final void setStartTimes(long elapsedRealtime, long uptimeMillis,
820 long startRequestedElapsedRealtime, long startRequestedUptime) {
821 sStartElapsedRealtime = elapsedRealtime;
822 sStartUptimeMillis = uptimeMillis;
823 sStartRequestedElapsedRealtime = startRequestedElapsedRealtime;
824 sStartRequestedUptimeMillis = startRequestedUptime;
825 }
826
827 /**
828 * Returns true if the current process is a 64-bit runtime.
829 */
830 public static final boolean is64Bit() {
831 return VMRuntime.getRuntime().is64Bit();
832 }
833
834 /**
835 * Returns the identifier of this process, which can be used with
836 * {@link #killProcess} and {@link #sendSignal}.
837 */
838 public static final int myPid() {
839 return Os.getpid();
840 }
841
842 /**
843 * Returns the identifier of this process' parent.
844 * @hide
845 */
846 @UnsupportedAppUsage(trackingBug = 171962076)
847 public static final int myPpid() {
848 return Os.getppid();
849 }
850
851 /**
852 * Returns the identifier of the calling thread, which be used with
853 * {@link #setThreadPriority(int, int)}.
854 */
855 public static final int myTid() {
856 return Os.gettid();
857 }
858
859 /**
860 * Returns the identifier of this process's uid. This is the kernel uid
861 * that the process is running under, which is the identity of its
862 * app-specific sandbox. It is different from {@link #myUserHandle} in that
863 * a uid identifies a specific app sandbox in a specific user.
864 */
865 public static final int myUid() {
866 return Os.getuid();
867 }
868
869 /**
870 * Returns this process's user handle. This is the
871 * user the process is running under. It is distinct from
872 * {@link #myUid()} in that a particular user will have multiple
873 * distinct apps running under it each with their own uid.
874 */
875 public static UserHandle myUserHandle() {
876 return UserHandle.of(UserHandle.getUserId(myUid()));
877 }
878
879 /**
880 * Returns whether the given uid belongs to a system core component or not.
881 * @hide
882 */
883 public static boolean isCoreUid(int uid) {
884 return UserHandle.isCore(uid);
885 }
886
887 /**
888 * Returns whether the given uid belongs to an application.
889 * @param uid A kernel uid.
890 * @return Whether the uid corresponds to an application sandbox running in
891 * a specific user.
892 */
893 public static boolean isApplicationUid(int uid) {
894 return UserHandle.isApp(uid);
895 }
896
897 /**
898 * Returns whether the current process is in an isolated sandbox.
899 */
900 public static final boolean isIsolated() {
901 return isIsolated(myUid());
902 }
903
904 /**
905 * @deprecated Use {@link #isIsolatedUid(int)} instead.
906 * {@hide}
907 */
908 @Deprecated
909 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
910 publicAlternatives = "Use {@link #isIsolatedUid(int)} instead.")
911 public static final boolean isIsolated(int uid) {
912 return isIsolatedUid(uid);
913 }
914
915 /**
916 * Returns whether the process with the given {@code uid} is an isolated sandbox.
917 */
918 public static final boolean isIsolatedUid(int uid) {
919 uid = UserHandle.getAppId(uid);
920 return (uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID)
921 || (uid >= FIRST_APP_ZYGOTE_ISOLATED_UID && uid <= LAST_APP_ZYGOTE_ISOLATED_UID);
922 }
923
924 /**
925 * Returns whether the provided UID belongs to a SDK sandbox process.
926 *
927 * @hide
928 */
929 @SystemApi(client = MODULE_LIBRARIES)
930 @TestApi
931 public static final boolean isSdkSandboxUid(int uid) {
932 uid = UserHandle.getAppId(uid);
933 return (uid >= FIRST_SDK_SANDBOX_UID && uid <= LAST_SDK_SANDBOX_UID);
934 }
935
936 /**
937 *
938 * Returns the app process corresponding to an sdk sandbox process.
939 *
940 * @hide
941 */
942 @SystemApi(client = MODULE_LIBRARIES)
943 @TestApi
944 public static final int getAppUidForSdkSandboxUid(int uid) {
945 return uid - (FIRST_SDK_SANDBOX_UID - FIRST_APPLICATION_UID);
946 }
947
948 /**
949 *
950 * Returns the sdk sandbox process corresponding to an app process.
951 *
952 * @hide
953 */
954 @SystemApi(client = MODULE_LIBRARIES)
955 @TestApi
956 public static final int toSdkSandboxUid(int uid) {
957 return uid + (FIRST_SDK_SANDBOX_UID - FIRST_APPLICATION_UID);
958 }
959
960 /**
961 * Returns whether the current process is a sdk sandbox process.
962 */
963 public static final boolean isSdkSandbox() {
964 return isSdkSandboxUid(myUid());
965 }
966
967 /**
968 * Returns the UID assigned to a particular user name, or -1 if there is
969 * none. If the given string consists of only numbers, it is converted
970 * directly to a uid.
971 */
972 public static final native int getUidForName(String name);
973
974 /**
975 * Returns the GID assigned to a particular user name, or -1 if there is
976 * none. If the given string consists of only numbers, it is converted
977 * directly to a gid.
978 */
979 public static final native int getGidForName(String name);
980
981 /**
982 * Returns a uid for a currently running process.
983 * @param pid the process id
984 * @return the uid of the process, or -1 if the process is not running.
985 * @hide pending API council review
986 */
987 @UnsupportedAppUsage
988 public static final int getUidForPid(int pid) {
989 String[] procStatusLabels = { "Uid:" };
990 long[] procStatusValues = new long[1];
991 procStatusValues[0] = -1;
992 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
993 return (int) procStatusValues[0];
994 }
995
996 /**
997 * Returns the parent process id for a currently running process.
998 * @param pid the process id
999 * @return the parent process id of the process, or -1 if the process is not running.
1000 * @hide
1001 */
1002 @UnsupportedAppUsage
1003 public static final int getParentPid(int pid) {
1004 String[] procStatusLabels = { "PPid:" };
1005 long[] procStatusValues = new long[1];
1006 procStatusValues[0] = -1;
1007 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
1008 return (int) procStatusValues[0];
1009 }
1010
1011 /**
1012 * Returns the thread group leader id for a currently running thread.
1013 * @param tid the thread id
1014 * @return the thread group leader id of the thread, or -1 if the thread is not running.
1015 * This is same as what getpid(2) would return if called by tid.
1016 * @hide
1017 */
1018 public static final int getThreadGroupLeader(int tid) {
1019 String[] procStatusLabels = { "Tgid:" };
1020 long[] procStatusValues = new long[1];
1021 procStatusValues[0] = -1;
1022 Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
1023 return (int) procStatusValues[0];
1024 }
1025
1026 /**
1027 * Set the priority of a thread, based on Linux priorities.
1028 *
1029 * @param tid The identifier of the thread/process to change.
1030 * @param priority A Linux priority level, from -20 for highest scheduling
1031 * priority to 19 for lowest scheduling priority.
1032 *
1033 * @throws IllegalArgumentException Throws IllegalArgumentException if
1034 * <var>tid</var> does not exist.
1035 * @throws SecurityException Throws SecurityException if your process does
1036 * not have permission to modify the given thread, or to use the given
1037 * priority.
1038 */
1039 public static final native void setThreadPriority(int tid, int priority)
1040 throws IllegalArgumentException, SecurityException;
1041
1042 /**
1043 * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
1044 * throw an exception if passed a background-level thread priority. This is only
1045 * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
1046 *
1047 * @hide
1048 */
1049 public static final native void setCanSelfBackground(boolean backgroundOk);
1050
1051 /**
1052 * Sets the scheduling group for a thread.
1053 * @hide
1054 * @param tid The identifier of the thread to change.
1055 * @param group The target group for this thread from THREAD_GROUP_*.
1056 *
1057 * @throws IllegalArgumentException Throws IllegalArgumentException if
1058 * <var>tid</var> does not exist.
1059 * @throws SecurityException Throws SecurityException if your process does
1060 * not have permission to modify the given thread, or to use the given
1061 * priority.
1062 * If the thread is a thread group leader, that is it's gettid() == getpid(),
1063 * then the other threads in the same thread group are _not_ affected.
1064 *
1065 * Does not set cpuset for some historical reason, just calls
1066 * libcutils::set_sched_policy().
1067 */
1068 public static final native void setThreadGroup(int tid, int group)
1069 throws IllegalArgumentException, SecurityException;
1070
1071 /**
1072 * Sets the scheduling group and the corresponding cpuset group
1073 * @hide
1074 * @param tid The identifier of the thread to change.
1075 * @param group The target group for this thread from THREAD_GROUP_*.
1076 *
1077 * @throws IllegalArgumentException Throws IllegalArgumentException if
1078 * <var>tid</var> does not exist.
1079 * @throws SecurityException Throws SecurityException if your process does
1080 * not have permission to modify the given thread, or to use the given
1081 * priority.
1082 */
1083 public static final native void setThreadGroupAndCpuset(int tid, int group)
1084 throws IllegalArgumentException, SecurityException;
1085
1086 /**
1087 * Sets the scheduling group for a process and all child threads
1088 * @hide
1089 * @param pid The identifier of the process to change.
1090 * @param group The target group for this process from THREAD_GROUP_*.
1091 *
1092 * @throws IllegalArgumentException Throws IllegalArgumentException if
1093 * <var>tid</var> does not exist.
1094 * @throws SecurityException Throws SecurityException if your process does
1095 * not have permission to modify the given thread, or to use the given
1096 * priority.
1097 *
1098 * group == THREAD_GROUP_DEFAULT means to move all non-background priority
1099 * threads to the foreground scheduling group, but to leave background
1100 * priority threads alone. group == THREAD_GROUP_BACKGROUND moves all
1101 * threads, regardless of priority, to the background scheduling group.
1102 * group == THREAD_GROUP_FOREGROUND is not allowed.
1103 *
1104 * Always sets cpusets.
1105 */
1106 @UnsupportedAppUsage
1107 public static final native void setProcessGroup(int pid, int group)
1108 throws IllegalArgumentException, SecurityException;
1109
1110 /**
1111 * Freeze or unfreeze the specified process.
1112 *
1113 * @param pid Identifier of the process to freeze or unfreeze.
1114 * @param uid Identifier of the user the process is running under.
1115 * @param frozen Specify whether to free (true) or unfreeze (false).
1116 *
1117 * @hide
1118 */
1119 public static final native void setProcessFrozen(int pid, int uid, boolean frozen);
1120
1121 /**
1122 * Enable or disable the freezer. When enable == false all frozen processes are unfrozen,
1123 * but aren't removed from the freezer. While in this state, processes can be added or removed
1124 * by using setProcessFrozen, but they won't actually be frozen until the freezer is enabled
1125 * again. If enable == true the freezer is enabled again, and all processes
1126 * in the freezer (including the ones added while the freezer was disabled) are frozen.
1127 *
1128 * @param enable Specify whether to enable (true) or disable (false) the freezer.
1129 *
1130 * @hide
1131 */
1132 public static final native void enableFreezer(boolean enable);
1133
1134 /**
1135 * Return the scheduling group of requested process.
1136 *
1137 * @hide
1138 */
1139 public static final native int getProcessGroup(int pid)
1140 throws IllegalArgumentException, SecurityException;
1141
1142 /**
1143 *
1144 * Create a new process group in the cgroup uid/pid hierarchy
1145 *
1146 * @return <0 in case of error
1147 *
1148 * @hide
1149 */
1150 public static final native int createProcessGroup(int uid, int pid);
1151
1152 /**
1153 * On some devices, the foreground process may have one or more CPU
1154 * cores exclusively reserved for it. This method can be used to
1155 * retrieve which cores that are (if any), so the calling process
1156 * can then use sched_setaffinity() to lock a thread to these cores.
1157 * Note that the calling process must currently be running in the
1158 * foreground for this method to return any cores.
1159 *
1160 * The CPU core(s) exclusively reserved for the foreground process will
1161 * stay reserved for as long as the process stays in the foreground.
1162 *
1163 * As soon as a process leaves the foreground, those CPU cores will
1164 * no longer be reserved for it, and will most likely be reserved for
1165 * the new foreground process. It's not necessary to change the affinity
1166 * of your process when it leaves the foreground (if you had previously
1167 * set it to use a reserved core); the OS will automatically take care
1168 * of resetting the affinity at that point.
1169 *
1170 * @return an array of integers, indicating the CPU cores exclusively
1171 * reserved for this process. The array will have length zero if no
1172 * CPU cores are exclusively reserved for this process at this point
1173 * in time.
1174 */
1175 public static final native int[] getExclusiveCores();
1176
1177 /**
1178 * Set the priority of the calling thread, based on Linux priorities. See
1179 * {@link #setThreadPriority(int, int)} for more information.
1180 *
1181 * @param priority A Linux priority level, from -20 for highest scheduling
1182 * priority to 19 for lowest scheduling priority.
1183 *
1184 * @throws IllegalArgumentException Throws IllegalArgumentException if
1185 * <var>tid</var> does not exist.
1186 * @throws SecurityException Throws SecurityException if your process does
1187 * not have permission to modify the given thread, or to use the given
1188 * priority.
1189 *
1190 * @see #setThreadPriority(int, int)
1191 */
1192 public static final native void setThreadPriority(int priority)
1193 throws IllegalArgumentException, SecurityException;
1194
1195 /**
1196 * Return the current priority of a thread, based on Linux priorities.
1197 *
1198 * @param tid The identifier of the thread/process. If tid equals zero, the priority of the
1199 * calling process/thread will be returned.
1200 *
1201 * @return Returns the current priority, as a Linux priority level,
1202 * from -20 for highest scheduling priority to 19 for lowest scheduling
1203 * priority.
1204 *
1205 * @throws IllegalArgumentException Throws IllegalArgumentException if
1206 * <var>tid</var> does not exist.
1207 */
1208 public static final native int getThreadPriority(int tid)
1209 throws IllegalArgumentException;
1210
1211 /**
1212 * Return the current scheduling policy of a thread, based on Linux.
1213 *
1214 * @param tid The identifier of the thread/process to get the scheduling policy.
1215 *
1216 * @throws IllegalArgumentException Throws IllegalArgumentException if
1217 * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
1218 * @throws SecurityException Throws SecurityException if your process does
1219 * not have permission to modify the given thread, or to use the given
1220 * scheduling policy or priority.
1221 *
1222 * {@hide}
1223 */
1224
1225 @TestApi
1226 public static final native int getThreadScheduler(int tid)
1227 throws IllegalArgumentException;
1228
1229 /**
1230 * Set the scheduling policy and priority of a thread, based on Linux.
1231 *
1232 * @param tid The identifier of the thread/process to change.
1233 * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
1234 * @param priority A Linux priority level in a range appropriate for the given policy.
1235 *
1236 * @throws IllegalArgumentException Throws IllegalArgumentException if
1237 * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
1238 * @throws SecurityException Throws SecurityException if your process does
1239 * not have permission to modify the given thread, or to use the given
1240 * scheduling policy or priority.
1241 *
1242 * {@hide}
1243 */
1244
1245 public static final native void setThreadScheduler(int tid, int policy, int priority)
1246 throws IllegalArgumentException;
1247
1248 /**
1249 * Determine whether the current environment supports multiple processes.
1250 *
1251 * @return Returns true if the system can run in multiple processes, else
1252 * false if everything is running in a single process.
1253 *
1254 * @deprecated This method always returns true. Do not use.
1255 */
1256 @Deprecated
1257 public static final boolean supportsProcesses() {
1258 return true;
1259 }
1260
1261 /**
1262 * Adjust the swappiness level for a process.
1263 *
1264 * @param pid The process identifier to set.
1265 * @param is_increased Whether swappiness should be increased or default.
1266 *
1267 * @return Returns true if the underlying system supports this
1268 * feature, else false.
1269 *
1270 * {@hide}
1271 */
1272 public static final native boolean setSwappiness(int pid, boolean is_increased);
1273
1274 /**
1275 * Change this process's argv[0] parameter. This can be useful to show
1276 * more descriptive information in things like the 'ps' command.
1277 *
1278 * @param text The new name of this process.
1279 *
1280 * {@hide}
1281 */
1282 @UnsupportedAppUsage(maxTargetSdk = VERSION_CODES.S, publicAlternatives = "Do not try to "
1283 + "change the process name. (If you must, you could use {@code pthread_setname_np(3)}, "
1284 + "but this could confuse the system)")
1285 public static void setArgV0(@NonNull String text) {
1286 sArgV0 = text;
1287 setArgV0Native(text);
1288 }
1289
1290 private static native void setArgV0Native(String text);
1291
1292 /**
1293 * Return the name of this process. By default, the process name is the same as the app's
1294 * package name, but this can be changed using {@code android:process}.
1295 */
1296 @NonNull
1297 public static String myProcessName() {
1298 // Note this could be different from the actual process name if someone changes the
1299 // process name using native code (using pthread_setname_np()). But sArgV0
1300 // is the name that the system thinks this process has.
1301 return sArgV0;
1302 }
1303
1304 /**
1305 * Kill the process with the given PID.
1306 * Note that, though this API allows us to request to
1307 * kill any process based on its PID, the kernel will
1308 * still impose standard restrictions on which PIDs you
1309 * are actually able to kill. Typically this means only
1310 * the process running the caller's packages/application
1311 * and any additional processes created by that app; packages
1312 * sharing a common UID will also be able to kill each
1313 * other's processes.
1314 */
1315 public static final void killProcess(int pid) {
1316 sendSignal(pid, SIGNAL_KILL);
1317 }
1318
1319 /** @hide */
1320 public static final native int setUid(int uid);
1321
1322 /** @hide */
1323 public static final native int setGid(int uid);
1324
1325 /**
1326 * Send a signal to the given process.
1327 *
1328 * @param pid The pid of the target process.
1329 * @param signal The signal to send.
1330 */
1331 public static final native void sendSignal(int pid, int signal);
1332
1333 /**
1334 * @hide
1335 * Private impl for avoiding a log message... DO NOT USE without doing
1336 * your own log, or the Android Illuminati will find you some night and
1337 * beat you up.
1338 */
1339 public static final void killProcessQuiet(int pid) {
1340 sendSignalQuiet(pid, SIGNAL_KILL);
1341 }
1342
1343 /**
1344 * @hide
1345 * Private impl for avoiding a log message... DO NOT USE without doing
1346 * your own log, or the Android Illuminati will find you some night and
1347 * beat you up.
1348 */
1349 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
1350 public static final native void sendSignalQuiet(int pid, int signal);
1351
1352 /**
1353 * @return The advertised memory of the system, as the end user would encounter in a retail
1354 * display environment. If the advertised memory is not defined, it returns
1355 * {@code getTotalMemory()} rounded.
1356 *
1357 * @hide
1358 */
1359 public static final long getAdvertisedMem() {
1360 String formatSize = MemoryProperties.memory_ddr_size().orElse("0KB");
1361 long memSize = FileUtils.parseSize(formatSize);
1362
1363 if (memSize == Long.MIN_VALUE) {
1364 return FileUtils.roundStorageSize(getTotalMemory());
1365 }
1366
1367 return memSize;
1368 }
1369
1370 /** @hide */
1371 @UnsupportedAppUsage
1372 public static final native long getFreeMemory();
1373
1374 /** @hide */
1375 @UnsupportedAppUsage
1376 public static final native long getTotalMemory();
1377
1378 /** @hide */
1379 @UnsupportedAppUsage
1380 public static final native void readProcLines(String path,
1381 String[] reqFields, long[] outSizes);
1382
1383 /** @hide */
1384 @UnsupportedAppUsage
1385 public static final native int[] getPids(String path, int[] lastArray);
1386
1387 /** @hide */
1388 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1389 public static final int PROC_TERM_MASK = 0xff;
1390 /** @hide */
1391 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1392 public static final int PROC_ZERO_TERM = 0;
1393 /** @hide */
1394 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1395 public static final int PROC_SPACE_TERM = (int)' ';
1396 /** @hide */
1397 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1398 public static final int PROC_TAB_TERM = (int)'\t';
1399 /** @hide */
1400 public static final int PROC_NEWLINE_TERM = (int) '\n';
1401 /** @hide */
1402 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1403 public static final int PROC_COMBINE = 0x100;
1404 /** @hide */
1405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1406 public static final int PROC_PARENS = 0x200;
1407 /** @hide */
1408 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1409 public static final int PROC_QUOTES = 0x400;
1410 /** @hide */
1411 public static final int PROC_CHAR = 0x800;
1412 /** @hide */
1413 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1414 public static final int PROC_OUT_STRING = 0x1000;
1415 /** @hide */
1416 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1417 public static final int PROC_OUT_LONG = 0x2000;
1418 /** @hide */
1419 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1420 public static final int PROC_OUT_FLOAT = 0x4000;
1421
1422 /**
1423 * Read and parse a {@code proc} file in the given format.
1424 *
1425 * <p>The format is a list of integers, where every integer describes a variable in the file. It
1426 * specifies how the variable is syntactically terminated (e.g. {@link Process#PROC_SPACE_TERM},
1427 * {@link Process#PROC_TAB_TERM}, {@link Process#PROC_ZERO_TERM}, {@link
1428 * Process#PROC_NEWLINE_TERM}).
1429 *
1430 * <p>If the variable should be parsed and returned to the caller, the termination type should
1431 * be binary OR'd with the type of output (e.g. {@link Process#PROC_OUT_STRING}, {@link
1432 * Process#PROC_OUT_LONG}, {@link Process#PROC_OUT_FLOAT}.
1433 *
1434 * <p>If the variable is wrapped in quotation marks it should be binary OR'd with {@link
1435 * Process#PROC_QUOTES}. If the variable is wrapped in parentheses it should be binary OR'd with
1436 * {@link Process#PROC_PARENS}.
1437 *
1438 * <p>If the variable is not formatted as a string and should be cast directly from characters
1439 * to a long, the {@link Process#PROC_CHAR} integer should be binary OR'd.
1440 *
1441 * <p>If the terminating character can be repeated, the {@link Process#PROC_COMBINE} integer
1442 * should be binary OR'd.
1443 *
1444 * @param file the path of the {@code proc} file to read
1445 * @param format the format of the file
1446 * @param outStrings the parsed {@code String}s from the file
1447 * @param outLongs the parsed {@code long}s from the file
1448 * @param outFloats the parsed {@code float}s from the file
1449 * @hide
1450 */
1451 @UnsupportedAppUsage
1452 public static final native boolean readProcFile(String file, int[] format,
1453 String[] outStrings, long[] outLongs, float[] outFloats);
1454
1455 /** @hide */
1456 @UnsupportedAppUsage
1457 public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1458 int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1459
1460 /** @hide */
1461 @UnsupportedAppUsage
1462 public static final native int[] getPidsForCommands(String[] cmds);
1463
1464 /**
1465 * Gets the total Pss value for a given process, in bytes.
1466 *
1467 * @param pid the process to the Pss for
1468 * @return the total Pss value for the given process in bytes,
1469 * or -1 if the value cannot be determined
1470 * @hide
1471 */
1472 @UnsupportedAppUsage
1473 public static final native long getPss(int pid);
1474
1475 /** @hide */
1476 public static final native long[] getRss(int pid);
1477
1478 /**
1479 * Specifies the outcome of having started a process.
1480 * @hide
1481 */
1482 public static final class ProcessStartResult {
1483 /**
1484 * The PID of the newly started process.
1485 * Always >= 0. (If the start failed, an exception will have been thrown instead.)
1486 */
1487 public int pid;
1488
1489 /**
1490 * True if the process was started with a wrapper attached.
1491 */
1492 public boolean usingWrapper;
1493 }
1494
1495 /**
1496 * Kill all processes in a process group started for the given
1497 * pid.
1498 * @hide
1499 */
1500 public static final native int killProcessGroup(int uid, int pid);
1501
1502 /**
1503 * Remove all process groups. Expected to be called when ActivityManager
1504 * is restarted.
1505 * @hide
1506 */
1507 public static final native void removeAllProcessGroups();
1508
1509 /**
1510 * Check to see if a thread belongs to a given process. This may require
1511 * more permissions than apps generally have.
1512 * @return true if this thread belongs to a process
1513 * @hide
1514 */
1515 public static final boolean isThreadInProcess(int tid, int pid) {
1516 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
1517 try {
1518 if (Os.access("/proc/" + tid + "/task/" + pid, OsConstants.F_OK)) {
1519 return true;
1520 } else {
1521 return false;
1522 }
1523 } catch (Exception e) {
1524 return false;
1525 } finally {
1526 StrictMode.setThreadPolicy(oldPolicy);
1527 }
1528
1529 }
1530
1531 /**
1532 * Wait for the death of the given process.
1533 *
1534 * @param pid The process ID to be waited on
1535 * @param timeout The maximum time to wait in milliseconds, or -1 to wait forever
1536 * @hide
1537 */
1538 public static void waitForProcessDeath(int pid, int timeout)
1539 throws InterruptedException, TimeoutException {
1540 boolean fallback = supportsPidFd();
1541 if (!fallback) {
1542 FileDescriptor pidfd = null;
1543 try {
1544 final int fd = nativePidFdOpen(pid, 0);
1545 if (fd >= 0) {
1546 pidfd = new FileDescriptor();
1547 pidfd.setInt$(fd);
1548 } else {
1549 fallback = true;
1550 }
1551 if (pidfd != null) {
1552 StructPollfd[] fds = new StructPollfd[] {
1553 new StructPollfd()
1554 };
1555 fds[0].fd = pidfd;
1556 fds[0].events = (short) OsConstants.POLLIN;
1557 fds[0].revents = 0;
1558 fds[0].userData = null;
1559 int res = Os.poll(fds, timeout);
1560 if (res > 0) {
1561 return;
1562 } else if (res == 0) {
1563 throw new TimeoutException();
1564 } else {
1565 // We should get an ErrnoException now
1566 }
1567 }
1568 } catch (ErrnoException e) {
1569 if (e.errno == OsConstants.EINTR) {
1570 throw new InterruptedException();
1571 }
1572 fallback = true;
1573 } finally {
1574 if (pidfd != null) {
1575 IoUtils.closeQuietly(pidfd);
1576 }
1577 }
1578 }
1579 if (fallback) {
1580 boolean infinity = timeout < 0;
1581 long now = System.currentTimeMillis();
1582 final long end = now + timeout;
1583 while (infinity || now < end) {
1584 try {
1585 Os.kill(pid, 0);
1586 } catch (ErrnoException e) {
1587 if (e.errno == OsConstants.ESRCH) {
1588 return;
1589 }
1590 }
1591 Thread.sleep(1);
1592 now = System.currentTimeMillis();
1593 }
1594 }
1595 throw new TimeoutException();
1596 }
1597
1598 /**
1599 * Determine whether the system supports pidfd APIs
1600 *
1601 * @return Returns true if the system supports pidfd APIs
1602 * @hide
1603 */
1604 public static boolean supportsPidFd() {
1605 if (sPidFdSupported == PIDFD_UNKNOWN) {
1606 int fd = -1;
1607 try {
1608 fd = nativePidFdOpen(myPid(), 0);
1609 sPidFdSupported = PIDFD_SUPPORTED;
1610 } catch (ErrnoException e) {
1611 sPidFdSupported = e.errno != OsConstants.ENOSYS
1612 ? PIDFD_SUPPORTED : PIDFD_UNSUPPORTED;
1613 } finally {
1614 if (fd >= 0) {
1615 final FileDescriptor f = new FileDescriptor();
1616 f.setInt$(fd);
1617 IoUtils.closeQuietly(f);
1618 }
1619 }
1620 }
1621 return sPidFdSupported == PIDFD_SUPPORTED;
1622 }
1623
1624 /**
1625 * Open process file descriptor for given pid.
1626 *
1627 * @param pid The process ID to open for
1628 * @param flags Reserved, unused now, must be 0
1629 * @return The process file descriptor for given pid
1630 * @throws IOException if it can't be opened
1631 *
1632 * @hide
1633 */
1634 public static @Nullable FileDescriptor openPidFd(int pid, int flags) throws IOException {
1635 if (!supportsPidFd()) {
1636 return null;
1637 }
1638 if (flags != 0) {
1639 throw new IllegalArgumentException();
1640 }
1641 try {
1642 FileDescriptor pidfd = new FileDescriptor();
1643 pidfd.setInt$(nativePidFdOpen(pid, flags));
1644 return pidfd;
1645 } catch (ErrnoException e) {
1646 IOException ex = new IOException();
1647 ex.initCause(e);
1648 throw ex;
1649 }
1650 }
1651
1652 private static native int nativePidFdOpen(int pid, int flags) throws ErrnoException;
1653 }