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