OSDN Git Service

Process: Fix communication with zygote.
[android-x86/frameworks-base.git] / core / java / android / os / Process.java
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
37     ZygoteStartFailedEx() {};
38     ZygoteStartFailedEx(String s) {super(s);}
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      */
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      */
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      */
493     private static ProcessStartResult zygoteSendArgsAndGetResult(ArrayList<String> args)
494             throws ZygoteStartFailedEx {
495         openZygoteSocketIfNeeded();
496
497         try {
498             // Throw early if any of the arguments are malformed. This means we can
499             // avoid writing a partial response to the zygote.
500             int sz = args.size();
501             for (int i = 0; i < sz; i++) {
502                 if (args.get(i).indexOf('\n') >= 0) {
503                     throw new ZygoteStartFailedEx("embedded newlines not allowed");
504                 }
505             }
506
507             /**
508              * See com.android.internal.os.ZygoteInit.readArgumentList()
509              * Presently the wire format to the zygote process is:
510              * a) a count of arguments (argc, in essence)
511              * b) a number of newline-separated argument strings equal to count
512              *
513              * After the zygote process reads these it will write the pid of
514              * the child or -1 on failure, followed by boolean to
515              * indicate whether a wrapper process was used.
516              */
517
518             sZygoteWriter.write(Integer.toString(args.size()));
519             sZygoteWriter.newLine();
520
521             for (int i = 0; i < sz; i++) {
522                 String arg = args.get(i);
523                 sZygoteWriter.write(arg);
524                 sZygoteWriter.newLine();
525             }
526
527             sZygoteWriter.flush();
528
529             // Should there be a timeout on this?
530             ProcessStartResult result = new ProcessStartResult();
531             // Always read the entire result from the input stream to avoid leaving
532             // bytes in the stream for future process starts to accidentally stumble
533             // upon.
534             result.pid = sZygoteInputStream.readInt();
535             result.usingWrapper = sZygoteInputStream.readBoolean();
536
537             if (result.pid < 0) {
538                 throw new ZygoteStartFailedEx("fork() failed");
539             }
540             return result;
541         } catch (IOException ex) {
542             try {
543                 if (sZygoteSocket != null) {
544                     sZygoteSocket.close();
545                 }
546             } catch (IOException ex2) {
547                 // we're going to fail anyway
548                 Log.e(LOG_TAG,"I/O exception on routine close", ex2);
549             }
550
551             sZygoteSocket = null;
552
553             throw new ZygoteStartFailedEx(ex);
554         }
555     }
556
557     /**
558      * Starts a new process via the zygote mechanism.
559      *
560      * @param processClass Class name whose static main() to run
561      * @param niceName 'nice' process name to appear in ps
562      * @param uid a POSIX uid that the new process should setuid() to
563      * @param gid a POSIX gid that the new process shuold setgid() to
564      * @param gids null-ok; a list of supplementary group IDs that the
565      * new process should setgroup() to.
566      * @param debugFlags Additional flags.
567      * @param targetSdkVersion The target SDK version for the app.
568      * @param seInfo null-ok SE Android information for the new process.
569      * @param extraArgs Additional arguments to supply to the zygote process.
570      * @return An object that describes the result of the attempt to start the process.
571      * @throws ZygoteStartFailedEx if process start failed for any reason
572      */
573     private static ProcessStartResult startViaZygote(final String processClass,
574                                   final String niceName,
575                                   final int uid, final int gid,
576                                   final int[] gids,
577                                   int debugFlags, int mountExternal,
578                                   int targetSdkVersion,
579                                   String seInfo,
580                                   String[] extraArgs)
581                                   throws ZygoteStartFailedEx {
582         synchronized(Process.class) {
583             ArrayList<String> argsForZygote = new ArrayList<String>();
584
585             // --runtime-init, --setuid=, --setgid=,
586             // and --setgroups= must go first
587             argsForZygote.add("--runtime-init");
588             argsForZygote.add("--setuid=" + uid);
589             argsForZygote.add("--setgid=" + gid);
590             if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
591                 argsForZygote.add("--enable-jni-logging");
592             }
593             if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
594                 argsForZygote.add("--enable-safemode");
595             }
596             if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
597                 argsForZygote.add("--enable-debugger");
598             }
599             if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
600                 argsForZygote.add("--enable-checkjni");
601             }
602             if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
603                 argsForZygote.add("--enable-assert");
604             }
605             if (mountExternal == Zygote.MOUNT_EXTERNAL_MULTIUSER) {
606                 argsForZygote.add("--mount-external-multiuser");
607             } else if (mountExternal == Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL) {
608                 argsForZygote.add("--mount-external-multiuser-all");
609             }
610             argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
611
612             //TODO optionally enable debuger
613             //argsForZygote.add("--enable-debugger");
614
615             // --setgroups is a comma-separated list
616             if (gids != null && gids.length > 0) {
617                 StringBuilder sb = new StringBuilder();
618                 sb.append("--setgroups=");
619
620                 int sz = gids.length;
621                 for (int i = 0; i < sz; i++) {
622                     if (i != 0) {
623                         sb.append(',');
624                     }
625                     sb.append(gids[i]);
626                 }
627
628                 argsForZygote.add(sb.toString());
629             }
630
631             if (niceName != null) {
632                 argsForZygote.add("--nice-name=" + niceName);
633             }
634
635             if (seInfo != null) {
636                 argsForZygote.add("--seinfo=" + seInfo);
637             }
638
639             argsForZygote.add(processClass);
640
641             if (extraArgs != null) {
642                 for (String arg : extraArgs) {
643                     argsForZygote.add(arg);
644                 }
645             }
646
647             return zygoteSendArgsAndGetResult(argsForZygote);
648         }
649     }
650     
651     /**
652      * Returns elapsed milliseconds of the time this process has run.
653      * @return  Returns the number of milliseconds this process has return.
654      */
655     public static final native long getElapsedCpuTime();
656     
657     /**
658      * Returns the identifier of this process, which can be used with
659      * {@link #killProcess} and {@link #sendSignal}.
660      */
661     public static final int myPid() {
662         return Libcore.os.getpid();
663     }
664
665     /**
666      * Returns the identifier of this process' parent.
667      * @hide
668      */
669     public static final int myPpid() {
670         return Libcore.os.getppid();
671     }
672
673     /**
674      * Returns the identifier of the calling thread, which be used with
675      * {@link #setThreadPriority(int, int)}.
676      */
677     public static final int myTid() {
678         return Libcore.os.gettid();
679     }
680
681     /**
682      * Returns the identifier of this process's uid.  This is the kernel uid
683      * that the process is running under, which is the identity of its
684      * app-specific sandbox.  It is different from {@link #myUserHandle} in that
685      * a uid identifies a specific app sandbox in a specific user.
686      */
687     public static final int myUid() {
688         return Libcore.os.getuid();
689     }
690
691     /**
692      * Returns this process's user handle.  This is the
693      * user the process is running under.  It is distinct from
694      * {@link #myUid()} in that a particular user will have multiple
695      * distinct apps running under it each with their own uid.
696      */
697     public static final UserHandle myUserHandle() {
698         return new UserHandle(UserHandle.getUserId(myUid()));
699     }
700
701     /**
702      * Returns whether the current process is in an isolated sandbox.
703      * @hide
704      */
705     public static final boolean isIsolated() {
706         int uid = UserHandle.getAppId(myUid());
707         return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
708     }
709
710     /**
711      * Returns the UID assigned to a particular user name, or -1 if there is
712      * none.  If the given string consists of only numbers, it is converted
713      * directly to a uid.
714      */
715     public static final native int getUidForName(String name);
716     
717     /**
718      * Returns the GID assigned to a particular user name, or -1 if there is
719      * none.  If the given string consists of only numbers, it is converted
720      * directly to a gid.
721      */
722     public static final native int getGidForName(String name);
723
724     /**
725      * Returns a uid for a currently running process.
726      * @param pid the process id
727      * @return the uid of the process, or -1 if the process is not running.
728      * @hide pending API council review
729      */
730     public static final int getUidForPid(int pid) {
731         String[] procStatusLabels = { "Uid:" };
732         long[] procStatusValues = new long[1];
733         procStatusValues[0] = -1;
734         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
735         return (int) procStatusValues[0];
736     }
737
738     /**
739      * Returns the parent process id for a currently running process.
740      * @param pid the process id
741      * @return the parent process id of the process, or -1 if the process is not running.
742      * @hide
743      */
744     public static final int getParentPid(int pid) {
745         String[] procStatusLabels = { "PPid:" };
746         long[] procStatusValues = new long[1];
747         procStatusValues[0] = -1;
748         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
749         return (int) procStatusValues[0];
750     }
751
752     /**
753      * Returns the thread group leader id for a currently running thread.
754      * @param tid the thread id
755      * @return the thread group leader id of the thread, or -1 if the thread is not running.
756      *         This is same as what getpid(2) would return if called by tid.
757      * @hide
758      */
759     public static final int getThreadGroupLeader(int tid) {
760         String[] procStatusLabels = { "Tgid:" };
761         long[] procStatusValues = new long[1];
762         procStatusValues[0] = -1;
763         Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
764         return (int) procStatusValues[0];
765     }
766
767     /**
768      * Set the priority of a thread, based on Linux priorities.
769      * 
770      * @param tid The identifier of the thread/process to change.
771      * @param priority A Linux priority level, from -20 for highest scheduling
772      * priority to 19 for lowest scheduling priority.
773      * 
774      * @throws IllegalArgumentException Throws IllegalArgumentException if
775      * <var>tid</var> does not exist.
776      * @throws SecurityException Throws SecurityException if your process does
777      * not have permission to modify the given thread, or to use the given
778      * priority.
779      */
780     public static final native void setThreadPriority(int tid, int priority)
781             throws IllegalArgumentException, SecurityException;
782
783     /**
784      * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
785      * throw an exception if passed a background-level thread priority.  This is only
786      * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
787      *
788      * @hide
789      */
790     public static final native void setCanSelfBackground(boolean backgroundOk);
791
792     /**
793      * Sets the scheduling group for a thread.
794      * @hide
795      * @param tid The identifier of the thread to change.
796      * @param group The target group for this thread from THREAD_GROUP_*.
797      * 
798      * @throws IllegalArgumentException Throws IllegalArgumentException if
799      * <var>tid</var> does not exist.
800      * @throws SecurityException Throws SecurityException if your process does
801      * not have permission to modify the given thread, or to use the given
802      * priority.
803      * If the thread is a thread group leader, that is it's gettid() == getpid(),
804      * then the other threads in the same thread group are _not_ affected.
805      */
806     public static final native void setThreadGroup(int tid, int group)
807             throws IllegalArgumentException, SecurityException;
808
809     /**
810      * Sets the scheduling group for a process and all child threads
811      * @hide
812      * @param pid The identifier of the process to change.
813      * @param group The target group for this process from THREAD_GROUP_*.
814      * 
815      * @throws IllegalArgumentException Throws IllegalArgumentException if
816      * <var>tid</var> does not exist.
817      * @throws SecurityException Throws SecurityException if your process does
818      * not have permission to modify the given thread, or to use the given
819      * priority.
820      *
821      * group == THREAD_GROUP_DEFAULT means to move all non-background priority
822      * threads to the foreground scheduling group, but to leave background
823      * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
824      * threads, regardless of priority, to the background scheduling group.
825      * group == THREAD_GROUP_FOREGROUND is not allowed.
826      */
827     public static final native void setProcessGroup(int pid, int group)
828             throws IllegalArgumentException, SecurityException;
829
830     /**
831      * Return the scheduling group of requested process.
832      *
833      * @hide
834      */
835     public static final native int getProcessGroup(int pid)
836             throws IllegalArgumentException, SecurityException;
837
838     /**
839      * Set the priority of the calling thread, based on Linux priorities.  See
840      * {@link #setThreadPriority(int, int)} for more information.
841      * 
842      * @param priority A Linux priority level, from -20 for highest scheduling
843      * priority to 19 for lowest scheduling priority.
844      * 
845      * @throws IllegalArgumentException Throws IllegalArgumentException if
846      * <var>tid</var> does not exist.
847      * @throws SecurityException Throws SecurityException if your process does
848      * not have permission to modify the given thread, or to use the given
849      * priority.
850      * 
851      * @see #setThreadPriority(int, int)
852      */
853     public static final native void setThreadPriority(int priority)
854             throws IllegalArgumentException, SecurityException;
855     
856     /**
857      * Return the current priority of a thread, based on Linux priorities.
858      * 
859      * @param tid The identifier of the thread/process to change.
860      * 
861      * @return Returns the current priority, as a Linux priority level,
862      * from -20 for highest scheduling priority to 19 for lowest scheduling
863      * priority.
864      * 
865      * @throws IllegalArgumentException Throws IllegalArgumentException if
866      * <var>tid</var> does not exist.
867      */
868     public static final native int getThreadPriority(int tid)
869             throws IllegalArgumentException;
870     
871     /**
872      * Set the scheduling policy and priority of a thread, based on Linux.
873      *
874      * @param tid The identifier of the thread/process to change.
875      * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
876      * @param priority A Linux priority level in a range appropriate for the given policy.
877      *
878      * @throws IllegalArgumentException Throws IllegalArgumentException if
879      * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
880      * @throws SecurityException Throws SecurityException if your process does
881      * not have permission to modify the given thread, or to use the given
882      * scheduling policy or priority.
883      *
884      * {@hide}
885      */
886     public static final native void setThreadScheduler(int tid, int policy, int priority)
887             throws IllegalArgumentException;
888
889     /**
890      * Determine whether the current environment supports multiple processes.
891      * 
892      * @return Returns true if the system can run in multiple processes, else
893      * false if everything is running in a single process.
894      *
895      * @deprecated This method always returns true.  Do not use.
896      */
897     @Deprecated
898     public static final boolean supportsProcesses() {
899         return true;
900     }
901
902     /**
903      * Set the out-of-memory badness adjustment for a process.
904      * 
905      * @param pid The process identifier to set.
906      * @param amt Adjustment value -- linux allows -16 to +15.
907      * 
908      * @return Returns true if the underlying system supports this
909      *         feature, else false.
910      *         
911      * {@hide}
912      */
913     public static final native boolean setOomAdj(int pid, int amt);
914
915     /**
916      * Adjust the swappiness level for a process.
917      *
918      * @param pid The process identifier to set.
919      * @param is_increased Whether swappiness should be increased or default.
920      *
921      * @return Returns true if the underlying system supports this
922      *         feature, else false.
923      *
924      * {@hide}
925      */
926     public static final native boolean setSwappiness(int pid, boolean is_increased);
927
928     /**
929      * Change this process's argv[0] parameter.  This can be useful to show
930      * more descriptive information in things like the 'ps' command.
931      * 
932      * @param text The new name of this process.
933      * 
934      * {@hide}
935      */
936     public static final native void setArgV0(String text);
937
938     /**
939      * Kill the process with the given PID.
940      * Note that, though this API allows us to request to
941      * kill any process based on its PID, the kernel will
942      * still impose standard restrictions on which PIDs you
943      * are actually able to kill.  Typically this means only
944      * the process running the caller's packages/application
945      * and any additional processes created by that app; packages
946      * sharing a common UID will also be able to kill each
947      * other's processes.
948      */
949     public static final void killProcess(int pid) {
950         sendSignal(pid, SIGNAL_KILL);
951     }
952
953     /** @hide */
954     public static final native int setUid(int uid);
955
956     /** @hide */
957     public static final native int setGid(int uid);
958
959     /**
960      * Send a signal to the given process.
961      * 
962      * @param pid The pid of the target process.
963      * @param signal The signal to send.
964      */
965     public static final native void sendSignal(int pid, int signal);
966     
967     /**
968      * @hide
969      * Private impl for avoiding a log message...  DO NOT USE without doing
970      * your own log, or the Android Illuminati will find you some night and
971      * beat you up.
972      */
973     public static final void killProcessQuiet(int pid) {
974         sendSignalQuiet(pid, SIGNAL_KILL);
975     }
976
977     /**
978      * @hide
979      * Private impl for avoiding a log message...  DO NOT USE without doing
980      * your own log, or the Android Illuminati will find you some night and
981      * beat you up.
982      */
983     public static final native void sendSignalQuiet(int pid, int signal);
984     
985     /** @hide */
986     public static final native long getFreeMemory();
987     
988     /** @hide */
989     public static final native long getTotalMemory();
990     
991     /** @hide */
992     public static final native void readProcLines(String path,
993             String[] reqFields, long[] outSizes);
994     
995     /** @hide */
996     public static final native int[] getPids(String path, int[] lastArray);
997     
998     /** @hide */
999     public static final int PROC_TERM_MASK = 0xff;
1000     /** @hide */
1001     public static final int PROC_ZERO_TERM = 0;
1002     /** @hide */
1003     public static final int PROC_SPACE_TERM = (int)' ';
1004     /** @hide */
1005     public static final int PROC_TAB_TERM = (int)'\t';
1006     /** @hide */
1007     public static final int PROC_COMBINE = 0x100;
1008     /** @hide */
1009     public static final int PROC_PARENS = 0x200;
1010     /** @hide */
1011     public static final int PROC_QUOTES = 0x400;
1012     /** @hide */
1013     public static final int PROC_OUT_STRING = 0x1000;
1014     /** @hide */
1015     public static final int PROC_OUT_LONG = 0x2000;
1016     /** @hide */
1017     public static final int PROC_OUT_FLOAT = 0x4000;
1018     
1019     /** @hide */
1020     public static final native boolean readProcFile(String file, int[] format,
1021             String[] outStrings, long[] outLongs, float[] outFloats);
1022     
1023     /** @hide */
1024     public static final native boolean parseProcLine(byte[] buffer, int startIndex, 
1025             int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1026
1027     /** @hide */
1028     public static final native int[] getPidsForCommands(String[] cmds);
1029
1030     /**
1031      * Gets the total Pss value for a given process, in bytes.
1032      * 
1033      * @param pid the process to the Pss for
1034      * @return the total Pss value for the given process in bytes,
1035      *  or -1 if the value cannot be determined 
1036      * @hide
1037      */
1038     public static final native long getPss(int pid);
1039
1040     /**
1041      * Specifies the outcome of having started a process.
1042      * @hide
1043      */
1044     public static final class ProcessStartResult {
1045         /**
1046          * The PID of the newly started process.
1047          * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
1048          */
1049         public int pid;
1050
1051         /**
1052          * True if the process was started with a wrapper attached.
1053          */
1054         public boolean usingWrapper;
1055     }
1056 }