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