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