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