Home | History | Annotate | Download | only in os
      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 
     17 package android.os;
     18 
     19 import android.net.LocalSocketAddress;
     20 import android.net.LocalSocket;
     21 import android.util.Log;
     22 import dalvik.system.Zygote;
     23 
     24 import java.io.BufferedWriter;
     25 import java.io.DataInputStream;
     26 import java.io.IOException;
     27 import java.io.OutputStreamWriter;
     28 import 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  */
     43 public 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 UID/GID for the user shell.
     72      * @hide
     73      */
     74     public static final int SHELL_UID = 2000;
     75 
     76     /**
     77      * Defines the UID/GID for the log group.
     78      * @hide
     79      */
     80     public static final int LOG_UID = 1007;
     81 
     82     /**
     83      * Defines the UID/GID for the WIFI supplicant process.
     84      * @hide
     85      */
     86     public static final int WIFI_UID = 1010;
     87 
     88     /**
     89      * Defines the UID/GID for the mediaserver process.
     90      * @hide
     91      */
     92     public static final int MEDIA_UID = 1013;
     93 
     94     /**
     95      * Defines the UID/GID for the DRM process.
     96      * @hide
     97      */
     98     public static final int DRM_UID = 1019;
     99 
    100     /**
    101      * Defines the GID for the group that allows write access to the SD card.
    102      * @hide
    103      */
    104     public static final int SDCARD_RW_GID = 1015;
    105 
    106     /**
    107      * Defines the UID/GID for the group that controls VPN services.
    108      * @hide
    109      */
    110     public static final int VPN_UID = 1016;
    111 
    112     /**
    113      * Defines the UID/GID for the NFC service process.
    114      * @hide
    115      */
    116     public static final int NFC_UID = 1027;
    117 
    118     /**
    119      * Defines the GID for the group that allows write access to the internal media storage.
    120      * @hide
    121      */
    122     public static final int MEDIA_RW_GID = 1023;
    123 
    124     /**
    125      * Defines the start of a range of UIDs (and GIDs), going from this
    126      * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
    127      * to applications.
    128      */
    129     public static final int FIRST_APPLICATION_UID = 10000;
    130     /**
    131      * Last of application-specific UIDs starting at
    132      * {@link #FIRST_APPLICATION_UID}.
    133      */
    134     public static final int LAST_APPLICATION_UID = 19999;
    135 
    136     /**
    137      * First uid used for fully isolated sandboxed processes (with no permissions of their own)
    138      * @hide
    139      */
    140     public static final int FIRST_ISOLATED_UID = 99000;
    141 
    142     /**
    143      * Last uid used for fully isolated sandboxed processes (with no permissions of their own)
    144      * @hide
    145      */
    146     public static final int LAST_ISOLATED_UID = 99999;
    147 
    148     /**
    149      * Defines a secondary group id for access to the bluetooth hardware.
    150      */
    151     public static final int BLUETOOTH_GID = 2000;
    152 
    153     /**
    154      * Standard priority of application threads.
    155      * Use with {@link #setThreadPriority(int)} and
    156      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
    157      * {@link java.lang.Thread} class.
    158      */
    159     public static final int THREAD_PRIORITY_DEFAULT = 0;
    160 
    161     /*
    162      * ***************************************
    163      * ** Keep in sync with utils/threads.h **
    164      * ***************************************
    165      */
    166 
    167     /**
    168      * Lowest available thread priority.  Only for those who really, really
    169      * don't want to run if anything else is happening.
    170      * Use with {@link #setThreadPriority(int)} and
    171      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
    172      * {@link java.lang.Thread} class.
    173      */
    174     public static final int THREAD_PRIORITY_LOWEST = 19;
    175 
    176     /**
    177      * Standard priority background threads.  This gives your thread a slightly
    178      * lower than normal priority, so that it will have less chance of impacting
    179      * the responsiveness of the user interface.
    180      * Use with {@link #setThreadPriority(int)} and
    181      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
    182      * {@link java.lang.Thread} class.
    183      */
    184     public static final int THREAD_PRIORITY_BACKGROUND = 10;
    185 
    186     /**
    187      * Standard priority of threads that are currently running a user interface
    188      * that the user is interacting with.  Applications can not normally
    189      * change to this priority; the system will automatically adjust your
    190      * application threads as the user moves through the UI.
    191      * Use with {@link #setThreadPriority(int)} and
    192      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
    193      * {@link java.lang.Thread} class.
    194      */
    195     public static final int THREAD_PRIORITY_FOREGROUND = -2;
    196 
    197     /**
    198      * Standard priority of system display threads, involved in updating
    199      * the user interface.  Applications can not
    200      * normally change to this priority.
    201      * Use with {@link #setThreadPriority(int)} and
    202      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
    203      * {@link java.lang.Thread} class.
    204      */
    205     public static final int THREAD_PRIORITY_DISPLAY = -4;
    206 
    207     /**
    208      * Standard priority of the most important display threads, for compositing
    209      * the screen and retrieving input events.  Applications can not normally
    210      * change to this priority.
    211      * Use with {@link #setThreadPriority(int)} and
    212      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
    213      * {@link java.lang.Thread} class.
    214      */
    215     public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
    216 
    217     /**
    218      * Standard priority of audio threads.  Applications can not normally
    219      * change to this priority.
    220      * Use with {@link #setThreadPriority(int)} and
    221      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
    222      * {@link java.lang.Thread} class.
    223      */
    224     public static final int THREAD_PRIORITY_AUDIO = -16;
    225 
    226     /**
    227      * Standard priority of the most important audio threads.
    228      * Applications can not normally change to this priority.
    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_URGENT_AUDIO = -19;
    234 
    235     /**
    236      * Minimum increment to make a priority more favorable.
    237      */
    238     public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
    239 
    240     /**
    241      * Minimum increment to make a priority less favorable.
    242      */
    243     public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
    244 
    245     /**
    246      * Default scheduling policy
    247      * @hide
    248      */
    249     public static final int SCHED_OTHER = 0;
    250 
    251     /**
    252      * First-In First-Out scheduling policy
    253      * @hide
    254      */
    255     public static final int SCHED_FIFO = 1;
    256 
    257     /**
    258      * Round-Robin scheduling policy
    259      * @hide
    260      */
    261     public static final int SCHED_RR = 2;
    262 
    263     /**
    264      * Batch scheduling policy
    265      * @hide
    266      */
    267     public static final int SCHED_BATCH = 3;
    268 
    269     /**
    270      * Idle scheduling policy
    271      * @hide
    272      */
    273     public static final int SCHED_IDLE = 5;
    274 
    275     // Keep in sync with SP_* constants of enum type SchedPolicy
    276     // declared in system/core/include/cutils/sched_policy.h,
    277     // except THREAD_GROUP_DEFAULT does not correspond to any SP_* value.
    278 
    279     /**
    280      * Default thread group -
    281      * has meaning with setProcessGroup() only, cannot be used with setThreadGroup().
    282      * When used with setProcessGroup(), the group of each thread in the process
    283      * is conditionally changed based on that thread's current priority, as follows:
    284      * threads with priority numerically less than THREAD_PRIORITY_BACKGROUND
    285      * are moved to foreground thread group.  All other threads are left unchanged.
    286      * @hide
    287      */
    288     public static final int THREAD_GROUP_DEFAULT = -1;
    289 
    290     /**
    291      * Background thread group - All threads in
    292      * this group are scheduled with a reduced share of the CPU.
    293      * Value is same as constant SP_BACKGROUND of enum SchedPolicy.
    294      * FIXME rename to THREAD_GROUP_BACKGROUND.
    295      * @hide
    296      */
    297     public static final int THREAD_GROUP_BG_NONINTERACTIVE = 0;
    298 
    299     /**
    300      * Foreground thread group - All threads in
    301      * this group are scheduled with a normal share of the CPU.
    302      * Value is same as constant SP_FOREGROUND of enum SchedPolicy.
    303      * Not used at this level.
    304      * @hide
    305      **/
    306     private static final int THREAD_GROUP_FOREGROUND = 1;
    307 
    308     /**
    309      * System thread group.
    310      * @hide
    311      **/
    312     public static final int THREAD_GROUP_SYSTEM = 2;
    313 
    314     /**
    315      * Application audio thread group.
    316      * @hide
    317      **/
    318     public static final int THREAD_GROUP_AUDIO_APP = 3;
    319 
    320     /**
    321      * System audio thread group.
    322      * @hide
    323      **/
    324     public static final int THREAD_GROUP_AUDIO_SYS = 4;
    325 
    326     public static final int SIGNAL_QUIT = 3;
    327     public static final int SIGNAL_KILL = 9;
    328     public static final int SIGNAL_USR1 = 10;
    329 
    330     // State for communicating with zygote process
    331 
    332     static LocalSocket sZygoteSocket;
    333     static DataInputStream sZygoteInputStream;
    334     static BufferedWriter sZygoteWriter;
    335 
    336     /** true if previous zygote open failed */
    337     static boolean sPreviousZygoteOpenFailed;
    338 
    339     /**
    340      * Start a new process.
    341      *
    342      * <p>If processes are enabled, a new process is created and the
    343      * static main() function of a <var>processClass</var> is executed there.
    344      * The process will continue running after this function returns.
    345      *
    346      * <p>If processes are not enabled, a new thread in the caller's
    347      * process is created and main() of <var>processClass</var> called there.
    348      *
    349      * <p>The niceName parameter, if not an empty string, is a custom name to
    350      * give to the process instead of using processClass.  This allows you to
    351      * make easily identifyable processes even if you are using the same base
    352      * <var>processClass</var> to start them.
    353      *
    354      * @param processClass The class to use as the process's main entry
    355      *                     point.
    356      * @param niceName A more readable name to use for the process.
    357      * @param uid The user-id under which the process will run.
    358      * @param gid The group-id under which the process will run.
    359      * @param gids Additional group-ids associated with the process.
    360      * @param debugFlags Additional flags.
    361      * @param targetSdkVersion The target SDK version for the app.
    362      * @param zygoteArgs Additional arguments to supply to the zygote process.
    363      *
    364      * @return An object that describes the result of the attempt to start the process.
    365      * @throws RuntimeException on fatal start failure
    366      *
    367      * {@hide}
    368      */
    369     public static final ProcessStartResult start(final String processClass,
    370                                   final String niceName,
    371                                   int uid, int gid, int[] gids,
    372                                   int debugFlags, int targetSdkVersion,
    373                                   String[] zygoteArgs) {
    374         try {
    375             return startViaZygote(processClass, niceName, uid, gid, gids,
    376                     debugFlags, targetSdkVersion, zygoteArgs);
    377         } catch (ZygoteStartFailedEx ex) {
    378             Log.e(LOG_TAG,
    379                     "Starting VM process through Zygote failed");
    380             throw new RuntimeException(
    381                     "Starting VM process through Zygote failed", ex);
    382         }
    383     }
    384 
    385     /** retry interval for opening a zygote socket */
    386     static final int ZYGOTE_RETRY_MILLIS = 500;
    387 
    388     /**
    389      * Tries to open socket to Zygote process if not already open. If
    390      * already open, does nothing.  May block and retry.
    391      */
    392     private static void openZygoteSocketIfNeeded()
    393             throws ZygoteStartFailedEx {
    394 
    395         int retryCount;
    396 
    397         if (sPreviousZygoteOpenFailed) {
    398             /*
    399              * If we've failed before, expect that we'll fail again and
    400              * don't pause for retries.
    401              */
    402             retryCount = 0;
    403         } else {
    404             retryCount = 10;
    405         }
    406 
    407         /*
    408          * See bug #811181: Sometimes runtime can make it up before zygote.
    409          * Really, we'd like to do something better to avoid this condition,
    410          * but for now just wait a bit...
    411          */
    412         for (int retry = 0
    413                 ; (sZygoteSocket == null) && (retry < (retryCount + 1))
    414                 ; retry++ ) {
    415 
    416             if (retry > 0) {
    417                 try {
    418                     Log.i("Zygote", "Zygote not up yet, sleeping...");
    419                     Thread.sleep(ZYGOTE_RETRY_MILLIS);
    420                 } catch (InterruptedException ex) {
    421                     // should never happen
    422                 }
    423             }
    424 
    425             try {
    426                 sZygoteSocket = new LocalSocket();
    427 
    428                 sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET,
    429                         LocalSocketAddress.Namespace.RESERVED));
    430 
    431                 sZygoteInputStream
    432                         = new DataInputStream(sZygoteSocket.getInputStream());
    433 
    434                 sZygoteWriter =
    435                     new BufferedWriter(
    436                             new OutputStreamWriter(
    437                                     sZygoteSocket.getOutputStream()),
    438                             256);
    439 
    440                 Log.i("Zygote", "Process: zygote socket opened");
    441 
    442                 sPreviousZygoteOpenFailed = false;
    443                 break;
    444             } catch (IOException ex) {
    445                 if (sZygoteSocket != null) {
    446                     try {
    447                         sZygoteSocket.close();
    448                     } catch (IOException ex2) {
    449                         Log.e(LOG_TAG,"I/O exception on close after exception",
    450                                 ex2);
    451                     }
    452                 }
    453 
    454                 sZygoteSocket = null;
    455             }
    456         }
    457 
    458         if (sZygoteSocket == null) {
    459             sPreviousZygoteOpenFailed = true;
    460             throw new ZygoteStartFailedEx("connect failed");
    461         }
    462     }
    463 
    464     /**
    465      * Sends an argument list to the zygote process, which starts a new child
    466      * and returns the child's pid. Please note: the present implementation
    467      * replaces newlines in the argument list with spaces.
    468      * @param args argument list
    469      * @return An object that describes the result of the attempt to start the process.
    470      * @throws ZygoteStartFailedEx if process start failed for any reason
    471      */
    472     private static ProcessStartResult zygoteSendArgsAndGetResult(ArrayList<String> args)
    473             throws ZygoteStartFailedEx {
    474         openZygoteSocketIfNeeded();
    475 
    476         try {
    477             /**
    478              * See com.android.internal.os.ZygoteInit.readArgumentList()
    479              * Presently the wire format to the zygote process is:
    480              * a) a count of arguments (argc, in essence)
    481              * b) a number of newline-separated argument strings equal to count
    482              *
    483              * After the zygote process reads these it will write the pid of
    484              * the child or -1 on failure, followed by boolean to
    485              * indicate whether a wrapper process was used.
    486              */
    487 
    488             sZygoteWriter.write(Integer.toString(args.size()));
    489             sZygoteWriter.newLine();
    490 
    491             int sz = args.size();
    492             for (int i = 0; i < sz; i++) {
    493                 String arg = args.get(i);
    494                 if (arg.indexOf('\n') >= 0) {
    495                     throw new ZygoteStartFailedEx(
    496                             "embedded newlines not allowed");
    497                 }
    498                 sZygoteWriter.write(arg);
    499                 sZygoteWriter.newLine();
    500             }
    501 
    502             sZygoteWriter.flush();
    503 
    504             // Should there be a timeout on this?
    505             ProcessStartResult result = new ProcessStartResult();
    506             result.pid = sZygoteInputStream.readInt();
    507             if (result.pid < 0) {
    508                 throw new ZygoteStartFailedEx("fork() failed");
    509             }
    510             result.usingWrapper = sZygoteInputStream.readBoolean();
    511             return result;
    512         } catch (IOException ex) {
    513             try {
    514                 if (sZygoteSocket != null) {
    515                     sZygoteSocket.close();
    516                 }
    517             } catch (IOException ex2) {
    518                 // we're going to fail anyway
    519                 Log.e(LOG_TAG,"I/O exception on routine close", ex2);
    520             }
    521 
    522             sZygoteSocket = null;
    523 
    524             throw new ZygoteStartFailedEx(ex);
    525         }
    526     }
    527 
    528     /**
    529      * Starts a new process via the zygote mechanism.
    530      *
    531      * @param processClass Class name whose static main() to run
    532      * @param niceName 'nice' process name to appear in ps
    533      * @param uid a POSIX uid that the new process should setuid() to
    534      * @param gid a POSIX gid that the new process shuold setgid() to
    535      * @param gids null-ok; a list of supplementary group IDs that the
    536      * new process should setgroup() to.
    537      * @param debugFlags Additional flags.
    538      * @param targetSdkVersion The target SDK version for the app.
    539      * @param extraArgs Additional arguments to supply to the zygote process.
    540      * @return An object that describes the result of the attempt to start the process.
    541      * @throws ZygoteStartFailedEx if process start failed for any reason
    542      */
    543     private static ProcessStartResult startViaZygote(final String processClass,
    544                                   final String niceName,
    545                                   final int uid, final int gid,
    546                                   final int[] gids,
    547                                   int debugFlags, int targetSdkVersion,
    548                                   String[] extraArgs)
    549                                   throws ZygoteStartFailedEx {
    550         synchronized(Process.class) {
    551             ArrayList<String> argsForZygote = new ArrayList<String>();
    552 
    553             // --runtime-init, --setuid=, --setgid=,
    554             // and --setgroups= must go first
    555             argsForZygote.add("--runtime-init");
    556             argsForZygote.add("--setuid=" + uid);
    557             argsForZygote.add("--setgid=" + gid);
    558             if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
    559                 argsForZygote.add("--enable-jni-logging");
    560             }
    561             if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
    562                 argsForZygote.add("--enable-safemode");
    563             }
    564             if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
    565                 argsForZygote.add("--enable-debugger");
    566             }
    567             if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
    568                 argsForZygote.add("--enable-checkjni");
    569             }
    570             if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
    571                 argsForZygote.add("--enable-assert");
    572             }
    573             argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
    574 
    575             //TODO optionally enable debuger
    576             //argsForZygote.add("--enable-debugger");
    577 
    578             // --setgroups is a comma-separated list
    579             if (gids != null && gids.length > 0) {
    580                 StringBuilder sb = new StringBuilder();
    581                 sb.append("--setgroups=");
    582 
    583                 int sz = gids.length;
    584                 for (int i = 0; i < sz; i++) {
    585                     if (i != 0) {
    586                         sb.append(',');
    587                     }
    588                     sb.append(gids[i]);
    589                 }
    590 
    591                 argsForZygote.add(sb.toString());
    592             }
    593 
    594             if (niceName != null) {
    595                 argsForZygote.add("--nice-name=" + niceName);
    596             }
    597 
    598             argsForZygote.add(processClass);
    599 
    600             if (extraArgs != null) {
    601                 for (String arg : extraArgs) {
    602                     argsForZygote.add(arg);
    603                 }
    604             }
    605 
    606             return zygoteSendArgsAndGetResult(argsForZygote);
    607         }
    608     }
    609 
    610     /**
    611      * Returns elapsed milliseconds of the time this process has run.
    612      * @return  Returns the number of milliseconds this process has return.
    613      */
    614     public static final native long getElapsedCpuTime();
    615 
    616     /**
    617      * Returns the identifier of this process, which can be used with
    618      * {@link #killProcess} and {@link #sendSignal}.
    619      */
    620     public static final native int myPid();
    621 
    622     /**
    623      * Returns the identifier of the calling thread, which be used with
    624      * {@link #setThreadPriority(int, int)}.
    625      */
    626     public static final native int myTid();
    627 
    628     /**
    629      * Returns the identifier of this process's user.
    630      */
    631     public static final native int myUid();
    632 
    633     /**
    634      * Returns whether the current process is in an isolated sandbox.
    635      * @hide
    636      */
    637     public static final boolean isIsolated() {
    638         int uid = UserId.getAppId(myUid());
    639         return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
    640     }
    641 
    642     /**
    643      * Returns the UID assigned to a particular user name, or -1 if there is
    644      * none.  If the given string consists of only numbers, it is converted
    645      * directly to a uid.
    646      */
    647     public static final native int getUidForName(String name);
    648 
    649     /**
    650      * Returns the GID assigned to a particular user name, or -1 if there is
    651      * none.  If the given string consists of only numbers, it is converted
    652      * directly to a gid.
    653      */
    654     public static final native int getGidForName(String name);
    655 
    656     /**
    657      * Returns a uid for a currently running process.
    658      * @param pid the process id
    659      * @return the uid of the process, or -1 if the process is not running.
    660      * @hide pending API council review
    661      */
    662     public static final int getUidForPid(int pid) {
    663         String[] procStatusLabels = { "Uid:" };
    664         long[] procStatusValues = new long[1];
    665         procStatusValues[0] = -1;
    666         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
    667         return (int) procStatusValues[0];
    668     }
    669 
    670     /**
    671      * Returns the parent process id for a currently running process.
    672      * @param pid the process id
    673      * @return the parent process id of the process, or -1 if the process is not running.
    674      * @hide
    675      */
    676     public static final int getParentPid(int pid) {
    677         String[] procStatusLabels = { "PPid:" };
    678         long[] procStatusValues = new long[1];
    679         procStatusValues[0] = -1;
    680         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
    681         return (int) procStatusValues[0];
    682     }
    683 
    684     /**
    685      * Returns the thread group leader id for a currently running thread.
    686      * @param tid the thread id
    687      * @return the thread group leader id of the thread, or -1 if the thread is not running.
    688      *         This is same as what getpid(2) would return if called by tid.
    689      * @hide
    690      */
    691     public static final int getThreadGroupLeader(int tid) {
    692         String[] procStatusLabels = { "Tgid:" };
    693         long[] procStatusValues = new long[1];
    694         procStatusValues[0] = -1;
    695         Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
    696         return (int) procStatusValues[0];
    697     }
    698 
    699     /**
    700      * Set the priority of a thread, based on Linux priorities.
    701      *
    702      * @param tid The identifier of the thread/process to change.
    703      * @param priority A Linux priority level, from -20 for highest scheduling
    704      * priority to 19 for lowest scheduling priority.
    705      *
    706      * @throws IllegalArgumentException Throws IllegalArgumentException if
    707      * <var>tid</var> does not exist.
    708      * @throws SecurityException Throws SecurityException if your process does
    709      * not have permission to modify the given thread, or to use the given
    710      * priority.
    711      */
    712     public static final native void setThreadPriority(int tid, int priority)
    713             throws IllegalArgumentException, SecurityException;
    714 
    715     /**
    716      * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
    717      * throw an exception if passed a background-level thread priority.  This is only
    718      * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
    719      *
    720      * @hide
    721      */
    722     public static final native void setCanSelfBackground(boolean backgroundOk);
    723 
    724     /**
    725      * Sets the scheduling group for a thread.
    726      * @hide
    727      * @param tid The identifier of the thread to change.
    728      * @param group The target group for this thread from THREAD_GROUP_*.
    729      *
    730      * @throws IllegalArgumentException Throws IllegalArgumentException if
    731      * <var>tid</var> does not exist.
    732      * @throws SecurityException Throws SecurityException if your process does
    733      * not have permission to modify the given thread, or to use the given
    734      * priority.
    735      * If the thread is a thread group leader, that is it's gettid() == getpid(),
    736      * then the other threads in the same thread group are _not_ affected.
    737      */
    738     public static final native void setThreadGroup(int tid, int group)
    739             throws IllegalArgumentException, SecurityException;
    740 
    741     /**
    742      * Sets the scheduling group for a process and all child threads
    743      * @hide
    744      * @param pid The identifier of the process to change.
    745      * @param group The target group for this process from THREAD_GROUP_*.
    746      *
    747      * @throws IllegalArgumentException Throws IllegalArgumentException if
    748      * <var>tid</var> does not exist.
    749      * @throws SecurityException Throws SecurityException if your process does
    750      * not have permission to modify the given thread, or to use the given
    751      * priority.
    752      *
    753      * group == THREAD_GROUP_DEFAULT means to move all non-background priority
    754      * threads to the foreground scheduling group, but to leave background
    755      * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
    756      * threads, regardless of priority, to the background scheduling group.
    757      * group == THREAD_GROUP_FOREGROUND is not allowed.
    758      */
    759     public static final native void setProcessGroup(int pid, int group)
    760             throws IllegalArgumentException, SecurityException;
    761 
    762     /**
    763      * Set the priority of the calling thread, based on Linux priorities.  See
    764      * {@link #setThreadPriority(int, int)} for more information.
    765      *
    766      * @param priority A Linux priority level, from -20 for highest scheduling
    767      * priority to 19 for lowest scheduling priority.
    768      *
    769      * @throws IllegalArgumentException Throws IllegalArgumentException if
    770      * <var>tid</var> does not exist.
    771      * @throws SecurityException Throws SecurityException if your process does
    772      * not have permission to modify the given thread, or to use the given
    773      * priority.
    774      *
    775      * @see #setThreadPriority(int, int)
    776      */
    777     public static final native void setThreadPriority(int priority)
    778             throws IllegalArgumentException, SecurityException;
    779 
    780     /**
    781      * Return the current priority of a thread, based on Linux priorities.
    782      *
    783      * @param tid The identifier of the thread/process to change.
    784      *
    785      * @return Returns the current priority, as a Linux priority level,
    786      * from -20 for highest scheduling priority to 19 for lowest scheduling
    787      * priority.
    788      *
    789      * @throws IllegalArgumentException Throws IllegalArgumentException if
    790      * <var>tid</var> does not exist.
    791      */
    792     public static final native int getThreadPriority(int tid)
    793             throws IllegalArgumentException;
    794 
    795     /**
    796      * Set the scheduling policy and priority of a thread, based on Linux.
    797      *
    798      * @param tid The identifier of the thread/process to change.
    799      * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
    800      * @param priority A Linux priority level in a range appropriate for the given policy.
    801      *
    802      * @throws IllegalArgumentException Throws IllegalArgumentException if
    803      * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
    804      * @throws SecurityException Throws SecurityException if your process does
    805      * not have permission to modify the given thread, or to use the given
    806      * scheduling policy or priority.
    807      *
    808      * {@hide}
    809      */
    810     public static final native void setThreadScheduler(int tid, int policy, int priority)
    811             throws IllegalArgumentException;
    812 
    813     /**
    814      * Determine whether the current environment supports multiple processes.
    815      *
    816      * @return Returns true if the system can run in multiple processes, else
    817      * false if everything is running in a single process.
    818      *
    819      * @deprecated This method always returns true.  Do not use.
    820      */
    821     @Deprecated
    822     public static final boolean supportsProcesses() {
    823         return true;
    824     }
    825 
    826     /**
    827      * Set the out-of-memory badness adjustment for a process.
    828      *
    829      * @param pid The process identifier to set.
    830      * @param amt Adjustment value -- linux allows -16 to +15.
    831      *
    832      * @return Returns true if the underlying system supports this
    833      *         feature, else false.
    834      *
    835      * {@hide}
    836      */
    837     public static final native boolean setOomAdj(int pid, int amt);
    838 
    839     /**
    840      * Change this process's argv[0] parameter.  This can be useful to show
    841      * more descriptive information in things like the 'ps' command.
    842      *
    843      * @param text The new name of this process.
    844      *
    845      * {@hide}
    846      */
    847     public static final native void setArgV0(String text);
    848 
    849     /**
    850      * Kill the process with the given PID.
    851      * Note that, though this API allows us to request to
    852      * kill any process based on its PID, the kernel will
    853      * still impose standard restrictions on which PIDs you
    854      * are actually able to kill.  Typically this means only
    855      * the process running the caller's packages/application
    856      * and any additional processes created by that app; packages
    857      * sharing a common UID will also be able to kill each
    858      * other's processes.
    859      */
    860     public static final void killProcess(int pid) {
    861         sendSignal(pid, SIGNAL_KILL);
    862     }
    863 
    864     /** @hide */
    865     public static final native int setUid(int uid);
    866 
    867     /** @hide */
    868     public static final native int setGid(int uid);
    869 
    870     /**
    871      * Send a signal to the given process.
    872      *
    873      * @param pid The pid of the target process.
    874      * @param signal The signal to send.
    875      */
    876     public static final native void sendSignal(int pid, int signal);
    877 
    878     /**
    879      * @hide
    880      * Private impl for avoiding a log message...  DO NOT USE without doing
    881      * your own log, or the Android Illuminati will find you some night and
    882      * beat you up.
    883      */
    884     public static final void killProcessQuiet(int pid) {
    885         sendSignalQuiet(pid, SIGNAL_KILL);
    886     }
    887 
    888     /**
    889      * @hide
    890      * Private impl for avoiding a log message...  DO NOT USE without doing
    891      * your own log, or the Android Illuminati will find you some night and
    892      * beat you up.
    893      */
    894     public static final native void sendSignalQuiet(int pid, int signal);
    895 
    896     /** @hide */
    897     public static final native long getFreeMemory();
    898 
    899     /** @hide */
    900     public static final native long getTotalMemory();
    901 
    902     /** @hide */
    903     public static final native void readProcLines(String path,
    904             String[] reqFields, long[] outSizes);
    905 
    906     /** @hide */
    907     public static final native int[] getPids(String path, int[] lastArray);
    908 
    909     /** @hide */
    910     public static final int PROC_TERM_MASK = 0xff;
    911     /** @hide */
    912     public static final int PROC_ZERO_TERM = 0;
    913     /** @hide */
    914     public static final int PROC_SPACE_TERM = (int)' ';
    915     /** @hide */
    916     public static final int PROC_TAB_TERM = (int)'\t';
    917     /** @hide */
    918     public static final int PROC_COMBINE = 0x100;
    919     /** @hide */
    920     public static final int PROC_PARENS = 0x200;
    921     /** @hide */
    922     public static final int PROC_OUT_STRING = 0x1000;
    923     /** @hide */
    924     public static final int PROC_OUT_LONG = 0x2000;
    925     /** @hide */
    926     public static final int PROC_OUT_FLOAT = 0x4000;
    927 
    928     /** @hide */
    929     public static final native boolean readProcFile(String file, int[] format,
    930             String[] outStrings, long[] outLongs, float[] outFloats);
    931 
    932     /** @hide */
    933     public static final native boolean parseProcLine(byte[] buffer, int startIndex,
    934             int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
    935 
    936     /** @hide */
    937     public static final native int[] getPidsForCommands(String[] cmds);
    938 
    939     /**
    940      * Gets the total Pss value for a given process, in bytes.
    941      *
    942      * @param pid the process to the Pss for
    943      * @return the total Pss value for the given process in bytes,
    944      *  or -1 if the value cannot be determined
    945      * @hide
    946      */
    947     public static final native long getPss(int pid);
    948 
    949     /**
    950      * Specifies the outcome of having started a process.
    951      * @hide
    952      */
    953     public static final class ProcessStartResult {
    954         /**
    955          * The PID of the newly started process.
    956          * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
    957          */
    958         public int pid;
    959 
    960         /**
    961          * True if the process was started with a wrapper attached.
    962          */
    963         public boolean usingWrapper;
    964     }
    965 }
    966