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