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