Process.java revision 34385d352da19805ae948215e2edbeedd16b7941
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        // TODO: Get rid of this. This is a temporary workaround until all the
711        // compilation related pieces for the dual zygote stack are ready.
712        // b/3647418.
713        if (System.getenv("ANDROID_SOCKET_" + SECONDARY_ZYGOTE_SOCKET) == null) {
714            Log.e(LOG_TAG, "Forcing app to primary zygote, secondary unavailable (ABI= " + abi + ")");
715            // Should be :
716            // throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
717            return primaryZygoteState;
718        }
719
720        // The primary zygote didn't match. Try the secondary.
721        if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
722            secondaryZygoteState = ZygoteState.connect(SECONDARY_ZYGOTE_SOCKET,
723                    getNumTries(secondaryZygoteState));
724        }
725
726        if (secondaryZygoteState.matches(abi)) {
727            return secondaryZygoteState;
728        }
729
730        throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
731    }
732
733    /**
734     * Returns elapsed milliseconds of the time this process has run.
735     * @return  Returns the number of milliseconds this process has return.
736     */
737    public static final native long getElapsedCpuTime();
738
739    /**
740     * Returns the identifier of this process, which can be used with
741     * {@link #killProcess} and {@link #sendSignal}.
742     */
743    public static final int myPid() {
744        return Os.getpid();
745    }
746
747    /**
748     * Returns the identifier of this process' parent.
749     * @hide
750     */
751    public static final int myPpid() {
752        return Os.getppid();
753    }
754
755    /**
756     * Returns the identifier of the calling thread, which be used with
757     * {@link #setThreadPriority(int, int)}.
758     */
759    public static final int myTid() {
760        return Os.gettid();
761    }
762
763    /**
764     * Returns the identifier of this process's uid.  This is the kernel uid
765     * that the process is running under, which is the identity of its
766     * app-specific sandbox.  It is different from {@link #myUserHandle} in that
767     * a uid identifies a specific app sandbox in a specific user.
768     */
769    public static final int myUid() {
770        return Os.getuid();
771    }
772
773    /**
774     * Returns this process's user handle.  This is the
775     * user the process is running under.  It is distinct from
776     * {@link #myUid()} in that a particular user will have multiple
777     * distinct apps running under it each with their own uid.
778     */
779    public static final UserHandle myUserHandle() {
780        return new UserHandle(UserHandle.getUserId(myUid()));
781    }
782
783    /**
784     * Returns whether the current process is in an isolated sandbox.
785     * @hide
786     */
787    public static final boolean isIsolated() {
788        int uid = UserHandle.getAppId(myUid());
789        return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
790    }
791
792    /**
793     * Returns the UID assigned to a particular user name, or -1 if there is
794     * none.  If the given string consists of only numbers, it is converted
795     * directly to a uid.
796     */
797    public static final native int getUidForName(String name);
798
799    /**
800     * Returns the GID assigned to a particular user name, or -1 if there is
801     * none.  If the given string consists of only numbers, it is converted
802     * directly to a gid.
803     */
804    public static final native int getGidForName(String name);
805
806    /**
807     * Returns a uid for a currently running process.
808     * @param pid the process id
809     * @return the uid of the process, or -1 if the process is not running.
810     * @hide pending API council review
811     */
812    public static final int getUidForPid(int pid) {
813        String[] procStatusLabels = { "Uid:" };
814        long[] procStatusValues = new long[1];
815        procStatusValues[0] = -1;
816        Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
817        return (int) procStatusValues[0];
818    }
819
820    /**
821     * Returns the parent process id for a currently running process.
822     * @param pid the process id
823     * @return the parent process id of the process, or -1 if the process is not running.
824     * @hide
825     */
826    public static final int getParentPid(int pid) {
827        String[] procStatusLabels = { "PPid:" };
828        long[] procStatusValues = new long[1];
829        procStatusValues[0] = -1;
830        Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
831        return (int) procStatusValues[0];
832    }
833
834    /**
835     * Returns the thread group leader id for a currently running thread.
836     * @param tid the thread id
837     * @return the thread group leader id of the thread, or -1 if the thread is not running.
838     *         This is same as what getpid(2) would return if called by tid.
839     * @hide
840     */
841    public static final int getThreadGroupLeader(int tid) {
842        String[] procStatusLabels = { "Tgid:" };
843        long[] procStatusValues = new long[1];
844        procStatusValues[0] = -1;
845        Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
846        return (int) procStatusValues[0];
847    }
848
849    /**
850     * Set the priority of a thread, based on Linux priorities.
851     *
852     * @param tid The identifier of the thread/process to change.
853     * @param priority A Linux priority level, from -20 for highest scheduling
854     * priority to 19 for lowest scheduling priority.
855     *
856     * @throws IllegalArgumentException Throws IllegalArgumentException if
857     * <var>tid</var> does not exist.
858     * @throws SecurityException Throws SecurityException if your process does
859     * not have permission to modify the given thread, or to use the given
860     * priority.
861     */
862    public static final native void setThreadPriority(int tid, int priority)
863            throws IllegalArgumentException, SecurityException;
864
865    /**
866     * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
867     * throw an exception if passed a background-level thread priority.  This is only
868     * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
869     *
870     * @hide
871     */
872    public static final native void setCanSelfBackground(boolean backgroundOk);
873
874    /**
875     * Sets the scheduling group for a thread.
876     * @hide
877     * @param tid The identifier of the thread to change.
878     * @param group The target group for this thread from THREAD_GROUP_*.
879     *
880     * @throws IllegalArgumentException Throws IllegalArgumentException if
881     * <var>tid</var> does not exist.
882     * @throws SecurityException Throws SecurityException if your process does
883     * not have permission to modify the given thread, or to use the given
884     * priority.
885     * If the thread is a thread group leader, that is it's gettid() == getpid(),
886     * then the other threads in the same thread group are _not_ affected.
887     */
888    public static final native void setThreadGroup(int tid, int group)
889            throws IllegalArgumentException, SecurityException;
890
891    /**
892     * Sets the scheduling group for a process and all child threads
893     * @hide
894     * @param pid The identifier of the process to change.
895     * @param group The target group for this process from THREAD_GROUP_*.
896     *
897     * @throws IllegalArgumentException Throws IllegalArgumentException if
898     * <var>tid</var> does not exist.
899     * @throws SecurityException Throws SecurityException if your process does
900     * not have permission to modify the given thread, or to use the given
901     * priority.
902     *
903     * group == THREAD_GROUP_DEFAULT means to move all non-background priority
904     * threads to the foreground scheduling group, but to leave background
905     * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
906     * threads, regardless of priority, to the background scheduling group.
907     * group == THREAD_GROUP_FOREGROUND is not allowed.
908     */
909    public static final native void setProcessGroup(int pid, int group)
910            throws IllegalArgumentException, SecurityException;
911
912    /**
913     * Return the scheduling group of requested process.
914     *
915     * @hide
916     */
917    public static final native int getProcessGroup(int pid)
918            throws IllegalArgumentException, SecurityException;
919
920    /**
921     * Set the priority of the calling thread, based on Linux priorities.  See
922     * {@link #setThreadPriority(int, int)} for more information.
923     *
924     * @param priority A Linux priority level, from -20 for highest scheduling
925     * priority to 19 for lowest scheduling priority.
926     *
927     * @throws IllegalArgumentException Throws IllegalArgumentException if
928     * <var>tid</var> does not exist.
929     * @throws SecurityException Throws SecurityException if your process does
930     * not have permission to modify the given thread, or to use the given
931     * priority.
932     *
933     * @see #setThreadPriority(int, int)
934     */
935    public static final native void setThreadPriority(int priority)
936            throws IllegalArgumentException, SecurityException;
937
938    /**
939     * Return the current priority of a thread, based on Linux priorities.
940     *
941     * @param tid The identifier of the thread/process to change.
942     *
943     * @return Returns the current priority, as a Linux priority level,
944     * from -20 for highest scheduling priority to 19 for lowest scheduling
945     * priority.
946     *
947     * @throws IllegalArgumentException Throws IllegalArgumentException if
948     * <var>tid</var> does not exist.
949     */
950    public static final native int getThreadPriority(int tid)
951            throws IllegalArgumentException;
952
953    /**
954     * Set the scheduling policy and priority of a thread, based on Linux.
955     *
956     * @param tid The identifier of the thread/process to change.
957     * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
958     * @param priority A Linux priority level in a range appropriate for the given policy.
959     *
960     * @throws IllegalArgumentException Throws IllegalArgumentException if
961     * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
962     * @throws SecurityException Throws SecurityException if your process does
963     * not have permission to modify the given thread, or to use the given
964     * scheduling policy or priority.
965     *
966     * {@hide}
967     */
968    public static final native void setThreadScheduler(int tid, int policy, int priority)
969            throws IllegalArgumentException;
970
971    /**
972     * Determine whether the current environment supports multiple processes.
973     *
974     * @return Returns true if the system can run in multiple processes, else
975     * false if everything is running in a single process.
976     *
977     * @deprecated This method always returns true.  Do not use.
978     */
979    @Deprecated
980    public static final boolean supportsProcesses() {
981        return true;
982    }
983
984    /**
985     * Set the out-of-memory badness adjustment for a process.
986     *
987     * @param pid The process identifier to set.
988     * @param amt Adjustment value -- linux allows -16 to +15.
989     *
990     * @return Returns true if the underlying system supports this
991     *         feature, else false.
992     *
993     * {@hide}
994     */
995    public static final native boolean setOomAdj(int pid, int amt);
996
997    /**
998     * Adjust the swappiness level for a process.
999     *
1000     * @param pid The process identifier to set.
1001     * @param is_increased Whether swappiness should be increased or default.
1002     *
1003     * @return Returns true if the underlying system supports this
1004     *         feature, else false.
1005     *
1006     * {@hide}
1007     */
1008    public static final native boolean setSwappiness(int pid, boolean is_increased);
1009
1010    /**
1011     * Change this process's argv[0] parameter.  This can be useful to show
1012     * more descriptive information in things like the 'ps' command.
1013     *
1014     * @param text The new name of this process.
1015     *
1016     * {@hide}
1017     */
1018    public static final native void setArgV0(String text);
1019
1020    /**
1021     * Kill the process with the given PID.
1022     * Note that, though this API allows us to request to
1023     * kill any process based on its PID, the kernel will
1024     * still impose standard restrictions on which PIDs you
1025     * are actually able to kill.  Typically this means only
1026     * the process running the caller's packages/application
1027     * and any additional processes created by that app; packages
1028     * sharing a common UID will also be able to kill each
1029     * other's processes.
1030     */
1031    public static final void killProcess(int pid) {
1032        sendSignal(pid, SIGNAL_KILL);
1033    }
1034
1035    /** @hide */
1036    public static final native int setUid(int uid);
1037
1038    /** @hide */
1039    public static final native int setGid(int uid);
1040
1041    /**
1042     * Send a signal to the given process.
1043     *
1044     * @param pid The pid of the target process.
1045     * @param signal The signal to send.
1046     */
1047    public static final native void sendSignal(int pid, int signal);
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 void killProcessQuiet(int pid) {
1056        sendSignalQuiet(pid, SIGNAL_KILL);
1057    }
1058
1059    /**
1060     * @hide
1061     * Private impl for avoiding a log message...  DO NOT USE without doing
1062     * your own log, or the Android Illuminati will find you some night and
1063     * beat you up.
1064     */
1065    public static final native void sendSignalQuiet(int pid, int signal);
1066
1067    /** @hide */
1068    public static final native long getFreeMemory();
1069
1070    /** @hide */
1071    public static final native long getTotalMemory();
1072
1073    /** @hide */
1074    public static final native void readProcLines(String path,
1075            String[] reqFields, long[] outSizes);
1076
1077    /** @hide */
1078    public static final native int[] getPids(String path, int[] lastArray);
1079
1080    /** @hide */
1081    public static final int PROC_TERM_MASK = 0xff;
1082    /** @hide */
1083    public static final int PROC_ZERO_TERM = 0;
1084    /** @hide */
1085    public static final int PROC_SPACE_TERM = (int)' ';
1086    /** @hide */
1087    public static final int PROC_TAB_TERM = (int)'\t';
1088    /** @hide */
1089    public static final int PROC_COMBINE = 0x100;
1090    /** @hide */
1091    public static final int PROC_PARENS = 0x200;
1092    /** @hide */
1093    public static final int PROC_QUOTES = 0x400;
1094    /** @hide */
1095    public static final int PROC_OUT_STRING = 0x1000;
1096    /** @hide */
1097    public static final int PROC_OUT_LONG = 0x2000;
1098    /** @hide */
1099    public static final int PROC_OUT_FLOAT = 0x4000;
1100
1101    /** @hide */
1102    public static final native boolean readProcFile(String file, int[] format,
1103            String[] outStrings, long[] outLongs, float[] outFloats);
1104
1105    /** @hide */
1106    public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1107            int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1108
1109    /** @hide */
1110    public static final native int[] getPidsForCommands(String[] cmds);
1111
1112    /**
1113     * Gets the total Pss value for a given process, in bytes.
1114     *
1115     * @param pid the process to the Pss for
1116     * @return the total Pss value for the given process in bytes,
1117     *  or -1 if the value cannot be determined
1118     * @hide
1119     */
1120    public static final native long getPss(int pid);
1121
1122    /**
1123     * Specifies the outcome of having started a process.
1124     * @hide
1125     */
1126    public static final class ProcessStartResult {
1127        /**
1128         * The PID of the newly started process.
1129         * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
1130         */
1131        public int pid;
1132
1133        /**
1134         * True if the process was started with a wrapper attached.
1135         */
1136        public boolean usingWrapper;
1137    }
1138}
1139