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