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