• 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.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 NetworkStack app.
218      * @hide
219      */
220     public static final int NETWORK_STACK_UID = 1073;
221 
222     /**
223      * Defines the UID/GID for fs-verity certificate ownership in keystore.
224      * @hide
225      */
226     public static final int FSVERITY_CERT_UID = 1075;
227 
228     /**
229      * GID that gives access to USB OTG (unreliable) volumes on /mnt/media_rw/<vol name>
230      * @hide
231      */
232     public static final int EXTERNAL_STORAGE_GID = 1077;
233 
234     /**
235      * GID that gives write access to app-private data directories on external
236      * storage (used on devices without sdcardfs only).
237      * @hide
238      */
239     public static final int EXT_DATA_RW_GID = 1078;
240 
241     /**
242      * GID that gives write access to app-private OBB directories on external
243      * storage (used on devices without sdcardfs only).
244      * @hide
245      */
246     public static final int EXT_OBB_RW_GID = 1079;
247 
248     /**
249      * Defines the UID/GID for the Uwb service process.
250      * @hide
251      */
252     public static final int UWB_UID = 1083;
253 
254     /**
255      * Defines a virtual UID that is used to aggregate data related to SDK sandbox UIDs.
256      * {@see SdkSandboxManager}
257      * @hide
258      */
259     @TestApi
260     public static final int SDK_SANDBOX_VIRTUAL_UID = 1090;
261 
262     /**
263      * GID that corresponds to the INTERNET permission.
264      * Must match the value of AID_INET.
265      * @hide
266      */
267     public static final int INET_GID = 3003;
268 
269     /** {@hide} */
270     public static final int NOBODY_UID = 9999;
271 
272     /**
273      * Defines the start of a range of UIDs (and GIDs), going from this
274      * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
275      * to applications.
276      */
277     public static final int FIRST_APPLICATION_UID = 10000;
278 
279     /**
280      * Last of application-specific UIDs starting at
281      * {@link #FIRST_APPLICATION_UID}.
282      */
283     public static final int LAST_APPLICATION_UID = 19999;
284 
285     /**
286      * Defines the start of a range of UIDs going from this number to
287      * {@link #LAST_SDK_SANDBOX_UID} that are reserved for assigning to
288      * sdk sandbox processes. There is a 1-1 mapping between a sdk sandbox
289      * process UID and the app that it belongs to, which can be computed by
290      * subtracting (FIRST_SDK_SANDBOX_UID - FIRST_APPLICATION_UID) from the
291      * uid of a sdk sandbox process.
292      *
293      * Note that there are no GIDs associated with these processes; storage
294      * attribution for them will be done using project IDs.
295      * @hide
296      */
297     public static final int FIRST_SDK_SANDBOX_UID = 20000;
298 
299     /**
300      * Last UID that is used for sdk sandbox processes.
301      * @hide
302      */
303     public static final int LAST_SDK_SANDBOX_UID = 29999;
304 
305     /**
306      * First uid used for fully isolated sandboxed processes spawned from an app zygote
307      * @hide
308      */
309     @TestApi
310     public static final int FIRST_APP_ZYGOTE_ISOLATED_UID = 90000;
311 
312     /**
313      * Number of UIDs we allocate per application zygote
314      * @hide
315      */
316     @TestApi
317     public static final int NUM_UIDS_PER_APP_ZYGOTE = 100;
318 
319     /**
320      * Last uid used for fully isolated sandboxed processes spawned from an app zygote
321      * @hide
322      */
323     @TestApi
324     public static final int LAST_APP_ZYGOTE_ISOLATED_UID = 98999;
325 
326     /**
327      * First uid used for fully isolated sandboxed processes (with no permissions of their own)
328      * @hide
329      */
330     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
331     @TestApi
332     public static final int FIRST_ISOLATED_UID = 99000;
333 
334     /**
335      * Last uid used for fully isolated sandboxed processes (with no permissions of their own)
336      * @hide
337      */
338     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
339     @TestApi
340     public static final int LAST_ISOLATED_UID = 99999;
341 
342     /**
343      * Defines the gid shared by all applications running under the same profile.
344      * @hide
345      */
346     public static final int SHARED_USER_GID = 9997;
347 
348     /**
349      * First gid for applications to share resources. Used when forward-locking
350      * is enabled but all UserHandles need to be able to read the resources.
351      * @hide
352      */
353     public static final int FIRST_SHARED_APPLICATION_GID = 50000;
354 
355     /**
356      * Last gid for applications to share resources. Used when forward-locking
357      * is enabled but all UserHandles need to be able to read the resources.
358      * @hide
359      */
360     public static final int LAST_SHARED_APPLICATION_GID = 59999;
361 
362     /** {@hide} */
363     public static final int FIRST_APPLICATION_CACHE_GID = 20000;
364     /** {@hide} */
365     public static final int LAST_APPLICATION_CACHE_GID = 29999;
366 
367     /**
368      * An invalid PID value.
369      */
370     public static final int INVALID_PID = -1;
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     /**
904      * @deprecated Use {@link #isIsolatedUid(int)} instead.
905      * {@hide}
906      */
907     @Deprecated
908     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
909             publicAlternatives = "Use {@link #isIsolatedUid(int)} instead.")
isIsolated(int uid)910     public static final boolean isIsolated(int uid) {
911         return isIsolatedUid(uid);
912     }
913 
914     /**
915      * Returns whether the process with the given {@code uid} is an isolated sandbox.
916      */
isIsolatedUid(int uid)917     public static final boolean isIsolatedUid(int uid) {
918         uid = UserHandle.getAppId(uid);
919         return (uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID)
920                 || (uid >= FIRST_APP_ZYGOTE_ISOLATED_UID && uid <= LAST_APP_ZYGOTE_ISOLATED_UID);
921     }
922 
923     /**
924      * Returns whether the provided UID belongs to a SDK sandbox process.
925      *
926      * @hide
927      */
928     @SystemApi(client = MODULE_LIBRARIES)
929     @TestApi
isSdkSandboxUid(int uid)930     public static final boolean isSdkSandboxUid(int uid) {
931         uid = UserHandle.getAppId(uid);
932         return (uid >= FIRST_SDK_SANDBOX_UID && uid <= LAST_SDK_SANDBOX_UID);
933     }
934 
935     /**
936      *
937      * Returns the app process corresponding to an sdk sandbox process.
938      *
939      * @hide
940      */
941     @SystemApi(client = MODULE_LIBRARIES)
942     @TestApi
getAppUidForSdkSandboxUid(int uid)943     public static final int getAppUidForSdkSandboxUid(int uid) {
944         return uid - (FIRST_SDK_SANDBOX_UID - FIRST_APPLICATION_UID);
945     }
946 
947     /**
948      *
949      * Returns the sdk sandbox process corresponding to an app process.
950      *
951      * @hide
952      */
953     @SystemApi(client = MODULE_LIBRARIES)
954     @TestApi
toSdkSandboxUid(int uid)955     public static final int toSdkSandboxUid(int uid) {
956         return uid + (FIRST_SDK_SANDBOX_UID - FIRST_APPLICATION_UID);
957     }
958 
959     /**
960      * Returns whether the current process is a sdk sandbox process.
961      */
isSdkSandbox()962     public static final boolean isSdkSandbox() {
963         return isSdkSandboxUid(myUid());
964     }
965 
966     /**
967      * Returns the UID assigned to a particular user name, or -1 if there is
968      * none.  If the given string consists of only numbers, it is converted
969      * directly to a uid.
970      */
getUidForName(String name)971     public static final native int getUidForName(String name);
972 
973     /**
974      * Returns the GID assigned to a particular user name, or -1 if there is
975      * none.  If the given string consists of only numbers, it is converted
976      * directly to a gid.
977      */
getGidForName(String name)978     public static final native int getGidForName(String name);
979 
980     /**
981      * Returns a uid for a currently running process.
982      * @param pid the process id
983      * @return the uid of the process, or -1 if the process is not running.
984      * @hide pending API council review
985      */
986     @UnsupportedAppUsage
getUidForPid(int pid)987     public static final int getUidForPid(int pid) {
988         String[] procStatusLabels = { "Uid:" };
989         long[] procStatusValues = new long[1];
990         procStatusValues[0] = -1;
991         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
992         return (int) procStatusValues[0];
993     }
994 
995     /**
996      * Returns the parent process id for a currently running process.
997      * @param pid the process id
998      * @return the parent process id of the process, or -1 if the process is not running.
999      * @hide
1000      */
1001     @UnsupportedAppUsage
getParentPid(int pid)1002     public static final int getParentPid(int pid) {
1003         String[] procStatusLabels = { "PPid:" };
1004         long[] procStatusValues = new long[1];
1005         procStatusValues[0] = -1;
1006         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
1007         return (int) procStatusValues[0];
1008     }
1009 
1010     /**
1011      * Returns the thread group leader id for a currently running thread.
1012      * @param tid the thread id
1013      * @return the thread group leader id of the thread, or -1 if the thread is not running.
1014      *         This is same as what getpid(2) would return if called by tid.
1015      * @hide
1016      */
getThreadGroupLeader(int tid)1017     public static final int getThreadGroupLeader(int tid) {
1018         String[] procStatusLabels = { "Tgid:" };
1019         long[] procStatusValues = new long[1];
1020         procStatusValues[0] = -1;
1021         Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
1022         return (int) procStatusValues[0];
1023     }
1024 
1025     /**
1026      * Set the priority of a thread, based on Linux priorities.
1027      *
1028      * @param tid The identifier of the thread/process to change.
1029      * @param priority A Linux priority level, from -20 for highest scheduling
1030      * priority to 19 for lowest scheduling priority.
1031      *
1032      * @throws IllegalArgumentException Throws IllegalArgumentException if
1033      * <var>tid</var> does not exist.
1034      * @throws SecurityException Throws SecurityException if your process does
1035      * not have permission to modify the given thread, or to use the given
1036      * priority.
1037      */
setThreadPriority(int tid, int priority)1038     public static final native void setThreadPriority(int tid, int priority)
1039             throws IllegalArgumentException, SecurityException;
1040 
1041     /**
1042      * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
1043      * throw an exception if passed a background-level thread priority.  This is only
1044      * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
1045      *
1046      * @hide
1047      */
setCanSelfBackground(boolean backgroundOk)1048     public static final native void setCanSelfBackground(boolean backgroundOk);
1049 
1050     /**
1051      * Sets the scheduling group for a thread.
1052      * @hide
1053      * @param tid The identifier of the thread to change.
1054      * @param group The target group for this thread from THREAD_GROUP_*.
1055      *
1056      * @throws IllegalArgumentException Throws IllegalArgumentException if
1057      * <var>tid</var> does not exist.
1058      * @throws SecurityException Throws SecurityException if your process does
1059      * not have permission to modify the given thread, or to use the given
1060      * priority.
1061      * If the thread is a thread group leader, that is it's gettid() == getpid(),
1062      * then the other threads in the same thread group are _not_ affected.
1063      *
1064      * Does not set cpuset for some historical reason, just calls
1065      * libcutils::set_sched_policy().
1066      */
setThreadGroup(int tid, int group)1067     public static final native void setThreadGroup(int tid, int group)
1068             throws IllegalArgumentException, SecurityException;
1069 
1070     /**
1071      * Sets the scheduling group and the corresponding cpuset group
1072      * @hide
1073      * @param tid The identifier of the thread to change.
1074      * @param group The target group for this thread from THREAD_GROUP_*.
1075      *
1076      * @throws IllegalArgumentException Throws IllegalArgumentException if
1077      * <var>tid</var> does not exist.
1078      * @throws SecurityException Throws SecurityException if your process does
1079      * not have permission to modify the given thread, or to use the given
1080      * priority.
1081      */
setThreadGroupAndCpuset(int tid, int group)1082     public static final native void setThreadGroupAndCpuset(int tid, int group)
1083             throws IllegalArgumentException, SecurityException;
1084 
1085     /**
1086      * Sets the scheduling group for a process and all child threads
1087      * @hide
1088      * @param pid The identifier of the process to change.
1089      * @param group The target group for this process from THREAD_GROUP_*.
1090      *
1091      * @throws IllegalArgumentException Throws IllegalArgumentException if
1092      * <var>tid</var> does not exist.
1093      * @throws SecurityException Throws SecurityException if your process does
1094      * not have permission to modify the given thread, or to use the given
1095      * priority.
1096      *
1097      * group == THREAD_GROUP_DEFAULT means to move all non-background priority
1098      * threads to the foreground scheduling group, but to leave background
1099      * priority threads alone.  group == THREAD_GROUP_BACKGROUND moves all
1100      * threads, regardless of priority, to the background scheduling group.
1101      * group == THREAD_GROUP_FOREGROUND is not allowed.
1102      *
1103      * Always sets cpusets.
1104      */
1105     @UnsupportedAppUsage
setProcessGroup(int pid, int group)1106     public static final native void setProcessGroup(int pid, int group)
1107             throws IllegalArgumentException, SecurityException;
1108 
1109     /**
1110      * Freeze or unfreeze the specified process.
1111      *
1112      * @param pid Identifier of the process to freeze or unfreeze.
1113      * @param uid Identifier of the user the process is running under.
1114      * @param frozen Specify whether to free (true) or unfreeze (false).
1115      *
1116      * @hide
1117      */
setProcessFrozen(int pid, int uid, boolean frozen)1118     public static final native void setProcessFrozen(int pid, int uid, boolean frozen);
1119 
1120     /**
1121      * Enable or disable the freezer. When enable == false all frozen processes are unfrozen,
1122      * but aren't removed from the freezer. While in this state, processes can be added or removed
1123      * by using setProcessFrozen, but they won't actually be frozen until the freezer is enabled
1124      * again. If enable == true the freezer is enabled again, and all processes
1125      * in the freezer (including the ones added while the freezer was disabled) are frozen.
1126      *
1127      * @param enable Specify whether to enable (true) or disable (false) the freezer.
1128      *
1129      * @hide
1130      */
enableFreezer(boolean enable)1131     public static final native void enableFreezer(boolean enable);
1132 
1133     /**
1134      * Return the scheduling group of requested process.
1135      *
1136      * @hide
1137      */
getProcessGroup(int pid)1138     public static final native int getProcessGroup(int pid)
1139             throws IllegalArgumentException, SecurityException;
1140 
1141     /**
1142      *
1143      * Create a new process group in the cgroup uid/pid hierarchy
1144      *
1145      * @return <0 in case of error
1146      *
1147      * @hide
1148      */
createProcessGroup(int uid, int pid)1149     public static final native int createProcessGroup(int uid, int pid);
1150 
1151     /**
1152      * On some devices, the foreground process may have one or more CPU
1153      * cores exclusively reserved for it. This method can be used to
1154      * retrieve which cores that are (if any), so the calling process
1155      * can then use sched_setaffinity() to lock a thread to these cores.
1156      * Note that the calling process must currently be running in the
1157      * foreground for this method to return any cores.
1158      *
1159      * The CPU core(s) exclusively reserved for the foreground process will
1160      * stay reserved for as long as the process stays in the foreground.
1161      *
1162      * As soon as a process leaves the foreground, those CPU cores will
1163      * no longer be reserved for it, and will most likely be reserved for
1164      * the new foreground process. It's not necessary to change the affinity
1165      * of your process when it leaves the foreground (if you had previously
1166      * set it to use a reserved core); the OS will automatically take care
1167      * of resetting the affinity at that point.
1168      *
1169      * @return an array of integers, indicating the CPU cores exclusively
1170      * reserved for this process. The array will have length zero if no
1171      * CPU cores are exclusively reserved for this process at this point
1172      * in time.
1173      */
getExclusiveCores()1174     public static final native int[] getExclusiveCores();
1175 
1176     /**
1177      * Set the priority of the calling thread, based on Linux priorities.  See
1178      * {@link #setThreadPriority(int, int)} for more information.
1179      *
1180      * @param priority A Linux priority level, from -20 for highest scheduling
1181      * priority to 19 for lowest scheduling priority.
1182      *
1183      * @throws IllegalArgumentException Throws IllegalArgumentException if
1184      * <var>tid</var> does not exist.
1185      * @throws SecurityException Throws SecurityException if your process does
1186      * not have permission to modify the given thread, or to use the given
1187      * priority.
1188      *
1189      * @see #setThreadPriority(int, int)
1190      */
setThreadPriority(int priority)1191     public static final native void setThreadPriority(int priority)
1192             throws IllegalArgumentException, SecurityException;
1193 
1194     /**
1195      * Return the current priority of a thread, based on Linux priorities.
1196      *
1197      * @param tid The identifier of the thread/process. If tid equals zero, the priority of the
1198      * calling process/thread will be returned.
1199      *
1200      * @return Returns the current priority, as a Linux priority level,
1201      * from -20 for highest scheduling priority to 19 for lowest scheduling
1202      * priority.
1203      *
1204      * @throws IllegalArgumentException Throws IllegalArgumentException if
1205      * <var>tid</var> does not exist.
1206      */
getThreadPriority(int tid)1207     public static final native int getThreadPriority(int tid)
1208             throws IllegalArgumentException;
1209 
1210     /**
1211      * Return the current scheduling policy of a thread, based on Linux.
1212      *
1213      * @param tid The identifier of the thread/process to get the scheduling policy.
1214      *
1215      * @throws IllegalArgumentException Throws IllegalArgumentException if
1216      * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
1217      * @throws SecurityException Throws SecurityException if your process does
1218      * not have permission to modify the given thread, or to use the given
1219      * scheduling policy or priority.
1220      *
1221      * {@hide}
1222      */
1223 
1224     @TestApi
getThreadScheduler(int tid)1225     public static final native int getThreadScheduler(int tid)
1226             throws IllegalArgumentException;
1227 
1228     /**
1229      * Set the scheduling policy and priority of a thread, based on Linux.
1230      *
1231      * @param tid The identifier of the thread/process to change.
1232      * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
1233      * @param priority A Linux priority level in a range appropriate for the given policy.
1234      *
1235      * @throws IllegalArgumentException Throws IllegalArgumentException if
1236      * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
1237      * @throws SecurityException Throws SecurityException if your process does
1238      * not have permission to modify the given thread, or to use the given
1239      * scheduling policy or priority.
1240      *
1241      * {@hide}
1242      */
1243 
setThreadScheduler(int tid, int policy, int priority)1244     public static final native void setThreadScheduler(int tid, int policy, int priority)
1245             throws IllegalArgumentException;
1246 
1247     /**
1248      * Determine whether the current environment supports multiple processes.
1249      *
1250      * @return Returns true if the system can run in multiple processes, else
1251      * false if everything is running in a single process.
1252      *
1253      * @deprecated This method always returns true.  Do not use.
1254      */
1255     @Deprecated
supportsProcesses()1256     public static final boolean supportsProcesses() {
1257         return true;
1258     }
1259 
1260     /**
1261      * Adjust the swappiness level for a process.
1262      *
1263      * @param pid The process identifier to set.
1264      * @param is_increased Whether swappiness should be increased or default.
1265      *
1266      * @return Returns true if the underlying system supports this
1267      *         feature, else false.
1268      *
1269      * {@hide}
1270      */
setSwappiness(int pid, boolean is_increased)1271     public static final native boolean setSwappiness(int pid, boolean is_increased);
1272 
1273     /**
1274      * Change this process's argv[0] parameter.  This can be useful to show
1275      * more descriptive information in things like the 'ps' command.
1276      *
1277      * @param text The new name of this process.
1278      *
1279      * {@hide}
1280      */
1281     @UnsupportedAppUsage(maxTargetSdk = VERSION_CODES.S, publicAlternatives = "Do not try to "
1282             + "change the process name. (If you must, you could use {@code pthread_setname_np(3)}, "
1283             + "but this could confuse the system)")
setArgV0(@onNull String text)1284     public static void setArgV0(@NonNull String text) {
1285         sArgV0 = text;
1286         setArgV0Native(text);
1287     }
1288 
setArgV0Native(String text)1289     private static native void setArgV0Native(String text);
1290 
1291     /**
1292      * Return the name of this process. By default, the process name is the same as the app's
1293      * package name, but this can be changed using {@code android:process}.
1294      */
1295     @NonNull
myProcessName()1296     public static String myProcessName() {
1297         // Note this could be different from the actual process name if someone changes the
1298         // process name using native code (using pthread_setname_np()). But sArgV0
1299         // is the name that the system thinks this process has.
1300         return sArgV0;
1301     }
1302 
1303     /**
1304      * Kill the process with the given PID.
1305      * Note that, though this API allows us to request to
1306      * kill any process based on its PID, the kernel will
1307      * still impose standard restrictions on which PIDs you
1308      * are actually able to kill.  Typically this means only
1309      * the process running the caller's packages/application
1310      * and any additional processes created by that app; packages
1311      * sharing a common UID will also be able to kill each
1312      * other's processes.
1313      */
killProcess(int pid)1314     public static final void killProcess(int pid) {
1315         sendSignal(pid, SIGNAL_KILL);
1316     }
1317 
1318     /** @hide */
setUid(int uid)1319     public static final native int setUid(int uid);
1320 
1321     /** @hide */
setGid(int uid)1322     public static final native int setGid(int uid);
1323 
1324     /**
1325      * Send a signal to the given process.
1326      *
1327      * @param pid The pid of the target process.
1328      * @param signal The signal to send.
1329      */
sendSignal(int pid, int signal)1330     public static final native void sendSignal(int pid, int signal);
1331 
1332     /**
1333      * @hide
1334      * Private impl for avoiding a log message...  DO NOT USE without doing
1335      * your own log, or the Android Illuminati will find you some night and
1336      * beat you up.
1337      */
killProcessQuiet(int pid)1338     public static final void killProcessQuiet(int pid) {
1339         sendSignalQuiet(pid, SIGNAL_KILL);
1340     }
1341 
1342     /**
1343      * @hide
1344      * Private impl for avoiding a log message...  DO NOT USE without doing
1345      * your own log, or the Android Illuminati will find you some night and
1346      * beat you up.
1347      */
1348     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
sendSignalQuiet(int pid, int signal)1349     public static final native void sendSignalQuiet(int pid, int signal);
1350 
1351     /**
1352      * @return The advertised memory of the system, as the end user would encounter in a retail
1353      * display environment. If the advertised memory is not defined, it returns
1354      * {@code getTotalMemory()} rounded.
1355      *
1356      * @hide
1357      */
getAdvertisedMem()1358     public static final long getAdvertisedMem() {
1359         String formatSize = MemoryProperties.memory_ddr_size().orElse("0KB");
1360         long memSize = FileUtils.parseSize(formatSize);
1361 
1362         if (memSize <= 0) {
1363             return FileUtils.roundStorageSize(getTotalMemory());
1364         }
1365 
1366         return memSize;
1367     }
1368 
1369     /** @hide */
1370     @UnsupportedAppUsage
getFreeMemory()1371     public static final native long getFreeMemory();
1372 
1373     /** @hide */
1374     @UnsupportedAppUsage
getTotalMemory()1375     public static final native long getTotalMemory();
1376 
1377     /** @hide */
1378     @UnsupportedAppUsage
readProcLines(String path, String[] reqFields, long[] outSizes)1379     public static final native void readProcLines(String path,
1380             String[] reqFields, long[] outSizes);
1381 
1382     /** @hide */
1383     @UnsupportedAppUsage
getPids(String path, int[] lastArray)1384     public static final native int[] getPids(String path, int[] lastArray);
1385 
1386     /** @hide */
1387     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1388     public static final int PROC_TERM_MASK = 0xff;
1389     /** @hide */
1390     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1391     public static final int PROC_ZERO_TERM = 0;
1392     /** @hide */
1393     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1394     public static final int PROC_SPACE_TERM = (int)' ';
1395     /** @hide */
1396     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1397     public static final int PROC_TAB_TERM = (int)'\t';
1398     /** @hide */
1399     public static final int PROC_NEWLINE_TERM = (int) '\n';
1400     /** @hide */
1401     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1402     public static final int PROC_COMBINE = 0x100;
1403     /** @hide */
1404     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1405     public static final int PROC_PARENS = 0x200;
1406     /** @hide */
1407     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1408     public static final int PROC_QUOTES = 0x400;
1409     /** @hide */
1410     public static final int PROC_CHAR = 0x800;
1411     /** @hide */
1412     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1413     public static final int PROC_OUT_STRING = 0x1000;
1414     /** @hide */
1415     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1416     public static final int PROC_OUT_LONG = 0x2000;
1417     /** @hide */
1418     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1419     public static final int PROC_OUT_FLOAT = 0x4000;
1420 
1421     /**
1422      * Read and parse a {@code proc} file in the given format.
1423      *
1424      * <p>The format is a list of integers, where every integer describes a variable in the file. It
1425      * specifies how the variable is syntactically terminated (e.g. {@link Process#PROC_SPACE_TERM},
1426      * {@link Process#PROC_TAB_TERM}, {@link Process#PROC_ZERO_TERM}, {@link
1427      * Process#PROC_NEWLINE_TERM}).
1428      *
1429      * <p>If the variable should be parsed and returned to the caller, the termination type should
1430      * be binary OR'd with the type of output (e.g. {@link Process#PROC_OUT_STRING}, {@link
1431      * Process#PROC_OUT_LONG}, {@link Process#PROC_OUT_FLOAT}.
1432      *
1433      * <p>If the variable is wrapped in quotation marks it should be binary OR'd with {@link
1434      * Process#PROC_QUOTES}. If the variable is wrapped in parentheses it should be binary OR'd with
1435      * {@link Process#PROC_PARENS}.
1436      *
1437      * <p>If the variable is not formatted as a string and should be cast directly from characters
1438      * to a long, the {@link Process#PROC_CHAR} integer should be binary OR'd.
1439      *
1440      * <p>If the terminating character can be repeated, the {@link Process#PROC_COMBINE} integer
1441      * should be binary OR'd.
1442      *
1443      * @param file the path of the {@code proc} file to read
1444      * @param format the format of the file
1445      * @param outStrings the parsed {@code String}s from the file
1446      * @param outLongs the parsed {@code long}s from the file
1447      * @param outFloats the parsed {@code float}s from the file
1448      * @hide
1449      */
1450     @UnsupportedAppUsage
readProcFile(String file, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1451     public static final native boolean readProcFile(String file, int[] format,
1452             String[] outStrings, long[] outLongs, float[] outFloats);
1453 
1454     /** @hide */
1455     @UnsupportedAppUsage
parseProcLine(byte[] buffer, int startIndex, int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1456     public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1457             int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1458 
1459     /** @hide */
1460     @UnsupportedAppUsage
getPidsForCommands(String[] cmds)1461     public static final native int[] getPidsForCommands(String[] cmds);
1462 
1463     /**
1464      * Gets the total Pss value for a given process, in bytes.
1465      *
1466      * @param pid the process to the Pss for
1467      * @return the total Pss value for the given process in bytes,
1468      *  or -1 if the value cannot be determined
1469      * @hide
1470      */
1471     @UnsupportedAppUsage
getPss(int pid)1472     public static final native long getPss(int pid);
1473 
1474     /** @hide */
getRss(int pid)1475     public static final native long[] getRss(int pid);
1476 
1477     /**
1478      * Specifies the outcome of having started a process.
1479      * @hide
1480      */
1481     public static final class ProcessStartResult {
1482         /**
1483          * The PID of the newly started process.
1484          * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
1485          */
1486         public int pid;
1487 
1488         /**
1489          * True if the process was started with a wrapper attached.
1490          */
1491         public boolean usingWrapper;
1492     }
1493 
1494     /**
1495      * Kill all processes in a process group started for the given
1496      * pid.
1497      * @hide
1498      */
killProcessGroup(int uid, int pid)1499     public static final native int killProcessGroup(int uid, int pid);
1500 
1501     /**
1502      * Send a signal to all processes in a group under the given PID, but do not wait for the
1503      * processes to be fully cleaned up, or for the cgroup to be removed before returning.
1504      * Callers should also ensure that killProcessGroup is called later to ensure the cgroup is
1505      * fully removed, otherwise system resources may leak.
1506      * @hide
1507      */
sendSignalToProcessGroup(int uid, int pid, int signal)1508     public static final native int sendSignalToProcessGroup(int uid, int pid, int signal);
1509 
1510     /**
1511       * Freeze the cgroup for the given UID.
1512       * This cgroup may contain child cgroups which will also be frozen. If this cgroup or its
1513       * children contain processes with Binder interfaces, those interfaces should be frozen before
1514       * the cgroup to avoid blocking synchronous callers indefinitely.
1515       *
1516       * @param uid The UID to be frozen
1517       * @param freeze true = freeze; false = unfreeze
1518       * @hide
1519       */
freezeCgroupUid(int uid, boolean freeze)1520     public static final native void freezeCgroupUid(int uid, boolean freeze);
1521 
1522     /**
1523      * Remove all process groups.  Expected to be called when ActivityManager
1524      * is restarted.
1525      * @hide
1526      */
removeAllProcessGroups()1527     public static final native void removeAllProcessGroups();
1528 
1529     /**
1530      * Check to see if a thread belongs to a given process. This may require
1531      * more permissions than apps generally have.
1532      * @return true if this thread belongs to a process
1533      * @hide
1534      */
isThreadInProcess(int tid, int pid)1535     public static final boolean isThreadInProcess(int tid, int pid) {
1536         StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
1537         try {
1538             if (Os.access("/proc/" + tid + "/task/" + pid, OsConstants.F_OK)) {
1539                 return true;
1540             } else {
1541                 return false;
1542             }
1543         } catch (Exception e) {
1544             return false;
1545         } finally {
1546             StrictMode.setThreadPolicy(oldPolicy);
1547         }
1548 
1549     }
1550 
1551     /**
1552      * Wait for the death of the given process.
1553      *
1554      * @param pid The process ID to be waited on
1555      * @param timeout The maximum time to wait in milliseconds, or -1 to wait forever
1556      * @hide
1557      */
waitForProcessDeath(int pid, int timeout)1558     public static void waitForProcessDeath(int pid, int timeout)
1559             throws InterruptedException, TimeoutException {
1560         boolean fallback = supportsPidFd();
1561         if (!fallback) {
1562             FileDescriptor pidfd = null;
1563             try {
1564                 final int fd = nativePidFdOpen(pid, 0);
1565                 if (fd >= 0) {
1566                     pidfd = new FileDescriptor();
1567                     pidfd.setInt$(fd);
1568                 } else {
1569                     fallback = true;
1570                 }
1571                 if (pidfd != null) {
1572                     StructPollfd[] fds = new StructPollfd[] {
1573                         new StructPollfd()
1574                     };
1575                     fds[0].fd = pidfd;
1576                     fds[0].events = (short) OsConstants.POLLIN;
1577                     fds[0].revents = 0;
1578                     fds[0].userData = null;
1579                     int res = Os.poll(fds, timeout);
1580                     if (res > 0) {
1581                         return;
1582                     } else if (res == 0) {
1583                         throw new TimeoutException();
1584                     } else {
1585                         // We should get an ErrnoException now
1586                     }
1587                 }
1588             } catch (ErrnoException e) {
1589                 if (e.errno == OsConstants.EINTR) {
1590                     throw new InterruptedException();
1591                 }
1592                 fallback = true;
1593             } finally {
1594                 if (pidfd != null) {
1595                     IoUtils.closeQuietly(pidfd);
1596                 }
1597             }
1598         }
1599         if (fallback) {
1600             boolean infinity = timeout < 0;
1601             long now = System.currentTimeMillis();
1602             final long end = now + timeout;
1603             while (infinity || now < end) {
1604                 try {
1605                     Os.kill(pid, 0);
1606                 } catch (ErrnoException e) {
1607                     if (e.errno == OsConstants.ESRCH) {
1608                         return;
1609                     }
1610                 }
1611                 Thread.sleep(1);
1612                 now = System.currentTimeMillis();
1613             }
1614         }
1615         throw new TimeoutException();
1616     }
1617 
1618     /**
1619      * Determine whether the system supports pidfd APIs
1620      *
1621      * @return Returns true if the system supports pidfd APIs
1622      * @hide
1623      */
1624     public static boolean supportsPidFd() {
1625         if (sPidFdSupported == PIDFD_UNKNOWN) {
1626             int fd = -1;
1627             try {
1628                 fd = nativePidFdOpen(myPid(), 0);
1629                 sPidFdSupported = PIDFD_SUPPORTED;
1630             } catch (ErrnoException e) {
1631                 sPidFdSupported = e.errno != OsConstants.ENOSYS
1632                         ? PIDFD_SUPPORTED : PIDFD_UNSUPPORTED;
1633             } finally {
1634                 if (fd >= 0) {
1635                     final FileDescriptor f = new FileDescriptor();
1636                     f.setInt$(fd);
1637                     IoUtils.closeQuietly(f);
1638                 }
1639             }
1640         }
1641         return sPidFdSupported == PIDFD_SUPPORTED;
1642     }
1643 
1644     /**
1645      * Open process file descriptor for given pid.
1646      *
1647      * @param pid The process ID to open for
1648      * @param flags Reserved, unused now, must be 0
1649      * @return The process file descriptor for given pid
1650      * @throws IOException if it can't be opened
1651      *
1652      * @hide
1653      */
1654     public static @Nullable FileDescriptor openPidFd(int pid, int flags) throws IOException {
1655         if (!supportsPidFd()) {
1656             return null;
1657         }
1658         if (flags != 0) {
1659             throw new IllegalArgumentException();
1660         }
1661         try {
1662             FileDescriptor pidfd = new FileDescriptor();
1663             pidfd.setInt$(nativePidFdOpen(pid, flags));
1664             return pidfd;
1665         } catch (ErrnoException e) {
1666             IOException ex = new IOException();
1667             ex.initCause(e);
1668             throw ex;
1669         }
1670     }
1671 
1672     private static native int nativePidFdOpen(int pid, int flags) throws ErrnoException;
1673 }
1674