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