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