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