Process.java revision f013e1afd1e68af5e3b868c26a653bbfb39538f8
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    public static final int SIGNAL_QUIT = 3;
180    public static final int SIGNAL_KILL = 9;
181    public static final int SIGNAL_USR1 = 10;
182
183    // State for communicating with zygote process
184
185    static LocalSocket sZygoteSocket;
186    static DataInputStream sZygoteInputStream;
187    static BufferedWriter sZygoteWriter;
188
189    /** true if previous zygote open failed */
190    static boolean sPreviousZygoteOpenFailed;
191
192    /**
193     * Start a new process.
194     *
195     * <p>If processes are enabled, a new process is created and the
196     * static main() function of a <var>processClass</var> is executed there.
197     * The process will continue running after this function returns.
198     *
199     * <p>If processes are not enabled, a new thread in the caller's
200     * process is created and main() of <var>processClass</var> called there.
201     *
202     * <p>The niceName parameter, if not an empty string, is a custom name to
203     * give to the process instead of using processClass.  This allows you to
204     * make easily identifyable processes even if you are using the same base
205     * <var>processClass</var> to start them.
206     *
207     * @param processClass The class to use as the process's main entry
208     *                     point.
209     * @param niceName A more readable name to use for the process.
210     * @param uid The user-id under which the process will run.
211     * @param gid The group-id under which the process will run.
212     * @param gids Additional group-ids associated with the process.
213     * @param enableDebugger True if debugging should be enabled for this process.
214     * @param zygoteArgs Additional arguments to supply to the zygote process.
215     *
216     * @return int If > 0 the pid of the new process; if 0 the process is
217     *         being emulated by a thread
218     * @throws RuntimeException on fatal start failure
219     *
220     * {@hide}
221     */
222    public static final int start(final String processClass,
223                                  final String niceName,
224                                  int uid, int gid, int[] gids,
225                                  int debugFlags,
226                                  String[] zygoteArgs)
227    {
228        if (supportsProcesses()) {
229            try {
230                return startViaZygote(processClass, niceName, uid, gid, gids,
231                        debugFlags, zygoteArgs);
232            } catch (ZygoteStartFailedEx ex) {
233                Log.e(LOG_TAG,
234                        "Starting VM process through Zygote failed");
235                throw new RuntimeException(
236                        "Starting VM process through Zygote failed", ex);
237            }
238        } else {
239            // Running in single-process mode
240
241            Runnable runnable = new Runnable() {
242                        public void run() {
243                            Process.invokeStaticMain(processClass);
244                        }
245            };
246
247            // Thread constructors must not be called with null names (see spec).
248            if (niceName != null) {
249                new Thread(runnable, niceName).start();
250            } else {
251                new Thread(runnable).start();
252            }
253
254            return 0;
255        }
256    }
257
258    /**
259     * Start a new process.  Don't supply a custom nice name.
260     * {@hide}
261     */
262    public static final int start(String processClass, int uid, int gid,
263            int[] gids, int debugFlags, String[] zygoteArgs) {
264        return start(processClass, "", uid, gid, gids,
265                debugFlags, zygoteArgs);
266    }
267
268    private static void invokeStaticMain(String className) {
269        Class cl;
270        Object args[] = new Object[1];
271
272        args[0] = new String[0];     //this is argv
273
274        try {
275            cl = Class.forName(className);
276            cl.getMethod("main", new Class[] { String[].class })
277                    .invoke(null, args);
278        } catch (Exception ex) {
279            // can be: ClassNotFoundException,
280            // NoSuchMethodException, SecurityException,
281            // IllegalAccessException, IllegalArgumentException
282            // InvocationTargetException
283            // or uncaught exception from main()
284
285            Log.e(LOG_TAG, "Exception invoking static main on "
286                    + className, ex);
287
288            throw new RuntimeException(ex);
289        }
290
291    }
292
293    /** retry interval for opening a zygote socket */
294    static final int ZYGOTE_RETRY_MILLIS = 500;
295
296    /**
297     * Tries to open socket to Zygote process if not already open. If
298     * already open, does nothing.  May block and retry.
299     */
300    private static void openZygoteSocketIfNeeded()
301            throws ZygoteStartFailedEx {
302
303        int retryCount;
304
305        if (sPreviousZygoteOpenFailed) {
306            /*
307             * If we've failed before, expect that we'll fail again and
308             * don't pause for retries.
309             */
310            retryCount = 0;
311        } else {
312            retryCount = 10;
313        }
314
315        /*
316         * See bug #811181: Sometimes runtime can make it up before zygote.
317         * Really, we'd like to do something better to avoid this condition,
318         * but for now just wait a bit...
319         */
320        for (int retry = 0
321                ; (sZygoteSocket == null) && (retry < (retryCount + 1))
322                ; retry++ ) {
323
324            if (retry > 0) {
325                try {
326                    Log.i("Zygote", "Zygote not up yet, sleeping...");
327                    Thread.sleep(ZYGOTE_RETRY_MILLIS);
328                } catch (InterruptedException ex) {
329                    // should never happen
330                }
331            }
332
333            try {
334                sZygoteSocket = new LocalSocket();
335
336                sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET,
337                        LocalSocketAddress.Namespace.RESERVED));
338
339                sZygoteInputStream
340                        = new DataInputStream(sZygoteSocket.getInputStream());
341
342                sZygoteWriter =
343                    new BufferedWriter(
344                            new OutputStreamWriter(
345                                    sZygoteSocket.getOutputStream()),
346                            256);
347
348                Log.i("Zygote", "Process: zygote socket opened");
349
350                sPreviousZygoteOpenFailed = false;
351                break;
352            } catch (IOException ex) {
353                if (sZygoteSocket != null) {
354                    try {
355                        sZygoteSocket.close();
356                    } catch (IOException ex2) {
357                        Log.e(LOG_TAG,"I/O exception on close after exception",
358                                ex2);
359                    }
360                }
361
362                sZygoteSocket = null;
363            }
364        }
365
366        if (sZygoteSocket == null) {
367            sPreviousZygoteOpenFailed = true;
368            throw new ZygoteStartFailedEx("connect failed");
369        }
370    }
371
372    /**
373     * Sends an argument list to the zygote process, which starts a new child
374     * and returns the child's pid. Please note: the present implementation
375     * replaces newlines in the argument list with spaces.
376     * @param args argument list
377     * @return PID of new child process
378     * @throws ZygoteStartFailedEx if process start failed for any reason
379     */
380    private static int zygoteSendArgsAndGetPid(ArrayList<String> args)
381            throws ZygoteStartFailedEx {
382
383        int pid;
384
385        openZygoteSocketIfNeeded();
386
387        try {
388            /**
389             * See com.android.internal.os.ZygoteInit.readArgumentList()
390             * Presently the wire format to the zygote process is:
391             * a) a count of arguments (argc, in essence)
392             * b) a number of newline-separated argument strings equal to count
393             *
394             * After the zygote process reads these it will write the pid of
395             * the child or -1 on failure.
396             */
397
398            sZygoteWriter.write(Integer.toString(args.size()));
399            sZygoteWriter.newLine();
400
401            int sz = args.size();
402            for (int i = 0; i < sz; i++) {
403                String arg = args.get(i);
404                if (arg.indexOf('\n') >= 0) {
405                    throw new ZygoteStartFailedEx(
406                            "embedded newlines not allowed");
407                }
408                sZygoteWriter.write(arg);
409                sZygoteWriter.newLine();
410            }
411
412            sZygoteWriter.flush();
413
414            // Should there be a timeout on this?
415            pid = sZygoteInputStream.readInt();
416
417            if (pid < 0) {
418                throw new ZygoteStartFailedEx("fork() failed");
419            }
420        } catch (IOException ex) {
421            try {
422                if (sZygoteSocket != null) {
423                    sZygoteSocket.close();
424                }
425            } catch (IOException ex2) {
426                // we're going to fail anyway
427                Log.e(LOG_TAG,"I/O exception on routine close", ex2);
428            }
429
430            sZygoteSocket = null;
431
432            throw new ZygoteStartFailedEx(ex);
433        }
434
435        return pid;
436    }
437
438    /**
439     * Starts a new process via the zygote mechanism.
440     *
441     * @param processClass Class name whose static main() to run
442     * @param niceName 'nice' process name to appear in ps
443     * @param uid a POSIX uid that the new process should setuid() to
444     * @param gid a POSIX gid that the new process shuold setgid() to
445     * @param gids null-ok; a list of supplementary group IDs that the
446     * new process should setgroup() to.
447     * @param enableDebugger True if debugging should be enabled for this process.
448     * @param extraArgs Additional arguments to supply to the zygote process.
449     * @return PID
450     * @throws ZygoteStartFailedEx if process start failed for any reason
451     */
452    private static int startViaZygote(final String processClass,
453                                  final String niceName,
454                                  final int uid, final int gid,
455                                  final int[] gids,
456                                  int debugFlags,
457                                  String[] extraArgs)
458                                  throws ZygoteStartFailedEx {
459        int pid;
460
461        synchronized(Process.class) {
462            ArrayList<String> argsForZygote = new ArrayList<String>();
463
464            // --runtime-init, --setuid=, --setgid=,
465            // and --setgroups= must go first
466            argsForZygote.add("--runtime-init");
467            argsForZygote.add("--setuid=" + uid);
468            argsForZygote.add("--setgid=" + gid);
469            if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
470                argsForZygote.add("--enable-debugger");
471            }
472            if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
473                argsForZygote.add("--enable-checkjni");
474            }
475            if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
476                argsForZygote.add("--enable-assert");
477            }
478
479            //TODO optionally enable debuger
480            //argsForZygote.add("--enable-debugger");
481
482            // --setgroups is a comma-separated list
483            if (gids != null && gids.length > 0) {
484                StringBuilder sb = new StringBuilder();
485                sb.append("--setgroups=");
486
487                int sz = gids.length;
488                for (int i = 0; i < sz; i++) {
489                    if (i != 0) {
490                        sb.append(',');
491                    }
492                    sb.append(gids[i]);
493                }
494
495                argsForZygote.add(sb.toString());
496            }
497
498            if (niceName != null) {
499                argsForZygote.add("--nice-name=" + niceName);
500            }
501
502            argsForZygote.add(processClass);
503
504            if (extraArgs != null) {
505                for (String arg : extraArgs) {
506                    argsForZygote.add(arg);
507                }
508            }
509
510            pid = zygoteSendArgsAndGetPid(argsForZygote);
511        }
512
513        if (pid <= 0) {
514            throw new ZygoteStartFailedEx("zygote start failed:" + pid);
515        }
516
517        return pid;
518    }
519
520    /**
521     * Returns elapsed milliseconds of the time this process has run.
522     * @return  Returns the number of milliseconds this process has return.
523     */
524    public static final native long getElapsedCpuTime();
525
526    /**
527     * Returns the identifier of this process, which can be used with
528     * {@link #killProcess} and {@link #sendSignal}.
529     */
530    public static final native int myPid();
531
532    /**
533     * Returns the identifier of the calling thread, which be used with
534     * {@link #setThreadPriority(int, int)}.
535     */
536    public static final native int myTid();
537
538    /**
539     * Returns the identifier of this process's user.
540     */
541    public static final native int myUid();
542
543    /**
544     * Returns the UID assigned to a particular user name, or -1 if there is
545     * none.  If the given string consists of only numbers, it is converted
546     * directly to a uid.
547     */
548    public static final native int getUidForName(String name);
549
550    /**
551     * Returns the GID assigned to a particular user name, or -1 if there is
552     * none.  If the given string consists of only numbers, it is converted
553     * directly to a gid.
554     */
555    public static final native int getGidForName(String name);
556
557    /**
558     * Set the priority of a thread, based on Linux priorities.
559     *
560     * @param tid The identifier of the thread/process to change.
561     * @param priority A Linux priority level, from -20 for highest scheduling
562     * priority to 19 for lowest scheduling priority.
563     *
564     * @throws IllegalArgumentException Throws IllegalArgumentException if
565     * <var>tid</var> does not exist.
566     * @throws SecurityException Throws SecurityException if your process does
567     * not have permission to modify the given thread, or to use the given
568     * priority.
569     */
570    public static final native void setThreadPriority(int tid, int priority)
571            throws IllegalArgumentException, SecurityException;
572
573    /**
574     * Set the priority of the calling thread, based on Linux priorities.  See
575     * {@link #setThreadPriority(int, int)} for more information.
576     *
577     * @param priority A Linux priority level, from -20 for highest scheduling
578     * priority to 19 for lowest scheduling priority.
579     *
580     * @throws IllegalArgumentException Throws IllegalArgumentException if
581     * <var>tid</var> does not exist.
582     * @throws SecurityException Throws SecurityException if your process does
583     * not have permission to modify the given thread, or to use the given
584     * priority.
585     *
586     * @see #setThreadPriority(int, int)
587     */
588    public static final native void setThreadPriority(int priority)
589            throws IllegalArgumentException, SecurityException;
590
591    /**
592     * Return the current priority of a thread, based on Linux priorities.
593     *
594     * @param tid The identifier of the thread/process to change.
595     *
596     * @return Returns the current priority, as a Linux priority level,
597     * from -20 for highest scheduling priority to 19 for lowest scheduling
598     * priority.
599     *
600     * @throws IllegalArgumentException Throws IllegalArgumentException if
601     * <var>tid</var> does not exist.
602     */
603    public static final native int getThreadPriority(int tid)
604            throws IllegalArgumentException;
605
606    /**
607     * Determine whether the current environment supports multiple processes.
608     *
609     * @return Returns true if the system can run in multiple processes, else
610     * false if everything is running in a single process.
611     */
612    public static final native boolean supportsProcesses();
613
614    /**
615     * Set the out-of-memory badness adjustment for a process.
616     *
617     * @param pid The process identifier to set.
618     * @param amt Adjustment value -- linux allows -16 to +15.
619     *
620     * @return Returns true if the underlying system supports this
621     *         feature, else false.
622     *
623     * {@hide}
624     */
625    public static final native boolean setOomAdj(int pid, int amt);
626
627    /**
628     * Change this process's argv[0] parameter.  This can be useful to show
629     * more descriptive information in things like the 'ps' command.
630     *
631     * @param text The new name of this process.
632     *
633     * {@hide}
634     */
635    public static final native void setArgV0(String text);
636
637    /**
638     * Kill the process with the given PID.
639     * Note that, though this API allows us to request to
640     * kill any process based on its PID, the kernel will
641     * still impose standard restrictions on which PIDs you
642     * are actually able to kill.  Typically this means only
643     * the process running the caller's packages/application
644     * and any additional processes created by that app; packages
645     * sharing a common UID will also be able to kill each
646     * other's processes.
647     */
648    public static final void killProcess(int pid) {
649        sendSignal(pid, SIGNAL_KILL);
650    }
651
652    /** @hide */
653    public static final native int setUid(int uid);
654
655    /** @hide */
656    public static final native int setGid(int uid);
657
658    /**
659     * Send a signal to the given process.
660     *
661     * @param pid The pid of the target process.
662     * @param signal The signal to send.
663     */
664    public static final native void sendSignal(int pid, int signal);
665
666    /** @hide */
667    public static final native int getFreeMemory();
668
669    /** @hide */
670    public static final native void readProcLines(String path,
671            String[] reqFields, long[] outSizes);
672
673    /** @hide */
674    public static final native int[] getPids(String path, int[] lastArray);
675
676    /** @hide */
677    public static final int PROC_TERM_MASK = 0xff;
678    /** @hide */
679    public static final int PROC_ZERO_TERM = 0;
680    /** @hide */
681    public static final int PROC_SPACE_TERM = (int)' ';
682    /** @hide */
683    public static final int PROC_COMBINE = 0x100;
684    /** @hide */
685    public static final int PROC_PARENS = 0x200;
686    /** @hide */
687    public static final int PROC_OUT_STRING = 0x1000;
688    /** @hide */
689    public static final int PROC_OUT_LONG = 0x2000;
690    /** @hide */
691    public static final int PROC_OUT_FLOAT = 0x4000;
692
693    /** @hide */
694    public static final native boolean readProcFile(String file, int[] format,
695            String[] outStrings, long[] outLongs, float[] outFloats);
696
697    /**
698     * Gets the total Pss value for a given process, in bytes.
699     *
700     * @param pid the process to the Pss for
701     * @return the total Pss value for the given process in bytes,
702     *  or -1 if the value cannot be determined
703     * @hide
704     */
705    public static final native long getPss(int pid);
706}
707