Process.java revision e9d376b801b7890b1ef5006ed55de4208e64bb63
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.LocalSocketAddress;
20import android.net.LocalSocket;
21import android.util.Log;
22import dalvik.system.Zygote;
23
24import java.io.BufferedWriter;
25import java.io.DataInputStream;
26import java.io.IOException;
27import java.io.OutputStreamWriter;
28import java.util.ArrayList;
29
30/*package*/ class ZygoteStartFailedEx extends Exception {
31    /**
32     * Something prevented the zygote process startup from happening normally
33     */
34
35    ZygoteStartFailedEx() {};
36    ZygoteStartFailedEx(String s) {super(s);}
37    ZygoteStartFailedEx(Throwable cause) {super(cause);}
38}
39
40/**
41 * Tools for managing OS processes.
42 */
43public class Process {
44    private static final String LOG_TAG = "Process";
45
46    private static final String ZYGOTE_SOCKET = "zygote";
47
48    /**
49     * Name of a process for running the platform's media services.
50     * {@hide}
51     */
52    public static final String ANDROID_SHARED_MEDIA = "com.android.process.media";
53
54    /**
55     * Name of the process that Google content providers can share.
56     * {@hide}
57     */
58    public static final String GOOGLE_SHARED_APP_CONTENT = "com.google.process.content";
59
60    /**
61     * Defines the UID/GID under which system code runs.
62     */
63    public static final int SYSTEM_UID = 1000;
64
65    /**
66     * Defines the UID/GID under which the telephony code runs.
67     */
68    public static final int PHONE_UID = 1001;
69
70    /**
71     * Defines the start of a range of UIDs (and GIDs), going from this
72     * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
73     * to applications.
74     */
75    public static final int FIRST_APPLICATION_UID = 10000;
76    /**
77     * Last of application-specific UIDs starting at
78     * {@link #FIRST_APPLICATION_UID}.
79     */
80    public static final int LAST_APPLICATION_UID = 99999;
81
82    /**
83     * Defines a secondary group id for access to the bluetooth hardware.
84     */
85    public static final int BLUETOOTH_GID = 2000;
86
87    /**
88     * Standard priority of application threads.
89     * Use with {@link #setThreadPriority(int)} and
90     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
91     * {@link java.lang.Thread} class.
92     */
93    public static final int THREAD_PRIORITY_DEFAULT = 0;
94
95    /*
96     * ***************************************
97     * ** Keep in sync with utils/threads.h **
98     * ***************************************
99     */
100
101    /**
102     * Lowest available thread priority.  Only for those who really, really
103     * don't want to run if anything else is happening.
104     * Use with {@link #setThreadPriority(int)} and
105     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
106     * {@link java.lang.Thread} class.
107     */
108    public static final int THREAD_PRIORITY_LOWEST = 19;
109
110    /**
111     * Standard priority background threads.  This gives your thread a slightly
112     * lower than normal priority, so that it will have less chance of impacting
113     * the responsiveness of the user interface.
114     * Use with {@link #setThreadPriority(int)} and
115     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
116     * {@link java.lang.Thread} class.
117     */
118    public static final int THREAD_PRIORITY_BACKGROUND = 10;
119
120    /**
121     * Standard priority of threads that are currently running a user interface
122     * that the user is interacting with.  Applications can not normally
123     * change to this priority; the system will automatically adjust your
124     * application threads as the user moves through the UI.
125     * Use with {@link #setThreadPriority(int)} and
126     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
127     * {@link java.lang.Thread} class.
128     */
129    public static final int THREAD_PRIORITY_FOREGROUND = -2;
130
131    /**
132     * Standard priority of system display threads, involved in updating
133     * the user interface.  Applications can not
134     * normally change to this priority.
135     * Use with {@link #setThreadPriority(int)} and
136     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
137     * {@link java.lang.Thread} class.
138     */
139    public static final int THREAD_PRIORITY_DISPLAY = -4;
140
141    /**
142     * Standard priority of the most important display threads, for compositing
143     * the screen and retrieving input events.  Applications can not normally
144     * change to this priority.
145     * Use with {@link #setThreadPriority(int)} and
146     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
147     * {@link java.lang.Thread} class.
148     */
149    public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
150
151    /**
152     * Standard priority of audio threads.  Applications can not normally
153     * change to this priority.
154     * Use with {@link #setThreadPriority(int)} and
155     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
156     * {@link java.lang.Thread} class.
157     */
158    public static final int THREAD_PRIORITY_AUDIO = -16;
159
160    /**
161     * Standard priority of the most important audio threads.
162     * Applications can not normally change to this priority.
163     * Use with {@link #setThreadPriority(int)} and
164     * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
165     * {@link java.lang.Thread} class.
166     */
167    public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
168
169    /**
170     * Minimum increment to make a priority more favorable.
171     */
172    public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
173
174    /**
175     * Minimum increment to make a priority less favorable.
176     */
177    public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
178
179    /**
180     * Default thread group - gets a 'normal' share of the CPU
181     * @hide
182     */
183    public static final int THREAD_GROUP_DEFAULT = 0;
184
185    /**
186     * Background non-interactive thread group - All threads in
187     * this group are scheduled with a reduced share of the CPU.
188     * @hide
189     */
190    public static final int THREAD_GROUP_BG_NONINTERACTIVE = 1;
191
192    /**
193     * Foreground 'boost' thread group - All threads in
194     * this group are scheduled with an increased share of the CPU
195     * @hide
196     **/
197    public static final int THREAD_GROUP_FG_BOOST = 2;
198
199    public static final int SIGNAL_QUIT = 3;
200    public static final int SIGNAL_KILL = 9;
201    public static final int SIGNAL_USR1 = 10;
202
203    // State for communicating with zygote process
204
205    static LocalSocket sZygoteSocket;
206    static DataInputStream sZygoteInputStream;
207    static BufferedWriter sZygoteWriter;
208
209    /** true if previous zygote open failed */
210    static boolean sPreviousZygoteOpenFailed;
211
212    /**
213     * Start a new process.
214     *
215     * <p>If processes are enabled, a new process is created and the
216     * static main() function of a <var>processClass</var> is executed there.
217     * The process will continue running after this function returns.
218     *
219     * <p>If processes are not enabled, a new thread in the caller's
220     * process is created and main() of <var>processClass</var> called there.
221     *
222     * <p>The niceName parameter, if not an empty string, is a custom name to
223     * give to the process instead of using processClass.  This allows you to
224     * make easily identifyable processes even if you are using the same base
225     * <var>processClass</var> to start them.
226     *
227     * @param processClass The class to use as the process's main entry
228     *                     point.
229     * @param niceName A more readable name to use for the process.
230     * @param uid The user-id under which the process will run.
231     * @param gid The group-id under which the process will run.
232     * @param gids Additional group-ids associated with the process.
233     * @param enableDebugger True if debugging should be enabled for this process.
234     * @param zygoteArgs Additional arguments to supply to the zygote process.
235     *
236     * @return int If > 0 the pid of the new process; if 0 the process is
237     *         being emulated by a thread
238     * @throws RuntimeException on fatal start failure
239     *
240     * {@hide}
241     */
242    public static final int start(final String processClass,
243                                  final String niceName,
244                                  int uid, int gid, int[] gids,
245                                  int debugFlags,
246                                  String[] zygoteArgs)
247    {
248        if (supportsProcesses()) {
249            try {
250                return startViaZygote(processClass, niceName, uid, gid, gids,
251                        debugFlags, zygoteArgs);
252            } catch (ZygoteStartFailedEx ex) {
253                Log.e(LOG_TAG,
254                        "Starting VM process through Zygote failed");
255                throw new RuntimeException(
256                        "Starting VM process through Zygote failed", ex);
257            }
258        } else {
259            // Running in single-process mode
260
261            Runnable runnable = new Runnable() {
262                        public void run() {
263                            Process.invokeStaticMain(processClass);
264                        }
265            };
266
267            // Thread constructors must not be called with null names (see spec).
268            if (niceName != null) {
269                new Thread(runnable, niceName).start();
270            } else {
271                new Thread(runnable).start();
272            }
273
274            return 0;
275        }
276    }
277
278    /**
279     * Start a new process.  Don't supply a custom nice name.
280     * {@hide}
281     */
282    public static final int start(String processClass, int uid, int gid,
283            int[] gids, int debugFlags, String[] zygoteArgs) {
284        return start(processClass, "", uid, gid, gids,
285                debugFlags, zygoteArgs);
286    }
287
288    private static void invokeStaticMain(String className) {
289        Class cl;
290        Object args[] = new Object[1];
291
292        args[0] = new String[0];     //this is argv
293
294        try {
295            cl = Class.forName(className);
296            cl.getMethod("main", new Class[] { String[].class })
297                    .invoke(null, args);
298        } catch (Exception ex) {
299            // can be: ClassNotFoundException,
300            // NoSuchMethodException, SecurityException,
301            // IllegalAccessException, IllegalArgumentException
302            // InvocationTargetException
303            // or uncaught exception from main()
304
305            Log.e(LOG_TAG, "Exception invoking static main on "
306                    + className, ex);
307
308            throw new RuntimeException(ex);
309        }
310
311    }
312
313    /** retry interval for opening a zygote socket */
314    static final int ZYGOTE_RETRY_MILLIS = 500;
315
316    /**
317     * Tries to open socket to Zygote process if not already open. If
318     * already open, does nothing.  May block and retry.
319     */
320    private static void openZygoteSocketIfNeeded()
321            throws ZygoteStartFailedEx {
322
323        int retryCount;
324
325        if (sPreviousZygoteOpenFailed) {
326            /*
327             * If we've failed before, expect that we'll fail again and
328             * don't pause for retries.
329             */
330            retryCount = 0;
331        } else {
332            retryCount = 10;
333        }
334
335        /*
336         * See bug #811181: Sometimes runtime can make it up before zygote.
337         * Really, we'd like to do something better to avoid this condition,
338         * but for now just wait a bit...
339         */
340        for (int retry = 0
341                ; (sZygoteSocket == null) && (retry < (retryCount + 1))
342                ; retry++ ) {
343
344            if (retry > 0) {
345                try {
346                    Log.i("Zygote", "Zygote not up yet, sleeping...");
347                    Thread.sleep(ZYGOTE_RETRY_MILLIS);
348                } catch (InterruptedException ex) {
349                    // should never happen
350                }
351            }
352
353            try {
354                sZygoteSocket = new LocalSocket();
355
356                sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET,
357                        LocalSocketAddress.Namespace.RESERVED));
358
359                sZygoteInputStream
360                        = new DataInputStream(sZygoteSocket.getInputStream());
361
362                sZygoteWriter =
363                    new BufferedWriter(
364                            new OutputStreamWriter(
365                                    sZygoteSocket.getOutputStream()),
366                            256);
367
368                Log.i("Zygote", "Process: zygote socket opened");
369
370                sPreviousZygoteOpenFailed = false;
371                break;
372            } catch (IOException ex) {
373                if (sZygoteSocket != null) {
374                    try {
375                        sZygoteSocket.close();
376                    } catch (IOException ex2) {
377                        Log.e(LOG_TAG,"I/O exception on close after exception",
378                                ex2);
379                    }
380                }
381
382                sZygoteSocket = null;
383            }
384        }
385
386        if (sZygoteSocket == null) {
387            sPreviousZygoteOpenFailed = true;
388            throw new ZygoteStartFailedEx("connect failed");
389        }
390    }
391
392    /**
393     * Sends an argument list to the zygote process, which starts a new child
394     * and returns the child's pid. Please note: the present implementation
395     * replaces newlines in the argument list with spaces.
396     * @param args argument list
397     * @return PID of new child process
398     * @throws ZygoteStartFailedEx if process start failed for any reason
399     */
400    private static int zygoteSendArgsAndGetPid(ArrayList<String> args)
401            throws ZygoteStartFailedEx {
402
403        int pid;
404
405        openZygoteSocketIfNeeded();
406
407        try {
408            /**
409             * See com.android.internal.os.ZygoteInit.readArgumentList()
410             * Presently the wire format to the zygote process is:
411             * a) a count of arguments (argc, in essence)
412             * b) a number of newline-separated argument strings equal to count
413             *
414             * After the zygote process reads these it will write the pid of
415             * the child or -1 on failure.
416             */
417
418            sZygoteWriter.write(Integer.toString(args.size()));
419            sZygoteWriter.newLine();
420
421            int sz = args.size();
422            for (int i = 0; i < sz; i++) {
423                String arg = args.get(i);
424                if (arg.indexOf('\n') >= 0) {
425                    throw new ZygoteStartFailedEx(
426                            "embedded newlines not allowed");
427                }
428                sZygoteWriter.write(arg);
429                sZygoteWriter.newLine();
430            }
431
432            sZygoteWriter.flush();
433
434            // Should there be a timeout on this?
435            pid = sZygoteInputStream.readInt();
436
437            if (pid < 0) {
438                throw new ZygoteStartFailedEx("fork() failed");
439            }
440        } catch (IOException ex) {
441            try {
442                if (sZygoteSocket != null) {
443                    sZygoteSocket.close();
444                }
445            } catch (IOException ex2) {
446                // we're going to fail anyway
447                Log.e(LOG_TAG,"I/O exception on routine close", ex2);
448            }
449
450            sZygoteSocket = null;
451
452            throw new ZygoteStartFailedEx(ex);
453        }
454
455        return pid;
456    }
457
458    /**
459     * Starts a new process via the zygote mechanism.
460     *
461     * @param processClass Class name whose static main() to run
462     * @param niceName 'nice' process name to appear in ps
463     * @param uid a POSIX uid that the new process should setuid() to
464     * @param gid a POSIX gid that the new process shuold setgid() to
465     * @param gids null-ok; a list of supplementary group IDs that the
466     * new process should setgroup() to.
467     * @param enableDebugger True if debugging should be enabled for this process.
468     * @param extraArgs Additional arguments to supply to the zygote process.
469     * @return PID
470     * @throws ZygoteStartFailedEx if process start failed for any reason
471     */
472    private static int startViaZygote(final String processClass,
473                                  final String niceName,
474                                  final int uid, final int gid,
475                                  final int[] gids,
476                                  int debugFlags,
477                                  String[] extraArgs)
478                                  throws ZygoteStartFailedEx {
479        int pid;
480
481        synchronized(Process.class) {
482            ArrayList<String> argsForZygote = new ArrayList<String>();
483
484            // --runtime-init, --setuid=, --setgid=,
485            // and --setgroups= must go first
486            argsForZygote.add("--runtime-init");
487            argsForZygote.add("--setuid=" + uid);
488            argsForZygote.add("--setgid=" + gid);
489            if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
490                argsForZygote.add("--enable-debugger");
491            }
492            if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
493                argsForZygote.add("--enable-checkjni");
494            }
495            if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
496                argsForZygote.add("--enable-assert");
497            }
498
499            //TODO optionally enable debuger
500            //argsForZygote.add("--enable-debugger");
501
502            // --setgroups is a comma-separated list
503            if (gids != null && gids.length > 0) {
504                StringBuilder sb = new StringBuilder();
505                sb.append("--setgroups=");
506
507                int sz = gids.length;
508                for (int i = 0; i < sz; i++) {
509                    if (i != 0) {
510                        sb.append(',');
511                    }
512                    sb.append(gids[i]);
513                }
514
515                argsForZygote.add(sb.toString());
516            }
517
518            if (niceName != null) {
519                argsForZygote.add("--nice-name=" + niceName);
520            }
521
522            argsForZygote.add(processClass);
523
524            if (extraArgs != null) {
525                for (String arg : extraArgs) {
526                    argsForZygote.add(arg);
527                }
528            }
529
530            pid = zygoteSendArgsAndGetPid(argsForZygote);
531        }
532
533        if (pid <= 0) {
534            throw new ZygoteStartFailedEx("zygote start failed:" + pid);
535        }
536
537        return pid;
538    }
539
540    /**
541     * Returns elapsed milliseconds of the time this process has run.
542     * @return  Returns the number of milliseconds this process has return.
543     */
544    public static final native long getElapsedCpuTime();
545
546    /**
547     * Returns the identifier of this process, which can be used with
548     * {@link #killProcess} and {@link #sendSignal}.
549     */
550    public static final native int myPid();
551
552    /**
553     * Returns the identifier of the calling thread, which be used with
554     * {@link #setThreadPriority(int, int)}.
555     */
556    public static final native int myTid();
557
558    /**
559     * Returns the identifier of this process's user.
560     */
561    public static final native int myUid();
562
563    /**
564     * Returns the UID assigned to a particular user name, or -1 if there is
565     * none.  If the given string consists of only numbers, it is converted
566     * directly to a uid.
567     */
568    public static final native int getUidForName(String name);
569
570    /**
571     * Returns the GID assigned to a particular user name, or -1 if there is
572     * none.  If the given string consists of only numbers, it is converted
573     * directly to a gid.
574     */
575    public static final native int getGidForName(String name);
576
577    /**
578     * Set the priority of a thread, based on Linux priorities.
579     *
580     * @param tid The identifier of the thread/process to change.
581     * @param priority A Linux priority level, from -20 for highest scheduling
582     * priority to 19 for lowest scheduling priority.
583     *
584     * @throws IllegalArgumentException Throws IllegalArgumentException if
585     * <var>tid</var> does not exist.
586     * @throws SecurityException Throws SecurityException if your process does
587     * not have permission to modify the given thread, or to use the given
588     * priority.
589     */
590    public static final native void setThreadPriority(int tid, int priority)
591            throws IllegalArgumentException, SecurityException;
592
593    /**
594     * Sets the scheduling group for a thread.
595     * @hide
596     * @param tid The indentifier of the thread/process to change.
597     * @param group The target group for this thread/process.
598     *
599     * @throws IllegalArgumentException Throws IllegalArgumentException if
600     * <var>tid</var> does not exist.
601     * @throws SecurityException Throws SecurityException if your process does
602     * not have permission to modify the given thread, or to use the given
603     * priority.
604     */
605    public static final native void setThreadGroup(int tid, int group)
606            throws IllegalArgumentException, SecurityException;
607
608    /**
609     * Set the priority of the calling thread, based on Linux priorities.  See
610     * {@link #setThreadPriority(int, int)} for more information.
611     *
612     * @param priority A Linux priority level, from -20 for highest scheduling
613     * priority to 19 for lowest scheduling priority.
614     *
615     * @throws IllegalArgumentException Throws IllegalArgumentException if
616     * <var>tid</var> does not exist.
617     * @throws SecurityException Throws SecurityException if your process does
618     * not have permission to modify the given thread, or to use the given
619     * priority.
620     *
621     * @see #setThreadPriority(int, int)
622     */
623    public static final native void setThreadPriority(int priority)
624            throws IllegalArgumentException, SecurityException;
625
626    /**
627     * Return the current priority of a thread, based on Linux priorities.
628     *
629     * @param tid The identifier of the thread/process to change.
630     *
631     * @return Returns the current priority, as a Linux priority level,
632     * from -20 for highest scheduling priority to 19 for lowest scheduling
633     * priority.
634     *
635     * @throws IllegalArgumentException Throws IllegalArgumentException if
636     * <var>tid</var> does not exist.
637     */
638    public static final native int getThreadPriority(int tid)
639            throws IllegalArgumentException;
640
641    /**
642     * Determine whether the current environment supports multiple processes.
643     *
644     * @return Returns true if the system can run in multiple processes, else
645     * false if everything is running in a single process.
646     */
647    public static final native boolean supportsProcesses();
648
649    /**
650     * Set the out-of-memory badness adjustment for a process.
651     *
652     * @param pid The process identifier to set.
653     * @param amt Adjustment value -- linux allows -16 to +15.
654     *
655     * @return Returns true if the underlying system supports this
656     *         feature, else false.
657     *
658     * {@hide}
659     */
660    public static final native boolean setOomAdj(int pid, int amt);
661
662    /**
663     * Change this process's argv[0] parameter.  This can be useful to show
664     * more descriptive information in things like the 'ps' command.
665     *
666     * @param text The new name of this process.
667     *
668     * {@hide}
669     */
670    public static final native void setArgV0(String text);
671
672    /**
673     * Kill the process with the given PID.
674     * Note that, though this API allows us to request to
675     * kill any process based on its PID, the kernel will
676     * still impose standard restrictions on which PIDs you
677     * are actually able to kill.  Typically this means only
678     * the process running the caller's packages/application
679     * and any additional processes created by that app; packages
680     * sharing a common UID will also be able to kill each
681     * other's processes.
682     */
683    public static final void killProcess(int pid) {
684        sendSignal(pid, SIGNAL_KILL);
685    }
686
687    /** @hide */
688    public static final native int setUid(int uid);
689
690    /** @hide */
691    public static final native int setGid(int uid);
692
693    /**
694     * Send a signal to the given process.
695     *
696     * @param pid The pid of the target process.
697     * @param signal The signal to send.
698     */
699    public static final native void sendSignal(int pid, int signal);
700
701    /** @hide */
702    public static final native int getFreeMemory();
703
704    /** @hide */
705    public static final native void readProcLines(String path,
706            String[] reqFields, long[] outSizes);
707
708    /** @hide */
709    public static final native int[] getPids(String path, int[] lastArray);
710
711    /** @hide */
712    public static final int PROC_TERM_MASK = 0xff;
713    /** @hide */
714    public static final int PROC_ZERO_TERM = 0;
715    /** @hide */
716    public static final int PROC_SPACE_TERM = (int)' ';
717    /** @hide */
718    public static final int PROC_TAB_TERM = (int)'\t';
719    /** @hide */
720    public static final int PROC_COMBINE = 0x100;
721    /** @hide */
722    public static final int PROC_PARENS = 0x200;
723    /** @hide */
724    public static final int PROC_OUT_STRING = 0x1000;
725    /** @hide */
726    public static final int PROC_OUT_LONG = 0x2000;
727    /** @hide */
728    public static final int PROC_OUT_FLOAT = 0x4000;
729
730    /** @hide */
731    public static final native boolean readProcFile(String file, int[] format,
732            String[] outStrings, long[] outLongs, float[] outFloats);
733
734    /** @hide */
735    public static final native boolean parseProcLine(byte[] buffer, int startIndex,
736            int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
737
738    /**
739     * Gets the total Pss value for a given process, in bytes.
740     *
741     * @param pid the process to the Pss for
742     * @return the total Pss value for the given process in bytes,
743     *  or -1 if the value cannot be determined
744     * @hide
745     */
746    public static final native long getPss(int pid);
747}
748