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