• 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.net.LocalSocketAddress;
20 import android.net.LocalSocket;
21 import android.util.Log;
22 import dalvik.system.Zygote;
23 
24 import java.io.BufferedWriter;
25 import java.io.DataInputStream;
26 import java.io.IOException;
27 import java.io.OutputStreamWriter;
28 import java.util.ArrayList;
29 
30 import libcore.io.Libcore;
31 
32 /*package*/ class ZygoteStartFailedEx extends Exception {
33     /**
34      * Something prevented the zygote process startup from happening normally
35      */
36 
ZygoteStartFailedEx()37     ZygoteStartFailedEx() {};
ZygoteStartFailedEx(String s)38     ZygoteStartFailedEx(String s) {super(s);}
ZygoteStartFailedEx(Throwable cause)39     ZygoteStartFailedEx(Throwable cause) {super(cause);}
40 }
41 
42 /**
43  * Tools for managing OS processes.
44  */
45 public class Process {
46     private static final String LOG_TAG = "Process";
47 
48     private static final String ZYGOTE_SOCKET = "zygote";
49 
50     /**
51      * Name of a process for running the platform's media services.
52      * {@hide}
53      */
54     public static final String ANDROID_SHARED_MEDIA = "com.android.process.media";
55 
56     /**
57      * Name of the process that Google content providers can share.
58      * {@hide}
59      */
60     public static final String GOOGLE_SHARED_APP_CONTENT = "com.google.process.content";
61 
62     /**
63      * Defines the UID/GID under which system code runs.
64      */
65     public static final int SYSTEM_UID = 1000;
66 
67     /**
68      * Defines the UID/GID under which the telephony code runs.
69      */
70     public static final int PHONE_UID = 1001;
71 
72     /**
73      * Defines the UID/GID for the user shell.
74      * @hide
75      */
76     public static final int SHELL_UID = 2000;
77 
78     /**
79      * Defines the UID/GID for the log group.
80      * @hide
81      */
82     public static final int LOG_UID = 1007;
83 
84     /**
85      * Defines the UID/GID for the WIFI supplicant process.
86      * @hide
87      */
88     public static final int WIFI_UID = 1010;
89 
90     /**
91      * Defines the UID/GID for the mediaserver process.
92      * @hide
93      */
94     public static final int MEDIA_UID = 1013;
95 
96     /**
97      * Defines the UID/GID for the DRM process.
98      * @hide
99      */
100     public static final int DRM_UID = 1019;
101 
102     /**
103      * Defines the UID/GID for the group that controls VPN services.
104      * @hide
105      */
106     public static final int VPN_UID = 1016;
107 
108     /**
109      * Defines the UID/GID for the NFC service process.
110      * @hide
111      */
112     public static final int NFC_UID = 1027;
113 
114     /**
115      * Defines the UID/GID for the Bluetooth service process.
116      * @hide
117      */
118     public static final int BLUETOOTH_UID = 1002;
119 
120     /**
121      * Defines the GID for the group that allows write access to the internal media storage.
122      * @hide
123      */
124     public static final int MEDIA_RW_GID = 1023;
125 
126     /**
127      * Access to installed package details
128      * @hide
129      */
130     public static final int PACKAGE_INFO_GID = 1032;
131 
132     /**
133      * Defines the start of a range of UIDs (and GIDs), going from this
134      * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
135      * to applications.
136      */
137     public static final int FIRST_APPLICATION_UID = 10000;
138 
139     /**
140      * Last of application-specific UIDs starting at
141      * {@link #FIRST_APPLICATION_UID}.
142      */
143     public static final int LAST_APPLICATION_UID = 19999;
144 
145     /**
146      * First uid used for fully isolated sandboxed processes (with no permissions of their own)
147      * @hide
148      */
149     public static final int FIRST_ISOLATED_UID = 99000;
150 
151     /**
152      * Last uid used for fully isolated sandboxed processes (with no permissions of their own)
153      * @hide
154      */
155     public static final int LAST_ISOLATED_UID = 99999;
156 
157     /**
158      * First gid for applications to share resources. Used when forward-locking
159      * is enabled but all UserHandles need to be able to read the resources.
160      * @hide
161      */
162     public static final int FIRST_SHARED_APPLICATION_GID = 50000;
163 
164     /**
165      * Last gid for applications to share resources. Used when forward-locking
166      * is enabled but all UserHandles need to be able to read the resources.
167      * @hide
168      */
169     public static final int LAST_SHARED_APPLICATION_GID = 59999;
170 
171     /**
172      * Standard priority of application threads.
173      * Use with {@link #setThreadPriority(int)} and
174      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
175      * {@link java.lang.Thread} class.
176      */
177     public static final int THREAD_PRIORITY_DEFAULT = 0;
178 
179     /*
180      * ***************************************
181      * ** Keep in sync with utils/threads.h **
182      * ***************************************
183      */
184 
185     /**
186      * Lowest available thread priority.  Only for those who really, really
187      * don't want to run if anything else is happening.
188      * Use with {@link #setThreadPriority(int)} and
189      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
190      * {@link java.lang.Thread} class.
191      */
192     public static final int THREAD_PRIORITY_LOWEST = 19;
193 
194     /**
195      * Standard priority background threads.  This gives your thread a slightly
196      * lower than normal priority, so that it will have less chance of impacting
197      * the responsiveness of the user interface.
198      * Use with {@link #setThreadPriority(int)} and
199      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
200      * {@link java.lang.Thread} class.
201      */
202     public static final int THREAD_PRIORITY_BACKGROUND = 10;
203 
204     /**
205      * Standard priority of threads that are currently running a user interface
206      * that the user is interacting with.  Applications can not normally
207      * change to this priority; the system will automatically adjust your
208      * application threads as the user moves through the UI.
209      * Use with {@link #setThreadPriority(int)} and
210      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
211      * {@link java.lang.Thread} class.
212      */
213     public static final int THREAD_PRIORITY_FOREGROUND = -2;
214 
215     /**
216      * Standard priority of system display threads, involved in updating
217      * the user interface.  Applications can not
218      * normally change to this priority.
219      * Use with {@link #setThreadPriority(int)} and
220      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
221      * {@link java.lang.Thread} class.
222      */
223     public static final int THREAD_PRIORITY_DISPLAY = -4;
224 
225     /**
226      * Standard priority of the most important display threads, for compositing
227      * the screen and retrieving input events.  Applications can not normally
228      * change to this priority.
229      * Use with {@link #setThreadPriority(int)} and
230      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
231      * {@link java.lang.Thread} class.
232      */
233     public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
234 
235     /**
236      * Standard priority of audio threads.  Applications can not normally
237      * change to this priority.
238      * Use with {@link #setThreadPriority(int)} and
239      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
240      * {@link java.lang.Thread} class.
241      */
242     public static final int THREAD_PRIORITY_AUDIO = -16;
243 
244     /**
245      * Standard priority of the most important audio threads.
246      * Applications can not normally change to this priority.
247      * Use with {@link #setThreadPriority(int)} and
248      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
249      * {@link java.lang.Thread} class.
250      */
251     public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
252 
253     /**
254      * Minimum increment to make a priority more favorable.
255      */
256     public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
257 
258     /**
259      * Minimum increment to make a priority less favorable.
260      */
261     public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
262 
263     /**
264      * Default scheduling policy
265      * @hide
266      */
267     public static final int SCHED_OTHER = 0;
268 
269     /**
270      * First-In First-Out scheduling policy
271      * @hide
272      */
273     public static final int SCHED_FIFO = 1;
274 
275     /**
276      * Round-Robin scheduling policy
277      * @hide
278      */
279     public static final int SCHED_RR = 2;
280 
281     /**
282      * Batch scheduling policy
283      * @hide
284      */
285     public static final int SCHED_BATCH = 3;
286 
287     /**
288      * Idle scheduling policy
289      * @hide
290      */
291     public static final int SCHED_IDLE = 5;
292 
293     // Keep in sync with SP_* constants of enum type SchedPolicy
294     // declared in system/core/include/cutils/sched_policy.h,
295     // except THREAD_GROUP_DEFAULT does not correspond to any SP_* value.
296 
297     /**
298      * Default thread group -
299      * has meaning with setProcessGroup() only, cannot be used with setThreadGroup().
300      * When used with setProcessGroup(), the group of each thread in the process
301      * is conditionally changed based on that thread's current priority, as follows:
302      * threads with priority numerically less than THREAD_PRIORITY_BACKGROUND
303      * are moved to foreground thread group.  All other threads are left unchanged.
304      * @hide
305      */
306     public static final int THREAD_GROUP_DEFAULT = -1;
307 
308     /**
309      * Background thread group - All threads in
310      * this group are scheduled with a reduced share of the CPU.
311      * Value is same as constant SP_BACKGROUND of enum SchedPolicy.
312      * FIXME rename to THREAD_GROUP_BACKGROUND.
313      * @hide
314      */
315     public static final int THREAD_GROUP_BG_NONINTERACTIVE = 0;
316 
317     /**
318      * Foreground thread group - All threads in
319      * this group are scheduled with a normal share of the CPU.
320      * Value is same as constant SP_FOREGROUND of enum SchedPolicy.
321      * Not used at this level.
322      * @hide
323      **/
324     private static final int THREAD_GROUP_FOREGROUND = 1;
325 
326     /**
327      * System thread group.
328      * @hide
329      **/
330     public static final int THREAD_GROUP_SYSTEM = 2;
331 
332     /**
333      * Application audio thread group.
334      * @hide
335      **/
336     public static final int THREAD_GROUP_AUDIO_APP = 3;
337 
338     /**
339      * System audio thread group.
340      * @hide
341      **/
342     public static final int THREAD_GROUP_AUDIO_SYS = 4;
343 
344     public static final int SIGNAL_QUIT = 3;
345     public static final int SIGNAL_KILL = 9;
346     public static final int SIGNAL_USR1 = 10;
347 
348     // State for communicating with zygote process
349 
350     static LocalSocket sZygoteSocket;
351     static DataInputStream sZygoteInputStream;
352     static BufferedWriter sZygoteWriter;
353 
354     /** true if previous zygote open failed */
355     static boolean sPreviousZygoteOpenFailed;
356 
357     /**
358      * Start a new process.
359      *
360      * <p>If processes are enabled, a new process is created and the
361      * static main() function of a <var>processClass</var> is executed there.
362      * The process will continue running after this function returns.
363      *
364      * <p>If processes are not enabled, a new thread in the caller's
365      * process is created and main() of <var>processClass</var> called there.
366      *
367      * <p>The niceName parameter, if not an empty string, is a custom name to
368      * give to the process instead of using processClass.  This allows you to
369      * make easily identifyable processes even if you are using the same base
370      * <var>processClass</var> to start them.
371      *
372      * @param processClass The class to use as the process's main entry
373      *                     point.
374      * @param niceName A more readable name to use for the process.
375      * @param uid The user-id under which the process will run.
376      * @param gid The group-id under which the process will run.
377      * @param gids Additional group-ids associated with the process.
378      * @param debugFlags Additional flags.
379      * @param targetSdkVersion The target SDK version for the app.
380      * @param seInfo null-ok SE Android information for the new process.
381      * @param zygoteArgs Additional arguments to supply to the zygote process.
382      *
383      * @return An object that describes the result of the attempt to start the process.
384      * @throws RuntimeException on fatal start failure
385      *
386      * {@hide}
387      */
start(final String processClass, final String niceName, int uid, int gid, int[] gids, int debugFlags, int mountExternal, int targetSdkVersion, String seInfo, String[] zygoteArgs)388     public static final ProcessStartResult start(final String processClass,
389                                   final String niceName,
390                                   int uid, int gid, int[] gids,
391                                   int debugFlags, int mountExternal,
392                                   int targetSdkVersion,
393                                   String seInfo,
394                                   String[] zygoteArgs) {
395         try {
396             return startViaZygote(processClass, niceName, uid, gid, gids,
397                     debugFlags, mountExternal, targetSdkVersion, seInfo, zygoteArgs);
398         } catch (ZygoteStartFailedEx ex) {
399             Log.e(LOG_TAG,
400                     "Starting VM process through Zygote failed");
401             throw new RuntimeException(
402                     "Starting VM process through Zygote failed", ex);
403         }
404     }
405 
406     /** retry interval for opening a zygote socket */
407     static final int ZYGOTE_RETRY_MILLIS = 500;
408 
409     /**
410      * Tries to open socket to Zygote process if not already open. If
411      * already open, does nothing.  May block and retry.
412      */
openZygoteSocketIfNeeded()413     private static void openZygoteSocketIfNeeded()
414             throws ZygoteStartFailedEx {
415 
416         int retryCount;
417 
418         if (sPreviousZygoteOpenFailed) {
419             /*
420              * If we've failed before, expect that we'll fail again and
421              * don't pause for retries.
422              */
423             retryCount = 0;
424         } else {
425             retryCount = 10;
426         }
427 
428         /*
429          * See bug #811181: Sometimes runtime can make it up before zygote.
430          * Really, we'd like to do something better to avoid this condition,
431          * but for now just wait a bit...
432          */
433         for (int retry = 0
434                 ; (sZygoteSocket == null) && (retry < (retryCount + 1))
435                 ; retry++ ) {
436 
437             if (retry > 0) {
438                 try {
439                     Log.i("Zygote", "Zygote not up yet, sleeping...");
440                     Thread.sleep(ZYGOTE_RETRY_MILLIS);
441                 } catch (InterruptedException ex) {
442                     // should never happen
443                 }
444             }
445 
446             try {
447                 sZygoteSocket = new LocalSocket();
448 
449                 sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET,
450                         LocalSocketAddress.Namespace.RESERVED));
451 
452                 sZygoteInputStream
453                         = new DataInputStream(sZygoteSocket.getInputStream());
454 
455                 sZygoteWriter =
456                     new BufferedWriter(
457                             new OutputStreamWriter(
458                                     sZygoteSocket.getOutputStream()),
459                             256);
460 
461                 Log.i("Zygote", "Process: zygote socket opened");
462 
463                 sPreviousZygoteOpenFailed = false;
464                 break;
465             } catch (IOException ex) {
466                 if (sZygoteSocket != null) {
467                     try {
468                         sZygoteSocket.close();
469                     } catch (IOException ex2) {
470                         Log.e(LOG_TAG,"I/O exception on close after exception",
471                                 ex2);
472                     }
473                 }
474 
475                 sZygoteSocket = null;
476             }
477         }
478 
479         if (sZygoteSocket == null) {
480             sPreviousZygoteOpenFailed = true;
481             throw new ZygoteStartFailedEx("connect failed");
482         }
483     }
484 
485     /**
486      * Sends an argument list to the zygote process, which starts a new child
487      * and returns the child's pid. Please note: the present implementation
488      * replaces newlines in the argument list with spaces.
489      * @param args argument list
490      * @return An object that describes the result of the attempt to start the process.
491      * @throws ZygoteStartFailedEx if process start failed for any reason
492      */
zygoteSendArgsAndGetResult(ArrayList<String> args)493     private static ProcessStartResult zygoteSendArgsAndGetResult(ArrayList<String> args)
494             throws ZygoteStartFailedEx {
495         openZygoteSocketIfNeeded();
496 
497         try {
498             /**
499              * See com.android.internal.os.ZygoteInit.readArgumentList()
500              * Presently the wire format to the zygote process is:
501              * a) a count of arguments (argc, in essence)
502              * b) a number of newline-separated argument strings equal to count
503              *
504              * After the zygote process reads these it will write the pid of
505              * the child or -1 on failure, followed by boolean to
506              * indicate whether a wrapper process was used.
507              */
508 
509             sZygoteWriter.write(Integer.toString(args.size()));
510             sZygoteWriter.newLine();
511 
512             int sz = args.size();
513             for (int i = 0; i < sz; i++) {
514                 String arg = args.get(i);
515                 if (arg.indexOf('\n') >= 0) {
516                     throw new ZygoteStartFailedEx(
517                             "embedded newlines not allowed");
518                 }
519                 sZygoteWriter.write(arg);
520                 sZygoteWriter.newLine();
521             }
522 
523             sZygoteWriter.flush();
524 
525             // Should there be a timeout on this?
526             ProcessStartResult result = new ProcessStartResult();
527             result.pid = sZygoteInputStream.readInt();
528             if (result.pid < 0) {
529                 throw new ZygoteStartFailedEx("fork() failed");
530             }
531             result.usingWrapper = sZygoteInputStream.readBoolean();
532             return result;
533         } catch (IOException ex) {
534             try {
535                 if (sZygoteSocket != null) {
536                     sZygoteSocket.close();
537                 }
538             } catch (IOException ex2) {
539                 // we're going to fail anyway
540                 Log.e(LOG_TAG,"I/O exception on routine close", ex2);
541             }
542 
543             sZygoteSocket = null;
544 
545             throw new ZygoteStartFailedEx(ex);
546         }
547     }
548 
549     /**
550      * Starts a new process via the zygote mechanism.
551      *
552      * @param processClass Class name whose static main() to run
553      * @param niceName 'nice' process name to appear in ps
554      * @param uid a POSIX uid that the new process should setuid() to
555      * @param gid a POSIX gid that the new process shuold setgid() to
556      * @param gids null-ok; a list of supplementary group IDs that the
557      * new process should setgroup() to.
558      * @param debugFlags Additional flags.
559      * @param targetSdkVersion The target SDK version for the app.
560      * @param seInfo null-ok SE Android information for the new process.
561      * @param extraArgs Additional arguments to supply to the zygote process.
562      * @return An object that describes the result of the attempt to start the process.
563      * @throws ZygoteStartFailedEx if process start failed for any reason
564      */
startViaZygote(final String processClass, final String niceName, final int uid, final int gid, final int[] gids, int debugFlags, int mountExternal, int targetSdkVersion, String seInfo, String[] extraArgs)565     private static ProcessStartResult startViaZygote(final String processClass,
566                                   final String niceName,
567                                   final int uid, final int gid,
568                                   final int[] gids,
569                                   int debugFlags, int mountExternal,
570                                   int targetSdkVersion,
571                                   String seInfo,
572                                   String[] extraArgs)
573                                   throws ZygoteStartFailedEx {
574         synchronized(Process.class) {
575             ArrayList<String> argsForZygote = new ArrayList<String>();
576 
577             // --runtime-init, --setuid=, --setgid=,
578             // and --setgroups= must go first
579             argsForZygote.add("--runtime-init");
580             argsForZygote.add("--setuid=" + uid);
581             argsForZygote.add("--setgid=" + gid);
582             if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
583                 argsForZygote.add("--enable-jni-logging");
584             }
585             if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
586                 argsForZygote.add("--enable-safemode");
587             }
588             if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
589                 argsForZygote.add("--enable-debugger");
590             }
591             if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
592                 argsForZygote.add("--enable-checkjni");
593             }
594             if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
595                 argsForZygote.add("--enable-assert");
596             }
597             if (mountExternal == Zygote.MOUNT_EXTERNAL_MULTIUSER) {
598                 argsForZygote.add("--mount-external-multiuser");
599             } else if (mountExternal == Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL) {
600                 argsForZygote.add("--mount-external-multiuser-all");
601             }
602             argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
603 
604             //TODO optionally enable debuger
605             //argsForZygote.add("--enable-debugger");
606 
607             // --setgroups is a comma-separated list
608             if (gids != null && gids.length > 0) {
609                 StringBuilder sb = new StringBuilder();
610                 sb.append("--setgroups=");
611 
612                 int sz = gids.length;
613                 for (int i = 0; i < sz; i++) {
614                     if (i != 0) {
615                         sb.append(',');
616                     }
617                     sb.append(gids[i]);
618                 }
619 
620                 argsForZygote.add(sb.toString());
621             }
622 
623             if (niceName != null) {
624                 argsForZygote.add("--nice-name=" + niceName);
625             }
626 
627             if (seInfo != null) {
628                 argsForZygote.add("--seinfo=" + seInfo);
629             }
630 
631             argsForZygote.add(processClass);
632 
633             if (extraArgs != null) {
634                 for (String arg : extraArgs) {
635                     argsForZygote.add(arg);
636                 }
637             }
638 
639             return zygoteSendArgsAndGetResult(argsForZygote);
640         }
641     }
642 
643     /**
644      * Returns elapsed milliseconds of the time this process has run.
645      * @return  Returns the number of milliseconds this process has return.
646      */
getElapsedCpuTime()647     public static final native long getElapsedCpuTime();
648 
649     /**
650      * Returns the identifier of this process, which can be used with
651      * {@link #killProcess} and {@link #sendSignal}.
652      */
myPid()653     public static final int myPid() {
654         return Libcore.os.getpid();
655     }
656 
657     /**
658      * Returns the identifier of this process' parent.
659      * @hide
660      */
myPpid()661     public static final int myPpid() {
662         return Libcore.os.getppid();
663     }
664 
665     /**
666      * Returns the identifier of the calling thread, which be used with
667      * {@link #setThreadPriority(int, int)}.
668      */
myTid()669     public static final int myTid() {
670         return Libcore.os.gettid();
671     }
672 
673     /**
674      * Returns the identifier of this process's uid.  This is the kernel uid
675      * that the process is running under, which is the identity of its
676      * app-specific sandbox.  It is different from {@link #myUserHandle} in that
677      * a uid identifies a specific app sandbox in a specific user.
678      */
myUid()679     public static final int myUid() {
680         return Libcore.os.getuid();
681     }
682 
683     /**
684      * Returns this process's user handle.  This is the
685      * user the process is running under.  It is distinct from
686      * {@link #myUid()} in that a particular user will have multiple
687      * distinct apps running under it each with their own uid.
688      */
myUserHandle()689     public static final UserHandle myUserHandle() {
690         return new UserHandle(UserHandle.getUserId(myUid()));
691     }
692 
693     /**
694      * Returns whether the current process is in an isolated sandbox.
695      * @hide
696      */
isIsolated()697     public static final boolean isIsolated() {
698         int uid = UserHandle.getAppId(myUid());
699         return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
700     }
701 
702     /**
703      * Returns the UID assigned to a particular user name, or -1 if there is
704      * none.  If the given string consists of only numbers, it is converted
705      * directly to a uid.
706      */
getUidForName(String name)707     public static final native int getUidForName(String name);
708 
709     /**
710      * Returns the GID assigned to a particular user name, or -1 if there is
711      * none.  If the given string consists of only numbers, it is converted
712      * directly to a gid.
713      */
getGidForName(String name)714     public static final native int getGidForName(String name);
715 
716     /**
717      * Returns a uid for a currently running process.
718      * @param pid the process id
719      * @return the uid of the process, or -1 if the process is not running.
720      * @hide pending API council review
721      */
getUidForPid(int pid)722     public static final int getUidForPid(int pid) {
723         String[] procStatusLabels = { "Uid:" };
724         long[] procStatusValues = new long[1];
725         procStatusValues[0] = -1;
726         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
727         return (int) procStatusValues[0];
728     }
729 
730     /**
731      * Returns the parent process id for a currently running process.
732      * @param pid the process id
733      * @return the parent process id of the process, or -1 if the process is not running.
734      * @hide
735      */
getParentPid(int pid)736     public static final int getParentPid(int pid) {
737         String[] procStatusLabels = { "PPid:" };
738         long[] procStatusValues = new long[1];
739         procStatusValues[0] = -1;
740         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
741         return (int) procStatusValues[0];
742     }
743 
744     /**
745      * Returns the thread group leader id for a currently running thread.
746      * @param tid the thread id
747      * @return the thread group leader id of the thread, or -1 if the thread is not running.
748      *         This is same as what getpid(2) would return if called by tid.
749      * @hide
750      */
getThreadGroupLeader(int tid)751     public static final int getThreadGroupLeader(int tid) {
752         String[] procStatusLabels = { "Tgid:" };
753         long[] procStatusValues = new long[1];
754         procStatusValues[0] = -1;
755         Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
756         return (int) procStatusValues[0];
757     }
758 
759     /**
760      * Set the priority of a thread, based on Linux priorities.
761      *
762      * @param tid The identifier of the thread/process to change.
763      * @param priority A Linux priority level, from -20 for highest scheduling
764      * priority to 19 for lowest scheduling priority.
765      *
766      * @throws IllegalArgumentException Throws IllegalArgumentException if
767      * <var>tid</var> does not exist.
768      * @throws SecurityException Throws SecurityException if your process does
769      * not have permission to modify the given thread, or to use the given
770      * priority.
771      */
setThreadPriority(int tid, int priority)772     public static final native void setThreadPriority(int tid, int priority)
773             throws IllegalArgumentException, SecurityException;
774 
775     /**
776      * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
777      * throw an exception if passed a background-level thread priority.  This is only
778      * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
779      *
780      * @hide
781      */
setCanSelfBackground(boolean backgroundOk)782     public static final native void setCanSelfBackground(boolean backgroundOk);
783 
784     /**
785      * Sets the scheduling group for a thread.
786      * @hide
787      * @param tid The identifier of the thread to change.
788      * @param group The target group for this thread from THREAD_GROUP_*.
789      *
790      * @throws IllegalArgumentException Throws IllegalArgumentException if
791      * <var>tid</var> does not exist.
792      * @throws SecurityException Throws SecurityException if your process does
793      * not have permission to modify the given thread, or to use the given
794      * priority.
795      * If the thread is a thread group leader, that is it's gettid() == getpid(),
796      * then the other threads in the same thread group are _not_ affected.
797      */
setThreadGroup(int tid, int group)798     public static final native void setThreadGroup(int tid, int group)
799             throws IllegalArgumentException, SecurityException;
800 
801     /**
802      * Sets the scheduling group for a process and all child threads
803      * @hide
804      * @param pid The identifier of the process to change.
805      * @param group The target group for this process from THREAD_GROUP_*.
806      *
807      * @throws IllegalArgumentException Throws IllegalArgumentException if
808      * <var>tid</var> does not exist.
809      * @throws SecurityException Throws SecurityException if your process does
810      * not have permission to modify the given thread, or to use the given
811      * priority.
812      *
813      * group == THREAD_GROUP_DEFAULT means to move all non-background priority
814      * threads to the foreground scheduling group, but to leave background
815      * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
816      * threads, regardless of priority, to the background scheduling group.
817      * group == THREAD_GROUP_FOREGROUND is not allowed.
818      */
setProcessGroup(int pid, int group)819     public static final native void setProcessGroup(int pid, int group)
820             throws IllegalArgumentException, SecurityException;
821 
822     /**
823      * Return the scheduling group of requested process.
824      *
825      * @hide
826      */
getProcessGroup(int pid)827     public static final native int getProcessGroup(int pid)
828             throws IllegalArgumentException, SecurityException;
829 
830     /**
831      * Set the priority of the calling thread, based on Linux priorities.  See
832      * {@link #setThreadPriority(int, int)} for more information.
833      *
834      * @param priority A Linux priority level, from -20 for highest scheduling
835      * priority to 19 for lowest scheduling priority.
836      *
837      * @throws IllegalArgumentException Throws IllegalArgumentException if
838      * <var>tid</var> does not exist.
839      * @throws SecurityException Throws SecurityException if your process does
840      * not have permission to modify the given thread, or to use the given
841      * priority.
842      *
843      * @see #setThreadPriority(int, int)
844      */
setThreadPriority(int priority)845     public static final native void setThreadPriority(int priority)
846             throws IllegalArgumentException, SecurityException;
847 
848     /**
849      * Return the current priority of a thread, based on Linux priorities.
850      *
851      * @param tid The identifier of the thread/process to change.
852      *
853      * @return Returns the current priority, as a Linux priority level,
854      * from -20 for highest scheduling priority to 19 for lowest scheduling
855      * priority.
856      *
857      * @throws IllegalArgumentException Throws IllegalArgumentException if
858      * <var>tid</var> does not exist.
859      */
getThreadPriority(int tid)860     public static final native int getThreadPriority(int tid)
861             throws IllegalArgumentException;
862 
863     /**
864      * Set the scheduling policy and priority of a thread, based on Linux.
865      *
866      * @param tid The identifier of the thread/process to change.
867      * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
868      * @param priority A Linux priority level in a range appropriate for the given policy.
869      *
870      * @throws IllegalArgumentException Throws IllegalArgumentException if
871      * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
872      * @throws SecurityException Throws SecurityException if your process does
873      * not have permission to modify the given thread, or to use the given
874      * scheduling policy or priority.
875      *
876      * {@hide}
877      */
setThreadScheduler(int tid, int policy, int priority)878     public static final native void setThreadScheduler(int tid, int policy, int priority)
879             throws IllegalArgumentException;
880 
881     /**
882      * Determine whether the current environment supports multiple processes.
883      *
884      * @return Returns true if the system can run in multiple processes, else
885      * false if everything is running in a single process.
886      *
887      * @deprecated This method always returns true.  Do not use.
888      */
889     @Deprecated
supportsProcesses()890     public static final boolean supportsProcesses() {
891         return true;
892     }
893 
894     /**
895      * Set the out-of-memory badness adjustment for a process.
896      *
897      * @param pid The process identifier to set.
898      * @param amt Adjustment value -- linux allows -16 to +15.
899      *
900      * @return Returns true if the underlying system supports this
901      *         feature, else false.
902      *
903      * {@hide}
904      */
setOomAdj(int pid, int amt)905     public static final native boolean setOomAdj(int pid, int amt);
906 
907     /**
908      * Adjust the swappiness level for a process.
909      *
910      * @param pid The process identifier to set.
911      * @param is_increased Whether swappiness should be increased or default.
912      *
913      * @return Returns true if the underlying system supports this
914      *         feature, else false.
915      *
916      * {@hide}
917      */
setSwappiness(int pid, boolean is_increased)918     public static final native boolean setSwappiness(int pid, boolean is_increased);
919 
920     /**
921      * Change this process's argv[0] parameter.  This can be useful to show
922      * more descriptive information in things like the 'ps' command.
923      *
924      * @param text The new name of this process.
925      *
926      * {@hide}
927      */
setArgV0(String text)928     public static final native void setArgV0(String text);
929 
930     /**
931      * Kill the process with the given PID.
932      * Note that, though this API allows us to request to
933      * kill any process based on its PID, the kernel will
934      * still impose standard restrictions on which PIDs you
935      * are actually able to kill.  Typically this means only
936      * the process running the caller's packages/application
937      * and any additional processes created by that app; packages
938      * sharing a common UID will also be able to kill each
939      * other's processes.
940      */
killProcess(int pid)941     public static final void killProcess(int pid) {
942         sendSignal(pid, SIGNAL_KILL);
943     }
944 
945     /** @hide */
setUid(int uid)946     public static final native int setUid(int uid);
947 
948     /** @hide */
setGid(int uid)949     public static final native int setGid(int uid);
950 
951     /**
952      * Send a signal to the given process.
953      *
954      * @param pid The pid of the target process.
955      * @param signal The signal to send.
956      */
sendSignal(int pid, int signal)957     public static final native void sendSignal(int pid, int signal);
958 
959     /**
960      * @hide
961      * Private impl for avoiding a log message...  DO NOT USE without doing
962      * your own log, or the Android Illuminati will find you some night and
963      * beat you up.
964      */
killProcessQuiet(int pid)965     public static final void killProcessQuiet(int pid) {
966         sendSignalQuiet(pid, SIGNAL_KILL);
967     }
968 
969     /**
970      * @hide
971      * Private impl for avoiding a log message...  DO NOT USE without doing
972      * your own log, or the Android Illuminati will find you some night and
973      * beat you up.
974      */
sendSignalQuiet(int pid, int signal)975     public static final native void sendSignalQuiet(int pid, int signal);
976 
977     /** @hide */
getFreeMemory()978     public static final native long getFreeMemory();
979 
980     /** @hide */
getTotalMemory()981     public static final native long getTotalMemory();
982 
983     /** @hide */
readProcLines(String path, String[] reqFields, long[] outSizes)984     public static final native void readProcLines(String path,
985             String[] reqFields, long[] outSizes);
986 
987     /** @hide */
getPids(String path, int[] lastArray)988     public static final native int[] getPids(String path, int[] lastArray);
989 
990     /** @hide */
991     public static final int PROC_TERM_MASK = 0xff;
992     /** @hide */
993     public static final int PROC_ZERO_TERM = 0;
994     /** @hide */
995     public static final int PROC_SPACE_TERM = (int)' ';
996     /** @hide */
997     public static final int PROC_TAB_TERM = (int)'\t';
998     /** @hide */
999     public static final int PROC_COMBINE = 0x100;
1000     /** @hide */
1001     public static final int PROC_PARENS = 0x200;
1002     /** @hide */
1003     public static final int PROC_QUOTES = 0x400;
1004     /** @hide */
1005     public static final int PROC_OUT_STRING = 0x1000;
1006     /** @hide */
1007     public static final int PROC_OUT_LONG = 0x2000;
1008     /** @hide */
1009     public static final int PROC_OUT_FLOAT = 0x4000;
1010 
1011     /** @hide */
readProcFile(String file, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1012     public static final native boolean readProcFile(String file, int[] format,
1013             String[] outStrings, long[] outLongs, float[] outFloats);
1014 
1015     /** @hide */
parseProcLine(byte[] buffer, int startIndex, int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1016     public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1017             int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1018 
1019     /** @hide */
getPidsForCommands(String[] cmds)1020     public static final native int[] getPidsForCommands(String[] cmds);
1021 
1022     /**
1023      * Gets the total Pss value for a given process, in bytes.
1024      *
1025      * @param pid the process to the Pss for
1026      * @return the total Pss value for the given process in bytes,
1027      *  or -1 if the value cannot be determined
1028      * @hide
1029      */
getPss(int pid)1030     public static final native long getPss(int pid);
1031 
1032     /**
1033      * Specifies the outcome of having started a process.
1034      * @hide
1035      */
1036     public static final class ProcessStartResult {
1037         /**
1038          * The PID of the newly started process.
1039          * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
1040          */
1041         public int pid;
1042 
1043         /**
1044          * True if the process was started with a wrapper attached.
1045          */
1046         public boolean usingWrapper;
1047     }
1048 }
1049