Process.java revision ee0cdce2a80f8cc033378134e37092bc467c0f38
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_ENABLE_JIT) != 0) {
636                argsForZygote.add("--enable-jit");
637            }
638            if ((debugFlags & Zygote.DEBUG_GENERATE_CFI) != 0) {
639                argsForZygote.add("--generate-cfi");
640            }
641            if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
642                argsForZygote.add("--enable-assert");
643            }
644            if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
645                argsForZygote.add("--mount-external-default");
646            }
647            argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
648
649            //TODO optionally enable debuger
650            //argsForZygote.add("--enable-debugger");
651
652            // --setgroups is a comma-separated list
653            if (gids != null && gids.length > 0) {
654                StringBuilder sb = new StringBuilder();
655                sb.append("--setgroups=");
656
657                int sz = gids.length;
658                for (int i = 0; i < sz; i++) {
659                    if (i != 0) {
660                        sb.append(',');
661                    }
662                    sb.append(gids[i]);
663                }
664
665                argsForZygote.add(sb.toString());
666            }
667
668            if (niceName != null) {
669                argsForZygote.add("--nice-name=" + niceName);
670            }
671
672            if (seInfo != null) {
673                argsForZygote.add("--seinfo=" + seInfo);
674            }
675
676            if (instructionSet != null) {
677                argsForZygote.add("--instruction-set=" + instructionSet);
678            }
679
680            if (appDataDir != null) {
681                argsForZygote.add("--app-data-dir=" + appDataDir);
682            }
683
684            argsForZygote.add(processClass);
685
686            if (extraArgs != null) {
687                for (String arg : extraArgs) {
688                    argsForZygote.add(arg);
689                }
690            }
691
692            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
693        }
694    }
695
696    /**
697     * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block and retry if the
698     * zygote is unresponsive. This method is a no-op if a connection is already open.
699     *
700     * @hide
701     */
702    public static void establishZygoteConnectionForAbi(String abi) {
703        try {
704            openZygoteSocketIfNeeded(abi);
705        } catch (ZygoteStartFailedEx ex) {
706            throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
707        }
708    }
709
710    /**
711     * Tries to open socket to Zygote process if not already open. If
712     * already open, does nothing.  May block and retry.
713     */
714    private static ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
715        if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
716            try {
717                primaryZygoteState = ZygoteState.connect(ZYGOTE_SOCKET);
718            } catch (IOException ioe) {
719                throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
720            }
721        }
722
723        if (primaryZygoteState.matches(abi)) {
724            return primaryZygoteState;
725        }
726
727        // The primary zygote didn't match. Try the secondary.
728        if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
729            try {
730            secondaryZygoteState = ZygoteState.connect(SECONDARY_ZYGOTE_SOCKET);
731            } catch (IOException ioe) {
732                throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
733            }
734        }
735
736        if (secondaryZygoteState.matches(abi)) {
737            return secondaryZygoteState;
738        }
739
740        throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
741    }
742
743    /**
744     * Returns elapsed milliseconds of the time this process has run.
745     * @return  Returns the number of milliseconds this process has return.
746     */
747    public static final native long getElapsedCpuTime();
748
749    /**
750     * Returns true if the current process is a 64-bit runtime.
751     */
752    public static final boolean is64Bit() {
753        return VMRuntime.getRuntime().is64Bit();
754    }
755
756    /**
757     * Returns the identifier of this process, which can be used with
758     * {@link #killProcess} and {@link #sendSignal}.
759     */
760    public static final int myPid() {
761        return Os.getpid();
762    }
763
764    /**
765     * Returns the identifier of this process' parent.
766     * @hide
767     */
768    public static final int myPpid() {
769        return Os.getppid();
770    }
771
772    /**
773     * Returns the identifier of the calling thread, which be used with
774     * {@link #setThreadPriority(int, int)}.
775     */
776    public static final int myTid() {
777        return Os.gettid();
778    }
779
780    /**
781     * Returns the identifier of this process's uid.  This is the kernel uid
782     * that the process is running under, which is the identity of its
783     * app-specific sandbox.  It is different from {@link #myUserHandle} in that
784     * a uid identifies a specific app sandbox in a specific user.
785     */
786    public static final int myUid() {
787        return Os.getuid();
788    }
789
790    /**
791     * Returns this process's user handle.  This is the
792     * user the process is running under.  It is distinct from
793     * {@link #myUid()} in that a particular user will have multiple
794     * distinct apps running under it each with their own uid.
795     */
796    public static final UserHandle myUserHandle() {
797        return new UserHandle(UserHandle.getUserId(myUid()));
798    }
799
800    /**
801     * Returns whether the current process is in an isolated sandbox.
802     * @hide
803     */
804    public static final boolean isIsolated() {
805        int uid = UserHandle.getAppId(myUid());
806        return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
807    }
808
809    /**
810     * Returns the UID assigned to a particular user name, or -1 if there is
811     * none.  If the given string consists of only numbers, it is converted
812     * directly to a uid.
813     */
814    public static final native int getUidForName(String name);
815
816    /**
817     * Returns the GID assigned to a particular user name, or -1 if there is
818     * none.  If the given string consists of only numbers, it is converted
819     * directly to a gid.
820     */
821    public static final native int getGidForName(String name);
822
823    /**
824     * Returns a uid for a currently running process.
825     * @param pid the process id
826     * @return the uid of the process, or -1 if the process is not running.
827     * @hide pending API council review
828     */
829    public static final int getUidForPid(int pid) {
830        String[] procStatusLabels = { "Uid:" };
831        long[] procStatusValues = new long[1];
832        procStatusValues[0] = -1;
833        Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
834        return (int) procStatusValues[0];
835    }
836
837    /**
838     * Returns the parent process id for a currently running process.
839     * @param pid the process id
840     * @return the parent process id of the process, or -1 if the process is not running.
841     * @hide
842     */
843    public static final int getParentPid(int pid) {
844        String[] procStatusLabels = { "PPid:" };
845        long[] procStatusValues = new long[1];
846        procStatusValues[0] = -1;
847        Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
848        return (int) procStatusValues[0];
849    }
850
851    /**
852     * Returns the thread group leader id for a currently running thread.
853     * @param tid the thread id
854     * @return the thread group leader id of the thread, or -1 if the thread is not running.
855     *         This is same as what getpid(2) would return if called by tid.
856     * @hide
857     */
858    public static final int getThreadGroupLeader(int tid) {
859        String[] procStatusLabels = { "Tgid:" };
860        long[] procStatusValues = new long[1];
861        procStatusValues[0] = -1;
862        Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
863        return (int) procStatusValues[0];
864    }
865
866    /**
867     * Set the priority of a thread, based on Linux priorities.
868     *
869     * @param tid The identifier of the thread/process to change.
870     * @param priority A Linux priority level, from -20 for highest scheduling
871     * priority to 19 for lowest scheduling priority.
872     *
873     * @throws IllegalArgumentException Throws IllegalArgumentException if
874     * <var>tid</var> does not exist.
875     * @throws SecurityException Throws SecurityException if your process does
876     * not have permission to modify the given thread, or to use the given
877     * priority.
878     */
879    public static final native void setThreadPriority(int tid, int priority)
880            throws IllegalArgumentException, SecurityException;
881
882    /**
883     * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
884     * throw an exception if passed a background-level thread priority.  This is only
885     * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
886     *
887     * @hide
888     */
889    public static final native void setCanSelfBackground(boolean backgroundOk);
890
891    /**
892     * Sets the scheduling group for a thread.
893     * @hide
894     * @param tid The identifier of the thread to change.
895     * @param group The target group for this thread from THREAD_GROUP_*.
896     *
897     * @throws IllegalArgumentException Throws IllegalArgumentException if
898     * <var>tid</var> does not exist.
899     * @throws SecurityException Throws SecurityException if your process does
900     * not have permission to modify the given thread, or to use the given
901     * priority.
902     * If the thread is a thread group leader, that is it's gettid() == getpid(),
903     * then the other threads in the same thread group are _not_ affected.
904     */
905    public static final native void setThreadGroup(int tid, int group)
906            throws IllegalArgumentException, SecurityException;
907
908    /**
909     * Sets the scheduling group for a process and all child threads
910     * @hide
911     * @param pid The identifier of the process to change.
912     * @param group The target group for this process from THREAD_GROUP_*.
913     *
914     * @throws IllegalArgumentException Throws IllegalArgumentException if
915     * <var>tid</var> does not exist.
916     * @throws SecurityException Throws SecurityException if your process does
917     * not have permission to modify the given thread, or to use the given
918     * priority.
919     *
920     * group == THREAD_GROUP_DEFAULT means to move all non-background priority
921     * threads to the foreground scheduling group, but to leave background
922     * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
923     * threads, regardless of priority, to the background scheduling group.
924     * group == THREAD_GROUP_FOREGROUND is not allowed.
925     */
926    public static final native void setProcessGroup(int pid, int group)
927            throws IllegalArgumentException, SecurityException;
928
929    /**
930     * Return the scheduling group of requested process.
931     *
932     * @hide
933     */
934    public static final native int getProcessGroup(int pid)
935            throws IllegalArgumentException, SecurityException;
936
937    /**
938     * Set the priority of the calling thread, based on Linux priorities.  See
939     * {@link #setThreadPriority(int, int)} for more information.
940     *
941     * @param priority A Linux priority level, from -20 for highest scheduling
942     * priority to 19 for lowest scheduling priority.
943     *
944     * @throws IllegalArgumentException Throws IllegalArgumentException if
945     * <var>tid</var> does not exist.
946     * @throws SecurityException Throws SecurityException if your process does
947     * not have permission to modify the given thread, or to use the given
948     * priority.
949     *
950     * @see #setThreadPriority(int, int)
951     */
952    public static final native void setThreadPriority(int priority)
953            throws IllegalArgumentException, SecurityException;
954
955    /**
956     * Return the current priority of a thread, based on Linux priorities.
957     *
958     * @param tid The identifier of the thread/process to change.
959     *
960     * @return Returns the current priority, as a Linux priority level,
961     * from -20 for highest scheduling priority to 19 for lowest scheduling
962     * priority.
963     *
964     * @throws IllegalArgumentException Throws IllegalArgumentException if
965     * <var>tid</var> does not exist.
966     */
967    public static final native int getThreadPriority(int tid)
968            throws IllegalArgumentException;
969
970    /**
971     * Set the scheduling policy and priority of a thread, based on Linux.
972     *
973     * @param tid The identifier of the thread/process to change.
974     * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
975     * @param priority A Linux priority level in a range appropriate for the given policy.
976     *
977     * @throws IllegalArgumentException Throws IllegalArgumentException if
978     * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
979     * @throws SecurityException Throws SecurityException if your process does
980     * not have permission to modify the given thread, or to use the given
981     * scheduling policy or priority.
982     *
983     * {@hide}
984     */
985    public static final native void setThreadScheduler(int tid, int policy, int priority)
986            throws IllegalArgumentException;
987
988    /**
989     * Determine whether the current environment supports multiple processes.
990     *
991     * @return Returns true if the system can run in multiple processes, else
992     * false if everything is running in a single process.
993     *
994     * @deprecated This method always returns true.  Do not use.
995     */
996    @Deprecated
997    public static final boolean supportsProcesses() {
998        return true;
999    }
1000
1001    /**
1002     * Adjust the swappiness level for a process.
1003     *
1004     * @param pid The process identifier to set.
1005     * @param is_increased Whether swappiness should be increased or default.
1006     *
1007     * @return Returns true if the underlying system supports this
1008     *         feature, else false.
1009     *
1010     * {@hide}
1011     */
1012    public static final native boolean setSwappiness(int pid, boolean is_increased);
1013
1014    /**
1015     * Change this process's argv[0] parameter.  This can be useful to show
1016     * more descriptive information in things like the 'ps' command.
1017     *
1018     * @param text The new name of this process.
1019     *
1020     * {@hide}
1021     */
1022    public static final native void setArgV0(String text);
1023
1024    /**
1025     * Kill the process with the given PID.
1026     * Note that, though this API allows us to request to
1027     * kill any process based on its PID, the kernel will
1028     * still impose standard restrictions on which PIDs you
1029     * are actually able to kill.  Typically this means only
1030     * the process running the caller's packages/application
1031     * and any additional processes created by that app; packages
1032     * sharing a common UID will also be able to kill each
1033     * other's processes.
1034     */
1035    public static final void killProcess(int pid) {
1036        sendSignal(pid, SIGNAL_KILL);
1037    }
1038
1039    /** @hide */
1040    public static final native int setUid(int uid);
1041
1042    /** @hide */
1043    public static final native int setGid(int uid);
1044
1045    /**
1046     * Send a signal to the given process.
1047     *
1048     * @param pid The pid of the target process.
1049     * @param signal The signal to send.
1050     */
1051    public static final native void sendSignal(int pid, int signal);
1052
1053    /**
1054     * @hide
1055     * Private impl for avoiding a log message...  DO NOT USE without doing
1056     * your own log, or the Android Illuminati will find you some night and
1057     * beat you up.
1058     */
1059    public static final void killProcessQuiet(int pid) {
1060        sendSignalQuiet(pid, SIGNAL_KILL);
1061    }
1062
1063    /**
1064     * @hide
1065     * Private impl for avoiding a log message...  DO NOT USE without doing
1066     * your own log, or the Android Illuminati will find you some night and
1067     * beat you up.
1068     */
1069    public static final native void sendSignalQuiet(int pid, int signal);
1070
1071    /** @hide */
1072    public static final native long getFreeMemory();
1073
1074    /** @hide */
1075    public static final native long getTotalMemory();
1076
1077    /** @hide */
1078    public static final native void readProcLines(String path,
1079            String[] reqFields, long[] outSizes);
1080
1081    /** @hide */
1082    public static final native int[] getPids(String path, int[] lastArray);
1083
1084    /** @hide */
1085    public static final int PROC_TERM_MASK = 0xff;
1086    /** @hide */
1087    public static final int PROC_ZERO_TERM = 0;
1088    /** @hide */
1089    public static final int PROC_SPACE_TERM = (int)' ';
1090    /** @hide */
1091    public static final int PROC_TAB_TERM = (int)'\t';
1092    /** @hide */
1093    public static final int PROC_COMBINE = 0x100;
1094    /** @hide */
1095    public static final int PROC_PARENS = 0x200;
1096    /** @hide */
1097    public static final int PROC_QUOTES = 0x400;
1098    /** @hide */
1099    public static final int PROC_OUT_STRING = 0x1000;
1100    /** @hide */
1101    public static final int PROC_OUT_LONG = 0x2000;
1102    /** @hide */
1103    public static final int PROC_OUT_FLOAT = 0x4000;
1104
1105    /** @hide */
1106    public static final native boolean readProcFile(String file, int[] format,
1107            String[] outStrings, long[] outLongs, float[] outFloats);
1108
1109    /** @hide */
1110    public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1111            int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1112
1113    /** @hide */
1114    public static final native int[] getPidsForCommands(String[] cmds);
1115
1116    /**
1117     * Gets the total Pss value for a given process, in bytes.
1118     *
1119     * @param pid the process to the Pss for
1120     * @return the total Pss value for the given process in bytes,
1121     *  or -1 if the value cannot be determined
1122     * @hide
1123     */
1124    public static final native long getPss(int pid);
1125
1126    /**
1127     * Specifies the outcome of having started a process.
1128     * @hide
1129     */
1130    public static final class ProcessStartResult {
1131        /**
1132         * The PID of the newly started process.
1133         * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
1134         */
1135        public int pid;
1136
1137        /**
1138         * True if the process was started with a wrapper attached.
1139         */
1140        public boolean usingWrapper;
1141    }
1142
1143    /**
1144     * Kill all processes in a process group started for the given
1145     * pid.
1146     * @hide
1147     */
1148    public static final native int killProcessGroup(int uid, int pid);
1149
1150    /**
1151     * Remove all process groups.  Expected to be called when ActivityManager
1152     * is restarted.
1153     * @hide
1154     */
1155    public static final native void removeAllProcessGroups();
1156}
1157