Process.java revision 448be0a62209c977593d81617853a8a428d013df
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    private static long sStartElapsedRealtime;
387    private static long sStartUptimeMillis;
388
389    /**
390     * State for communicating with the zygote process.
391     *
392     * @hide for internal use only.
393     */
394    public static class ZygoteState {
395        final LocalSocket socket;
396        final DataInputStream inputStream;
397        final BufferedWriter writer;
398        final List<String> abiList;
399
400        boolean mClosed;
401
402        private ZygoteState(LocalSocket socket, DataInputStream inputStream,
403                BufferedWriter writer, List<String> abiList) {
404            this.socket = socket;
405            this.inputStream = inputStream;
406            this.writer = writer;
407            this.abiList = abiList;
408        }
409
410        public static ZygoteState connect(String socketAddress) throws IOException {
411            DataInputStream zygoteInputStream = null;
412            BufferedWriter zygoteWriter = null;
413            final LocalSocket zygoteSocket = new LocalSocket();
414
415            try {
416                zygoteSocket.connect(new LocalSocketAddress(socketAddress,
417                        LocalSocketAddress.Namespace.RESERVED));
418
419                zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
420
421                zygoteWriter = new BufferedWriter(new OutputStreamWriter(
422                        zygoteSocket.getOutputStream()), 256);
423            } catch (IOException ex) {
424                try {
425                    zygoteSocket.close();
426                } catch (IOException ignore) {
427                }
428
429                throw ex;
430            }
431
432            String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
433            Log.i("Zygote", "Process: zygote socket opened, supported ABIS: " + abiListString);
434
435            return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
436                    Arrays.asList(abiListString.split(",")));
437        }
438
439        boolean matches(String abi) {
440            return abiList.contains(abi);
441        }
442
443        public void close() {
444            try {
445                socket.close();
446            } catch (IOException ex) {
447                Log.e(LOG_TAG,"I/O exception on routine close", ex);
448            }
449
450            mClosed = true;
451        }
452
453        boolean isClosed() {
454            return mClosed;
455        }
456    }
457
458    /**
459     * The state of the connection to the primary zygote.
460     */
461    static ZygoteState primaryZygoteState;
462
463    /**
464     * The state of the connection to the secondary zygote.
465     */
466    static ZygoteState secondaryZygoteState;
467
468    /**
469     * Start a new process.
470     *
471     * <p>If processes are enabled, a new process is created and the
472     * static main() function of a <var>processClass</var> is executed there.
473     * The process will continue running after this function returns.
474     *
475     * <p>If processes are not enabled, a new thread in the caller's
476     * process is created and main() of <var>processClass</var> called there.
477     *
478     * <p>The niceName parameter, if not an empty string, is a custom name to
479     * give to the process instead of using processClass.  This allows you to
480     * make easily identifyable processes even if you are using the same base
481     * <var>processClass</var> to start them.
482     *
483     * @param processClass The class to use as the process's main entry
484     *                     point.
485     * @param niceName A more readable name to use for the process.
486     * @param uid The user-id under which the process will run.
487     * @param gid The group-id under which the process will run.
488     * @param gids Additional group-ids associated with the process.
489     * @param debugFlags Additional flags.
490     * @param targetSdkVersion The target SDK version for the app.
491     * @param seInfo null-ok SELinux information for the new process.
492     * @param abi non-null the ABI this app should be started with.
493     * @param instructionSet null-ok the instruction set to use.
494     * @param appDataDir null-ok the data directory of the app.
495     * @param zygoteArgs Additional arguments to supply to the zygote process.
496     *
497     * @return An object that describes the result of the attempt to start the process.
498     * @throws RuntimeException on fatal start failure
499     *
500     * {@hide}
501     */
502    public static final ProcessStartResult start(final String processClass,
503                                  final String niceName,
504                                  int uid, int gid, int[] gids,
505                                  int debugFlags, int mountExternal,
506                                  int targetSdkVersion,
507                                  String seInfo,
508                                  String abi,
509                                  String instructionSet,
510                                  String appDataDir,
511                                  String[] zygoteArgs) {
512        try {
513            return startViaZygote(processClass, niceName, uid, gid, gids,
514                    debugFlags, mountExternal, targetSdkVersion, seInfo,
515                    abi, instructionSet, appDataDir, zygoteArgs);
516        } catch (ZygoteStartFailedEx ex) {
517            Log.e(LOG_TAG,
518                    "Starting VM process through Zygote failed");
519            throw new RuntimeException(
520                    "Starting VM process through Zygote failed", ex);
521        }
522    }
523
524    /** retry interval for opening a zygote socket */
525    static final int ZYGOTE_RETRY_MILLIS = 500;
526
527    /**
528     * Queries the zygote for the list of ABIS it supports.
529     *
530     * @throws ZygoteStartFailedEx if the query failed.
531     */
532    private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
533            throws IOException {
534        // Each query starts with the argument count (1 in this case)
535        writer.write("1");
536        // ... followed by a new-line.
537        writer.newLine();
538        // ... followed by our only argument.
539        writer.write("--query-abi-list");
540        writer.newLine();
541        writer.flush();
542
543        // The response is a length prefixed stream of ASCII bytes.
544        int numBytes = inputStream.readInt();
545        byte[] bytes = new byte[numBytes];
546        inputStream.readFully(bytes);
547
548        return new String(bytes, StandardCharsets.US_ASCII);
549    }
550
551    /**
552     * Sends an argument list to the zygote process, which starts a new child
553     * and returns the child's pid. Please note: the present implementation
554     * replaces newlines in the argument list with spaces.
555     *
556     * @throws ZygoteStartFailedEx if process start failed for any reason
557     */
558    private static ProcessStartResult zygoteSendArgsAndGetResult(
559            ZygoteState zygoteState, ArrayList<String> args)
560            throws ZygoteStartFailedEx {
561        try {
562            // Throw early if any of the arguments are malformed. This means we can
563            // avoid writing a partial response to the zygote.
564            int sz = args.size();
565            for (int i = 0; i < sz; i++) {
566                if (args.get(i).indexOf('\n') >= 0) {
567                    throw new ZygoteStartFailedEx("embedded newlines not allowed");
568                }
569            }
570
571            /**
572             * See com.android.internal.os.ZygoteInit.readArgumentList()
573             * Presently the wire format to the zygote process is:
574             * a) a count of arguments (argc, in essence)
575             * b) a number of newline-separated argument strings equal to count
576             *
577             * After the zygote process reads these it will write the pid of
578             * the child or -1 on failure, followed by boolean to
579             * indicate whether a wrapper process was used.
580             */
581            final BufferedWriter writer = zygoteState.writer;
582            final DataInputStream inputStream = zygoteState.inputStream;
583
584            writer.write(Integer.toString(args.size()));
585            writer.newLine();
586
587            for (int i = 0; i < sz; i++) {
588                String arg = args.get(i);
589                writer.write(arg);
590                writer.newLine();
591            }
592
593            writer.flush();
594
595            // Should there be a timeout on this?
596            ProcessStartResult result = new ProcessStartResult();
597
598            // Always read the entire result from the input stream to avoid leaving
599            // bytes in the stream for future process starts to accidentally stumble
600            // upon.
601            result.pid = inputStream.readInt();
602            result.usingWrapper = inputStream.readBoolean();
603
604            if (result.pid < 0) {
605                throw new ZygoteStartFailedEx("fork() failed");
606            }
607            return result;
608        } catch (IOException ex) {
609            zygoteState.close();
610            throw new ZygoteStartFailedEx(ex);
611        }
612    }
613
614    /**
615     * Starts a new process via the zygote mechanism.
616     *
617     * @param processClass Class name whose static main() to run
618     * @param niceName 'nice' process name to appear in ps
619     * @param uid a POSIX uid that the new process should setuid() to
620     * @param gid a POSIX gid that the new process shuold setgid() to
621     * @param gids null-ok; a list of supplementary group IDs that the
622     * new process should setgroup() to.
623     * @param debugFlags Additional flags.
624     * @param targetSdkVersion The target SDK version for the app.
625     * @param seInfo null-ok SELinux information for the new process.
626     * @param abi the ABI the process should use.
627     * @param instructionSet null-ok the instruction set to use.
628     * @param appDataDir null-ok the data directory of the app.
629     * @param extraArgs Additional arguments to supply to the zygote process.
630     * @return An object that describes the result of the attempt to start the process.
631     * @throws ZygoteStartFailedEx if process start failed for any reason
632     */
633    private static ProcessStartResult startViaZygote(final String processClass,
634                                  final String niceName,
635                                  final int uid, final int gid,
636                                  final int[] gids,
637                                  int debugFlags, int mountExternal,
638                                  int targetSdkVersion,
639                                  String seInfo,
640                                  String abi,
641                                  String instructionSet,
642                                  String appDataDir,
643                                  String[] extraArgs)
644                                  throws ZygoteStartFailedEx {
645        synchronized(Process.class) {
646            ArrayList<String> argsForZygote = new ArrayList<String>();
647
648            // --runtime-args, --setuid=, --setgid=,
649            // and --setgroups= must go first
650            argsForZygote.add("--runtime-args");
651            argsForZygote.add("--setuid=" + uid);
652            argsForZygote.add("--setgid=" + gid);
653            if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
654                argsForZygote.add("--enable-jni-logging");
655            }
656            if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
657                argsForZygote.add("--enable-safemode");
658            }
659            if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
660                argsForZygote.add("--enable-debugger");
661            }
662            if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
663                argsForZygote.add("--enable-checkjni");
664            }
665            if ((debugFlags & Zygote.DEBUG_GENERATE_DEBUG_INFO) != 0) {
666                argsForZygote.add("--generate-debug-info");
667            }
668            if ((debugFlags & Zygote.DEBUG_ALWAYS_JIT) != 0) {
669                argsForZygote.add("--always-jit");
670            }
671            if ((debugFlags & Zygote.DEBUG_NATIVE_DEBUGGABLE) != 0) {
672                argsForZygote.add("--native-debuggable");
673            }
674            if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
675                argsForZygote.add("--enable-assert");
676            }
677            if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
678                argsForZygote.add("--mount-external-default");
679            } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
680                argsForZygote.add("--mount-external-read");
681            } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
682                argsForZygote.add("--mount-external-write");
683            }
684            argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
685
686            //TODO optionally enable debuger
687            //argsForZygote.add("--enable-debugger");
688
689            // --setgroups is a comma-separated list
690            if (gids != null && gids.length > 0) {
691                StringBuilder sb = new StringBuilder();
692                sb.append("--setgroups=");
693
694                int sz = gids.length;
695                for (int i = 0; i < sz; i++) {
696                    if (i != 0) {
697                        sb.append(',');
698                    }
699                    sb.append(gids[i]);
700                }
701
702                argsForZygote.add(sb.toString());
703            }
704
705            if (niceName != null) {
706                argsForZygote.add("--nice-name=" + niceName);
707            }
708
709            if (seInfo != null) {
710                argsForZygote.add("--seinfo=" + seInfo);
711            }
712
713            if (instructionSet != null) {
714                argsForZygote.add("--instruction-set=" + instructionSet);
715            }
716
717            if (appDataDir != null) {
718                argsForZygote.add("--app-data-dir=" + appDataDir);
719            }
720
721            argsForZygote.add(processClass);
722
723            if (extraArgs != null) {
724                for (String arg : extraArgs) {
725                    argsForZygote.add(arg);
726                }
727            }
728
729            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
730        }
731    }
732
733    /**
734     * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block and retry if the
735     * zygote is unresponsive. This method is a no-op if a connection is already open.
736     *
737     * @hide
738     */
739    public static void establishZygoteConnectionForAbi(String abi) {
740        try {
741            openZygoteSocketIfNeeded(abi);
742        } catch (ZygoteStartFailedEx ex) {
743            throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
744        }
745    }
746
747    /**
748     * Tries to open socket to Zygote process if not already open. If
749     * already open, does nothing.  May block and retry.
750     */
751    private static ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
752        if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
753            try {
754                primaryZygoteState = ZygoteState.connect(ZYGOTE_SOCKET);
755            } catch (IOException ioe) {
756                throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
757            }
758        }
759
760        if (primaryZygoteState.matches(abi)) {
761            return primaryZygoteState;
762        }
763
764        // The primary zygote didn't match. Try the secondary.
765        if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
766            try {
767            secondaryZygoteState = ZygoteState.connect(SECONDARY_ZYGOTE_SOCKET);
768            } catch (IOException ioe) {
769                throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
770            }
771        }
772
773        if (secondaryZygoteState.matches(abi)) {
774            return secondaryZygoteState;
775        }
776
777        throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
778    }
779
780    /**
781     * Returns elapsed milliseconds of the time this process has run.
782     * @return  Returns the number of milliseconds this process has return.
783     */
784    public static final native long getElapsedCpuTime();
785
786    /**
787     * Return the {@link SystemClock#elapsedRealtime()} at which this process was started.
788     */
789    public static final long getStartElapsedRealtime() {
790        return sStartElapsedRealtime;
791    }
792
793    /**
794     * Return the {@link SystemClock#uptimeMillis()} at which this process was started.
795     */
796    public static final long getStartUptimeMillis() {
797        return sStartUptimeMillis;
798    }
799
800    /** @hide */
801    public static final void setStartTimes(long elapsedRealtime, long uptimeMillis) {
802        sStartElapsedRealtime = elapsedRealtime;
803        sStartUptimeMillis = uptimeMillis;
804    }
805
806    /**
807     * Returns true if the current process is a 64-bit runtime.
808     */
809    public static final boolean is64Bit() {
810        return VMRuntime.getRuntime().is64Bit();
811    }
812
813    /**
814     * Returns the identifier of this process, which can be used with
815     * {@link #killProcess} and {@link #sendSignal}.
816     */
817    public static final int myPid() {
818        return Os.getpid();
819    }
820
821    /**
822     * Returns the identifier of this process' parent.
823     * @hide
824     */
825    public static final int myPpid() {
826        return Os.getppid();
827    }
828
829    /**
830     * Returns the identifier of the calling thread, which be used with
831     * {@link #setThreadPriority(int, int)}.
832     */
833    public static final int myTid() {
834        return Os.gettid();
835    }
836
837    /**
838     * Returns the identifier of this process's uid.  This is the kernel uid
839     * that the process is running under, which is the identity of its
840     * app-specific sandbox.  It is different from {@link #myUserHandle} in that
841     * a uid identifies a specific app sandbox in a specific user.
842     */
843    public static final int myUid() {
844        return Os.getuid();
845    }
846
847    /**
848     * Returns this process's user handle.  This is the
849     * user the process is running under.  It is distinct from
850     * {@link #myUid()} in that a particular user will have multiple
851     * distinct apps running under it each with their own uid.
852     */
853    public static UserHandle myUserHandle() {
854        return UserHandle.of(UserHandle.getUserId(myUid()));
855    }
856
857    /**
858     * Returns whether the given uid belongs to an application.
859     * @param uid A kernel uid.
860     * @return Whether the uid corresponds to an application sandbox running in
861     *     a specific user.
862     */
863    public static boolean isApplicationUid(int uid) {
864        return UserHandle.isApp(uid);
865    }
866
867    /**
868     * Returns whether the current process is in an isolated sandbox.
869     * @hide
870     */
871    public static final boolean isIsolated() {
872        return isIsolated(myUid());
873    }
874
875    /** {@hide} */
876    public static final boolean isIsolated(int uid) {
877        uid = UserHandle.getAppId(uid);
878        return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
879    }
880
881    /**
882     * Returns the UID assigned to a particular user name, or -1 if there is
883     * none.  If the given string consists of only numbers, it is converted
884     * directly to a uid.
885     */
886    public static final native int getUidForName(String name);
887
888    /**
889     * Returns the GID assigned to a particular user name, or -1 if there is
890     * none.  If the given string consists of only numbers, it is converted
891     * directly to a gid.
892     */
893    public static final native int getGidForName(String name);
894
895    /**
896     * Returns a uid for a currently running process.
897     * @param pid the process id
898     * @return the uid of the process, or -1 if the process is not running.
899     * @hide pending API council review
900     */
901    public static final int getUidForPid(int pid) {
902        String[] procStatusLabels = { "Uid:" };
903        long[] procStatusValues = new long[1];
904        procStatusValues[0] = -1;
905        Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
906        return (int) procStatusValues[0];
907    }
908
909    /**
910     * Returns the parent process id for a currently running process.
911     * @param pid the process id
912     * @return the parent process id of the process, or -1 if the process is not running.
913     * @hide
914     */
915    public static final int getParentPid(int pid) {
916        String[] procStatusLabels = { "PPid:" };
917        long[] procStatusValues = new long[1];
918        procStatusValues[0] = -1;
919        Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
920        return (int) procStatusValues[0];
921    }
922
923    /**
924     * Returns the thread group leader id for a currently running thread.
925     * @param tid the thread id
926     * @return the thread group leader id of the thread, or -1 if the thread is not running.
927     *         This is same as what getpid(2) would return if called by tid.
928     * @hide
929     */
930    public static final int getThreadGroupLeader(int tid) {
931        String[] procStatusLabels = { "Tgid:" };
932        long[] procStatusValues = new long[1];
933        procStatusValues[0] = -1;
934        Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
935        return (int) procStatusValues[0];
936    }
937
938    /**
939     * Set the priority of a thread, based on Linux priorities.
940     *
941     * @param tid The identifier of the thread/process to change.
942     * @param priority A Linux priority level, from -20 for highest scheduling
943     * priority to 19 for lowest scheduling priority.
944     *
945     * @throws IllegalArgumentException Throws IllegalArgumentException if
946     * <var>tid</var> does not exist.
947     * @throws SecurityException Throws SecurityException if your process does
948     * not have permission to modify the given thread, or to use the given
949     * priority.
950     */
951    public static final native void setThreadPriority(int tid, int priority)
952            throws IllegalArgumentException, SecurityException;
953
954    /**
955     * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
956     * throw an exception if passed a background-level thread priority.  This is only
957     * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
958     *
959     * @hide
960     */
961    public static final native void setCanSelfBackground(boolean backgroundOk);
962
963    /**
964     * Sets the scheduling group for a thread.
965     * @hide
966     * @param tid The identifier of the thread to change.
967     * @param group The target group for this thread from THREAD_GROUP_*.
968     *
969     * @throws IllegalArgumentException Throws IllegalArgumentException if
970     * <var>tid</var> does not exist.
971     * @throws SecurityException Throws SecurityException if your process does
972     * not have permission to modify the given thread, or to use the given
973     * priority.
974     * If the thread is a thread group leader, that is it's gettid() == getpid(),
975     * then the other threads in the same thread group are _not_ affected.
976     */
977    public static final native void setThreadGroup(int tid, int group)
978            throws IllegalArgumentException, SecurityException;
979
980    /**
981     * Sets the scheduling group for a process and all child threads
982     * @hide
983     * @param pid The identifier of the process to change.
984     * @param group The target group for this process from THREAD_GROUP_*.
985     *
986     * @throws IllegalArgumentException Throws IllegalArgumentException if
987     * <var>tid</var> does not exist.
988     * @throws SecurityException Throws SecurityException if your process does
989     * not have permission to modify the given thread, or to use the given
990     * priority.
991     *
992     * group == THREAD_GROUP_DEFAULT means to move all non-background priority
993     * threads to the foreground scheduling group, but to leave background
994     * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
995     * threads, regardless of priority, to the background scheduling group.
996     * group == THREAD_GROUP_FOREGROUND is not allowed.
997     */
998    public static final native void setProcessGroup(int pid, int group)
999            throws IllegalArgumentException, SecurityException;
1000
1001    /**
1002     * Return the scheduling group of requested process.
1003     *
1004     * @hide
1005     */
1006    public static final native int getProcessGroup(int pid)
1007            throws IllegalArgumentException, SecurityException;
1008
1009    /**
1010     * On some devices, the foreground process may have one or more CPU
1011     * cores exclusively reserved for it. This method can be used to
1012     * retrieve which cores that are (if any), so the calling process
1013     * can then use sched_setaffinity() to lock a thread to these cores.
1014     * Note that the calling process must currently be running in the
1015     * foreground for this method to return any cores.
1016     *
1017     * The CPU core(s) exclusively reserved for the foreground process will
1018     * stay reserved for as long as the process stays in the foreground.
1019     *
1020     * As soon as a process leaves the foreground, those CPU cores will
1021     * no longer be reserved for it, and will most likely be reserved for
1022     * the new foreground process. It's not necessary to change the affinity
1023     * of your process when it leaves the foreground (if you had previously
1024     * set it to use a reserved core); the OS will automatically take care
1025     * of resetting the affinity at that point.
1026     *
1027     * @return an array of integers, indicating the CPU cores exclusively
1028     * reserved for this process. The array will have length zero if no
1029     * CPU cores are exclusively reserved for this process at this point
1030     * in time.
1031     */
1032    public static final native int[] getExclusiveCores();
1033
1034    /**
1035     * Set the priority of the calling thread, based on Linux priorities.  See
1036     * {@link #setThreadPriority(int, int)} for more information.
1037     *
1038     * @param priority A Linux priority level, from -20 for highest scheduling
1039     * priority to 19 for lowest scheduling priority.
1040     *
1041     * @throws IllegalArgumentException Throws IllegalArgumentException if
1042     * <var>tid</var> does not exist.
1043     * @throws SecurityException Throws SecurityException if your process does
1044     * not have permission to modify the given thread, or to use the given
1045     * priority.
1046     *
1047     * @see #setThreadPriority(int, int)
1048     */
1049    public static final native void setThreadPriority(int priority)
1050            throws IllegalArgumentException, SecurityException;
1051
1052    /**
1053     * Return the current priority of a thread, based on Linux priorities.
1054     *
1055     * @param tid The identifier of the thread/process to change.
1056     *
1057     * @return Returns the current priority, as a Linux priority level,
1058     * from -20 for highest scheduling priority to 19 for lowest scheduling
1059     * priority.
1060     *
1061     * @throws IllegalArgumentException Throws IllegalArgumentException if
1062     * <var>tid</var> does not exist.
1063     */
1064    public static final native int getThreadPriority(int tid)
1065            throws IllegalArgumentException;
1066
1067    /**
1068     * Set the scheduling policy and priority of a thread, based on Linux.
1069     *
1070     * @param tid The identifier of the thread/process to change.
1071     * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
1072     * @param priority A Linux priority level in a range appropriate for the given policy.
1073     *
1074     * @throws IllegalArgumentException Throws IllegalArgumentException if
1075     * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
1076     * @throws SecurityException Throws SecurityException if your process does
1077     * not have permission to modify the given thread, or to use the given
1078     * scheduling policy or priority.
1079     *
1080     * {@hide}
1081     */
1082    public static final native void setThreadScheduler(int tid, int policy, int priority)
1083            throws IllegalArgumentException;
1084
1085    /**
1086     * Determine whether the current environment supports multiple processes.
1087     *
1088     * @return Returns true if the system can run in multiple processes, else
1089     * false if everything is running in a single process.
1090     *
1091     * @deprecated This method always returns true.  Do not use.
1092     */
1093    @Deprecated
1094    public static final boolean supportsProcesses() {
1095        return true;
1096    }
1097
1098    /**
1099     * Adjust the swappiness level for a process.
1100     *
1101     * @param pid The process identifier to set.
1102     * @param is_increased Whether swappiness should be increased or default.
1103     *
1104     * @return Returns true if the underlying system supports this
1105     *         feature, else false.
1106     *
1107     * {@hide}
1108     */
1109    public static final native boolean setSwappiness(int pid, boolean is_increased);
1110
1111    /**
1112     * Change this process's argv[0] parameter.  This can be useful to show
1113     * more descriptive information in things like the 'ps' command.
1114     *
1115     * @param text The new name of this process.
1116     *
1117     * {@hide}
1118     */
1119    public static final native void setArgV0(String text);
1120
1121    /**
1122     * Kill the process with the given PID.
1123     * Note that, though this API allows us to request to
1124     * kill any process based on its PID, the kernel will
1125     * still impose standard restrictions on which PIDs you
1126     * are actually able to kill.  Typically this means only
1127     * the process running the caller's packages/application
1128     * and any additional processes created by that app; packages
1129     * sharing a common UID will also be able to kill each
1130     * other's processes.
1131     */
1132    public static final void killProcess(int pid) {
1133        sendSignal(pid, SIGNAL_KILL);
1134    }
1135
1136    /** @hide */
1137    public static final native int setUid(int uid);
1138
1139    /** @hide */
1140    public static final native int setGid(int uid);
1141
1142    /**
1143     * Send a signal to the given process.
1144     *
1145     * @param pid The pid of the target process.
1146     * @param signal The signal to send.
1147     */
1148    public static final native void sendSignal(int pid, int signal);
1149
1150    /**
1151     * @hide
1152     * Private impl for avoiding a log message...  DO NOT USE without doing
1153     * your own log, or the Android Illuminati will find you some night and
1154     * beat you up.
1155     */
1156    public static final void killProcessQuiet(int pid) {
1157        sendSignalQuiet(pid, SIGNAL_KILL);
1158    }
1159
1160    /**
1161     * @hide
1162     * Private impl for avoiding a log message...  DO NOT USE without doing
1163     * your own log, or the Android Illuminati will find you some night and
1164     * beat you up.
1165     */
1166    public static final native void sendSignalQuiet(int pid, int signal);
1167
1168    /** @hide */
1169    public static final native long getFreeMemory();
1170
1171    /** @hide */
1172    public static final native long getTotalMemory();
1173
1174    /** @hide */
1175    public static final native void readProcLines(String path,
1176            String[] reqFields, long[] outSizes);
1177
1178    /** @hide */
1179    public static final native int[] getPids(String path, int[] lastArray);
1180
1181    /** @hide */
1182    public static final int PROC_TERM_MASK = 0xff;
1183    /** @hide */
1184    public static final int PROC_ZERO_TERM = 0;
1185    /** @hide */
1186    public static final int PROC_SPACE_TERM = (int)' ';
1187    /** @hide */
1188    public static final int PROC_TAB_TERM = (int)'\t';
1189    /** @hide */
1190    public static final int PROC_COMBINE = 0x100;
1191    /** @hide */
1192    public static final int PROC_PARENS = 0x200;
1193    /** @hide */
1194    public static final int PROC_QUOTES = 0x400;
1195    /** @hide */
1196    public static final int PROC_CHAR = 0x800;
1197    /** @hide */
1198    public static final int PROC_OUT_STRING = 0x1000;
1199    /** @hide */
1200    public static final int PROC_OUT_LONG = 0x2000;
1201    /** @hide */
1202    public static final int PROC_OUT_FLOAT = 0x4000;
1203
1204    /** @hide */
1205    public static final native boolean readProcFile(String file, int[] format,
1206            String[] outStrings, long[] outLongs, float[] outFloats);
1207
1208    /** @hide */
1209    public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1210            int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1211
1212    /** @hide */
1213    public static final native int[] getPidsForCommands(String[] cmds);
1214
1215    /**
1216     * Gets the total Pss value for a given process, in bytes.
1217     *
1218     * @param pid the process to the Pss for
1219     * @return the total Pss value for the given process in bytes,
1220     *  or -1 if the value cannot be determined
1221     * @hide
1222     */
1223    public static final native long getPss(int pid);
1224
1225    /**
1226     * Specifies the outcome of having started a process.
1227     * @hide
1228     */
1229    public static final class ProcessStartResult {
1230        /**
1231         * The PID of the newly started process.
1232         * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
1233         */
1234        public int pid;
1235
1236        /**
1237         * True if the process was started with a wrapper attached.
1238         */
1239        public boolean usingWrapper;
1240    }
1241
1242    /**
1243     * Kill all processes in a process group started for the given
1244     * pid.
1245     * @hide
1246     */
1247    public static final native int killProcessGroup(int uid, int pid);
1248
1249    /**
1250     * Remove all process groups.  Expected to be called when ActivityManager
1251     * is restarted.
1252     * @hide
1253     */
1254    public static final native void removeAllProcessGroups();
1255}
1256