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