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