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