Home | History | Annotate | Download | only in jni
      1 /* //device/libs/android_runtime/android_util_Process.cpp
      2 **
      3 ** Copyright 2006, The Android Open Source Project
      4 **
      5 ** Licensed under the Apache License, Version 2.0 (the "License");
      6 ** you may not use this file except in compliance with the License.
      7 ** You may obtain a copy of the License at
      8 **
      9 **     http://www.apache.org/licenses/LICENSE-2.0
     10 **
     11 ** Unless required by applicable law or agreed to in writing, software
     12 ** distributed under the License is distributed on an "AS IS" BASIS,
     13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14 ** See the License for the specific language governing permissions and
     15 ** limitations under the License.
     16 */
     17 
     18 #define LOG_TAG "Process"
     19 
     20 // To make sure cpu_set_t is included from sched.h
     21 #define _GNU_SOURCE 1
     22 #include <utils/Log.h>
     23 #include <binder/IPCThreadState.h>
     24 #include <binder/IServiceManager.h>
     25 #include <cutils/process_name.h>
     26 #include <cutils/sched_policy.h>
     27 #include <utils/String8.h>
     28 #include <utils/Vector.h>
     29 #include <processgroup/processgroup.h>
     30 
     31 #include "core_jni_helpers.h"
     32 
     33 #include "android_util_Binder.h"
     34 #include "JNIHelp.h"
     35 
     36 #include <dirent.h>
     37 #include <fcntl.h>
     38 #include <grp.h>
     39 #include <inttypes.h>
     40 #include <pwd.h>
     41 #include <signal.h>
     42 #include <sys/errno.h>
     43 #include <sys/resource.h>
     44 #include <sys/stat.h>
     45 #include <sys/types.h>
     46 #include <unistd.h>
     47 
     48 #define GUARD_THREAD_PRIORITY 0
     49 
     50 using namespace android;
     51 
     52 static const bool kDebugPolicy = false;
     53 static const bool kDebugProc = false;
     54 
     55 #if GUARD_THREAD_PRIORITY
     56 Mutex gKeyCreateMutex;
     57 static pthread_key_t gBgKey = -1;
     58 #endif
     59 
     60 // For both of these, err should be in the errno range (positive), not a status_t (negative)
     61 
     62 static void signalExceptionForPriorityError(JNIEnv* env, int err)
     63 {
     64     switch (err) {
     65         case EINVAL:
     66             jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
     67             break;
     68         case ESRCH:
     69             jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist");
     70             break;
     71         case EPERM:
     72             jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread");
     73             break;
     74         case EACCES:
     75             jniThrowException(env, "java/lang/SecurityException", "No permission to set to given priority");
     76             break;
     77         default:
     78             jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
     79             break;
     80     }
     81 }
     82 
     83 static void signalExceptionForGroupError(JNIEnv* env, int err)
     84 {
     85     switch (err) {
     86         case EINVAL:
     87             jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
     88             break;
     89         case ESRCH:
     90             jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist");
     91             break;
     92         case EPERM:
     93             jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread");
     94             break;
     95         case EACCES:
     96             jniThrowException(env, "java/lang/SecurityException", "No permission to set to given group");
     97             break;
     98         default:
     99             jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
    100             break;
    101     }
    102 }
    103 
    104 jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
    105 {
    106     if (name == NULL) {
    107         jniThrowNullPointerException(env, NULL);
    108         return -1;
    109     }
    110 
    111     const jchar* str16 = env->GetStringCritical(name, 0);
    112     String8 name8;
    113     if (str16) {
    114         name8 = String8(reinterpret_cast<const char16_t*>(str16),
    115                         env->GetStringLength(name));
    116         env->ReleaseStringCritical(name, str16);
    117     }
    118 
    119     const size_t N = name8.size();
    120     if (N > 0) {
    121         const char* str = name8.string();
    122         for (size_t i=0; i<N; i++) {
    123             if (str[i] < '0' || str[i] > '9') {
    124                 struct passwd* pwd = getpwnam(str);
    125                 if (pwd == NULL) {
    126                     return -1;
    127                 }
    128                 return pwd->pw_uid;
    129             }
    130         }
    131         return atoi(str);
    132     }
    133     return -1;
    134 }
    135 
    136 jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
    137 {
    138     if (name == NULL) {
    139         jniThrowNullPointerException(env, NULL);
    140         return -1;
    141     }
    142 
    143     const jchar* str16 = env->GetStringCritical(name, 0);
    144     String8 name8;
    145     if (str16) {
    146         name8 = String8(reinterpret_cast<const char16_t*>(str16),
    147                         env->GetStringLength(name));
    148         env->ReleaseStringCritical(name, str16);
    149     }
    150 
    151     const size_t N = name8.size();
    152     if (N > 0) {
    153         const char* str = name8.string();
    154         for (size_t i=0; i<N; i++) {
    155             if (str[i] < '0' || str[i] > '9') {
    156                 struct group* grp = getgrnam(str);
    157                 if (grp == NULL) {
    158                     return -1;
    159                 }
    160                 return grp->gr_gid;
    161             }
    162         }
    163         return atoi(str);
    164     }
    165     return -1;
    166 }
    167 
    168 void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int tid, jint grp)
    169 {
    170     ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
    171     SchedPolicy sp = (SchedPolicy) grp;
    172     int res = set_sched_policy(tid, sp);
    173     if (res != NO_ERROR) {
    174         signalExceptionForGroupError(env, -res);
    175     }
    176 }
    177 
    178 void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
    179 {
    180     ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp);
    181     DIR *d;
    182     char proc_path[255];
    183     struct dirent *de;
    184 
    185     if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
    186         signalExceptionForGroupError(env, EINVAL);
    187         return;
    188     }
    189 
    190     bool isDefault = false;
    191     if (grp < 0) {
    192         grp = SP_FOREGROUND;
    193         isDefault = true;
    194     }
    195     SchedPolicy sp = (SchedPolicy) grp;
    196 
    197     if (kDebugPolicy) {
    198         char cmdline[32];
    199         int fd;
    200 
    201         strcpy(cmdline, "unknown");
    202 
    203         sprintf(proc_path, "/proc/%d/cmdline", pid);
    204         fd = open(proc_path, O_RDONLY);
    205         if (fd >= 0) {
    206             int rc = read(fd, cmdline, sizeof(cmdline)-1);
    207             cmdline[rc] = 0;
    208             close(fd);
    209         }
    210 
    211         if (sp == SP_BACKGROUND) {
    212             ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
    213         } else {
    214             ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
    215         }
    216     }
    217 
    218     sprintf(proc_path, "/proc/%d/task", pid);
    219     if (!(d = opendir(proc_path))) {
    220         // If the process exited on us, don't generate an exception
    221         if (errno != ENOENT)
    222             signalExceptionForGroupError(env, errno);
    223         return;
    224     }
    225 
    226     while ((de = readdir(d))) {
    227         int t_pid;
    228         int t_pri;
    229 
    230         if (de->d_name[0] == '.')
    231             continue;
    232         t_pid = atoi(de->d_name);
    233 
    234         if (!t_pid) {
    235             ALOGE("Error getting pid for '%s'\n", de->d_name);
    236             continue;
    237         }
    238 
    239         t_pri = getpriority(PRIO_PROCESS, t_pid);
    240 
    241         if (t_pri <= ANDROID_PRIORITY_AUDIO) {
    242             int scheduler = sched_getscheduler(t_pid);
    243             if ((scheduler == SCHED_FIFO) || (scheduler == SCHED_RR)) {
    244                 // This task wants to stay in its current audio group so it can keep its budget
    245                 // don't update its cpuset or cgroup
    246                 continue;
    247             }
    248         }
    249 
    250         if (isDefault) {
    251             if (t_pri >= ANDROID_PRIORITY_BACKGROUND) {
    252                 // This task wants to stay at background
    253                 // update its cpuset so it doesn't only run on bg core(s)
    254 #ifdef ENABLE_CPUSETS
    255                 int err = set_cpuset_policy(t_pid, sp);
    256                 if (err != NO_ERROR) {
    257                     signalExceptionForGroupError(env, -err);
    258                     break;
    259                 }
    260 #endif
    261                 continue;
    262             }
    263         }
    264         int err;
    265 #ifdef ENABLE_CPUSETS
    266         // set both cpuset and cgroup for general threads
    267         err = set_cpuset_policy(t_pid, sp);
    268         if (err != NO_ERROR) {
    269             signalExceptionForGroupError(env, -err);
    270             break;
    271         }
    272 #endif
    273 
    274         err = set_sched_policy(t_pid, sp);
    275         if (err != NO_ERROR) {
    276             signalExceptionForGroupError(env, -err);
    277             break;
    278         }
    279 
    280     }
    281     closedir(d);
    282 }
    283 
    284 jint android_os_Process_getProcessGroup(JNIEnv* env, jobject clazz, jint pid)
    285 {
    286     SchedPolicy sp;
    287     if (get_sched_policy(pid, &sp) != 0) {
    288         signalExceptionForGroupError(env, errno);
    289     }
    290     return (int) sp;
    291 }
    292 
    293 #ifdef ENABLE_CPUSETS
    294 /** Sample CPUset list format:
    295  *  0-3,4,6-8
    296  */
    297 static void parse_cpuset_cpus(char *cpus, cpu_set_t *cpu_set) {
    298     unsigned int start, end, matched, i;
    299     char *cpu_range = strtok(cpus, ",");
    300     while (cpu_range != NULL) {
    301         start = end = 0;
    302         matched = sscanf(cpu_range, "%u-%u", &start, &end);
    303         cpu_range = strtok(NULL, ",");
    304         if (start >= CPU_SETSIZE) {
    305             ALOGE("parse_cpuset_cpus: ignoring CPU number larger than %d.", CPU_SETSIZE);
    306             continue;
    307         } else if (end >= CPU_SETSIZE) {
    308             ALOGE("parse_cpuset_cpus: ignoring CPU numbers larger than %d.", CPU_SETSIZE);
    309             end = CPU_SETSIZE - 1;
    310         }
    311         if (matched == 1) {
    312             CPU_SET(start, cpu_set);
    313         } else if (matched == 2) {
    314             for (i = start; i <= end; i++) {
    315                 CPU_SET(i, cpu_set);
    316             }
    317         } else {
    318             ALOGE("Failed to match cpus");
    319         }
    320     }
    321     return;
    322 }
    323 
    324 /**
    325  * Stores the CPUs assigned to the cpuset corresponding to the
    326  * SchedPolicy in the passed in cpu_set.
    327  */
    328 static void get_cpuset_cores_for_policy(SchedPolicy policy, cpu_set_t *cpu_set)
    329 {
    330     FILE *file;
    331     const char *filename;
    332 
    333     CPU_ZERO(cpu_set);
    334 
    335     switch (policy) {
    336         case SP_BACKGROUND:
    337             filename = "/dev/cpuset/background/cpus";
    338             break;
    339         case SP_FOREGROUND:
    340         case SP_AUDIO_APP:
    341         case SP_AUDIO_SYS:
    342             filename = "/dev/cpuset/foreground/cpus";
    343             break;
    344         case SP_TOP_APP:
    345             filename = "/dev/cpuset/top-app/cpus";
    346             break;
    347         default:
    348             filename = NULL;
    349     }
    350 
    351     if (!filename) return;
    352 
    353     file = fopen(filename, "re");
    354     if (file != NULL) {
    355         // Parse cpus string
    356         char *line = NULL;
    357         size_t len = 0;
    358         ssize_t num_read = getline(&line, &len, file);
    359         fclose (file);
    360         if (num_read > 0) {
    361             parse_cpuset_cpus(line, cpu_set);
    362         } else {
    363             ALOGE("Failed to read %s", filename);
    364         }
    365         free(line);
    366     }
    367     return;
    368 }
    369 #endif
    370 
    371 
    372 /**
    373  * Determine CPU cores exclusively assigned to the
    374  * cpuset corresponding to the SchedPolicy and store
    375  * them in the passed in cpu_set_t
    376  */
    377 void get_exclusive_cpuset_cores(SchedPolicy policy, cpu_set_t *cpu_set) {
    378 #ifdef ENABLE_CPUSETS
    379     int i;
    380     cpu_set_t tmp_set;
    381     get_cpuset_cores_for_policy(policy, cpu_set);
    382     for (i = 0; i < SP_CNT; i++) {
    383         if ((SchedPolicy) i == policy) continue;
    384         get_cpuset_cores_for_policy((SchedPolicy)i, &tmp_set);
    385         // First get cores exclusive to one set or the other
    386         CPU_XOR(&tmp_set, cpu_set, &tmp_set);
    387         // Then get the ones only in cpu_set
    388         CPU_AND(cpu_set, cpu_set, &tmp_set);
    389     }
    390 #else
    391     (void) policy;
    392     CPU_ZERO(cpu_set);
    393 #endif
    394     return;
    395 }
    396 
    397 jintArray android_os_Process_getExclusiveCores(JNIEnv* env, jobject clazz) {
    398     SchedPolicy sp;
    399     cpu_set_t cpu_set;
    400     jintArray cpus;
    401     int pid = getpid();
    402     if (get_sched_policy(pid, &sp) != 0) {
    403         signalExceptionForGroupError(env, errno);
    404         return NULL;
    405     }
    406     get_exclusive_cpuset_cores(sp, &cpu_set);
    407     int num_cpus = CPU_COUNT(&cpu_set);
    408     cpus = env->NewIntArray(num_cpus);
    409     if (cpus == NULL) {
    410         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
    411         return NULL;
    412     }
    413 
    414     jint* cpu_elements = env->GetIntArrayElements(cpus, 0);
    415     int count = 0;
    416     for (int i = 0; i < CPU_SETSIZE && count < num_cpus; i++) {
    417         if (CPU_ISSET(i, &cpu_set)) {
    418             cpu_elements[count++] = i;
    419         }
    420     }
    421 
    422     env->ReleaseIntArrayElements(cpus, cpu_elements, 0);
    423     return cpus;
    424 }
    425 
    426 static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
    427     // Establishes the calling thread as illegal to put into the background.
    428     // Typically used only for the system process's main looper.
    429 #if GUARD_THREAD_PRIORITY
    430     ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
    431     {
    432         Mutex::Autolock _l(gKeyCreateMutex);
    433         if (gBgKey == -1) {
    434             pthread_key_create(&gBgKey, NULL);
    435         }
    436     }
    437 
    438     // inverted:  not-okay, we set a sentinel value
    439     pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
    440 #endif
    441 }
    442 
    443 void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
    444                                               jint tid, jint policy, jint pri)
    445 {
    446 // linux has sched_setscheduler(), others don't.
    447 #if defined(__linux__)
    448     struct sched_param param;
    449     param.sched_priority = pri;
    450     int rc = sched_setscheduler(tid, policy, &param);
    451     if (rc) {
    452         signalExceptionForPriorityError(env, errno);
    453     }
    454 #else
    455     signalExceptionForPriorityError(env, ENOSYS);
    456 #endif
    457 }
    458 
    459 void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
    460                                               jint pid, jint pri)
    461 {
    462 #if GUARD_THREAD_PRIORITY
    463     // if we're putting the current thread into the background, check the TLS
    464     // to make sure this thread isn't guarded.  If it is, raise an exception.
    465     if (pri >= ANDROID_PRIORITY_BACKGROUND) {
    466         if (pid == gettid()) {
    467             void* bgOk = pthread_getspecific(gBgKey);
    468             if (bgOk == ((void*)0xbaad)) {
    469                 ALOGE("Thread marked fg-only put self in background!");
    470                 jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
    471                 return;
    472             }
    473         }
    474     }
    475 #endif
    476 
    477     int rc = androidSetThreadPriority(pid, pri);
    478     if (rc != 0) {
    479         if (rc == INVALID_OPERATION) {
    480             signalExceptionForPriorityError(env, errno);
    481         } else {
    482             signalExceptionForGroupError(env, errno);
    483         }
    484     }
    485 
    486     //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
    487     //     pid, pri, getpriority(PRIO_PROCESS, pid));
    488 }
    489 
    490 void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
    491                                                         jint pri)
    492 {
    493     android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
    494 }
    495 
    496 jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
    497                                               jint pid)
    498 {
    499     errno = 0;
    500     jint pri = getpriority(PRIO_PROCESS, pid);
    501     if (errno != 0) {
    502         signalExceptionForPriorityError(env, errno);
    503     }
    504     //ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
    505     return pri;
    506 }
    507 
    508 jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
    509                                           jint pid, jboolean is_increased)
    510 {
    511     char text[64];
    512 
    513     if (is_increased) {
    514         strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
    515     } else {
    516         strcpy(text, "/sys/fs/cgroup/memory/tasks");
    517     }
    518 
    519     struct stat st;
    520     if (stat(text, &st) || !S_ISREG(st.st_mode)) {
    521         return false;
    522     }
    523 
    524     int fd = open(text, O_WRONLY);
    525     if (fd >= 0) {
    526         sprintf(text, "%" PRId32, pid);
    527         write(fd, text, strlen(text));
    528         close(fd);
    529     }
    530 
    531     return true;
    532 }
    533 
    534 void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
    535 {
    536     if (name == NULL) {
    537         jniThrowNullPointerException(env, NULL);
    538         return;
    539     }
    540 
    541     const jchar* str = env->GetStringCritical(name, 0);
    542     String8 name8;
    543     if (str) {
    544         name8 = String8(reinterpret_cast<const char16_t*>(str),
    545                         env->GetStringLength(name));
    546         env->ReleaseStringCritical(name, str);
    547     }
    548 
    549     if (name8.size() > 0) {
    550         const char* procName = name8.string();
    551         set_process_name(procName);
    552         AndroidRuntime::getRuntime()->setArgv0(procName);
    553     }
    554 }
    555 
    556 jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
    557 {
    558     return setuid(uid) == 0 ? 0 : errno;
    559 }
    560 
    561 jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
    562 {
    563     return setgid(uid) == 0 ? 0 : errno;
    564 }
    565 
    566 static int pid_compare(const void* v1, const void* v2)
    567 {
    568     //ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
    569     return *((const jint*)v1) - *((const jint*)v2);
    570 }
    571 
    572 static jlong getFreeMemoryImpl(const char* const sums[], const size_t sumsLen[], size_t num)
    573 {
    574     int fd = open("/proc/meminfo", O_RDONLY);
    575 
    576     if (fd < 0) {
    577         ALOGW("Unable to open /proc/meminfo");
    578         return -1;
    579     }
    580 
    581     char buffer[256];
    582     const int len = read(fd, buffer, sizeof(buffer)-1);
    583     close(fd);
    584 
    585     if (len < 0) {
    586         ALOGW("Unable to read /proc/meminfo");
    587         return -1;
    588     }
    589     buffer[len] = 0;
    590 
    591     size_t numFound = 0;
    592     jlong mem = 0;
    593 
    594     char* p = buffer;
    595     while (*p && numFound < num) {
    596         int i = 0;
    597         while (sums[i]) {
    598             if (strncmp(p, sums[i], sumsLen[i]) == 0) {
    599                 p += sumsLen[i];
    600                 while (*p == ' ') p++;
    601                 char* num = p;
    602                 while (*p >= '0' && *p <= '9') p++;
    603                 if (*p != 0) {
    604                     *p = 0;
    605                     p++;
    606                     if (*p == 0) p--;
    607                 }
    608                 mem += atoll(num) * 1024;
    609                 numFound++;
    610                 break;
    611             }
    612             i++;
    613         }
    614         p++;
    615     }
    616 
    617     return numFound > 0 ? mem : -1;
    618 }
    619 
    620 static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
    621 {
    622     static const char* const sums[] = { "MemFree:", "Cached:", NULL };
    623     static const size_t sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 };
    624     return getFreeMemoryImpl(sums, sumsLen, 2);
    625 }
    626 
    627 static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
    628 {
    629     static const char* const sums[] = { "MemTotal:", NULL };
    630     static const size_t sumsLen[] = { strlen("MemTotal:"), 0 };
    631     return getFreeMemoryImpl(sums, sumsLen, 1);
    632 }
    633 
    634 void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
    635                                       jobjectArray reqFields, jlongArray outFields)
    636 {
    637     //ALOGI("getMemInfo: %p %p", reqFields, outFields);
    638 
    639     if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
    640         jniThrowNullPointerException(env, NULL);
    641         return;
    642     }
    643 
    644     const char* file8 = env->GetStringUTFChars(fileStr, NULL);
    645     if (file8 == NULL) {
    646         return;
    647     }
    648     String8 file(file8);
    649     env->ReleaseStringUTFChars(fileStr, file8);
    650 
    651     jsize count = env->GetArrayLength(reqFields);
    652     if (count > env->GetArrayLength(outFields)) {
    653         jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
    654         return;
    655     }
    656 
    657     Vector<String8> fields;
    658     int i;
    659 
    660     for (i=0; i<count; i++) {
    661         jobject obj = env->GetObjectArrayElement(reqFields, i);
    662         if (obj != NULL) {
    663             const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
    664             //ALOGI("String at %d: %p = %s", i, obj, str8);
    665             if (str8 == NULL) {
    666                 jniThrowNullPointerException(env, "Element in reqFields");
    667                 return;
    668             }
    669             fields.add(String8(str8));
    670             env->ReleaseStringUTFChars((jstring)obj, str8);
    671         } else {
    672             jniThrowNullPointerException(env, "Element in reqFields");
    673             return;
    674         }
    675     }
    676 
    677     jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
    678     if (sizesArray == NULL) {
    679         return;
    680     }
    681 
    682     //ALOGI("Clearing %" PRId32 " sizes", count);
    683     for (i=0; i<count; i++) {
    684         sizesArray[i] = 0;
    685     }
    686 
    687     int fd = open(file.string(), O_RDONLY);
    688 
    689     if (fd >= 0) {
    690         const size_t BUFFER_SIZE = 2048;
    691         char* buffer = (char*)malloc(BUFFER_SIZE);
    692         int len = read(fd, buffer, BUFFER_SIZE-1);
    693         close(fd);
    694 
    695         if (len < 0) {
    696             ALOGW("Unable to read %s", file.string());
    697             len = 0;
    698         }
    699         buffer[len] = 0;
    700 
    701         int foundCount = 0;
    702 
    703         char* p = buffer;
    704         while (*p && foundCount < count) {
    705             bool skipToEol = true;
    706             //ALOGI("Parsing at: %s", p);
    707             for (i=0; i<count; i++) {
    708                 const String8& field = fields[i];
    709                 if (strncmp(p, field.string(), field.length()) == 0) {
    710                     p += field.length();
    711                     while (*p == ' ' || *p == '\t') p++;
    712                     char* num = p;
    713                     while (*p >= '0' && *p <= '9') p++;
    714                     skipToEol = *p != '\n';
    715                     if (*p != 0) {
    716                         *p = 0;
    717                         p++;
    718                     }
    719                     char* end;
    720                     sizesArray[i] = strtoll(num, &end, 10);
    721                     //ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
    722                     foundCount++;
    723                     break;
    724                 }
    725             }
    726             if (skipToEol) {
    727                 while (*p && *p != '\n') {
    728                     p++;
    729                 }
    730                 if (*p == '\n') {
    731                     p++;
    732                 }
    733             }
    734         }
    735 
    736         free(buffer);
    737     } else {
    738         ALOGW("Unable to open %s", file.string());
    739     }
    740 
    741     //ALOGI("Done!");
    742     env->ReleaseLongArrayElements(outFields, sizesArray, 0);
    743 }
    744 
    745 jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
    746                                      jstring file, jintArray lastArray)
    747 {
    748     if (file == NULL) {
    749         jniThrowNullPointerException(env, NULL);
    750         return NULL;
    751     }
    752 
    753     const char* file8 = env->GetStringUTFChars(file, NULL);
    754     if (file8 == NULL) {
    755         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
    756         return NULL;
    757     }
    758 
    759     DIR* dirp = opendir(file8);
    760 
    761     env->ReleaseStringUTFChars(file, file8);
    762 
    763     if(dirp == NULL) {
    764         return NULL;
    765     }
    766 
    767     jsize curCount = 0;
    768     jint* curData = NULL;
    769     if (lastArray != NULL) {
    770         curCount = env->GetArrayLength(lastArray);
    771         curData = env->GetIntArrayElements(lastArray, 0);
    772     }
    773 
    774     jint curPos = 0;
    775 
    776     struct dirent* entry;
    777     while ((entry=readdir(dirp)) != NULL) {
    778         const char* p = entry->d_name;
    779         while (*p) {
    780             if (*p < '0' || *p > '9') break;
    781             p++;
    782         }
    783         if (*p != 0) continue;
    784 
    785         char* end;
    786         int pid = strtol(entry->d_name, &end, 10);
    787         //ALOGI("File %s pid=%d\n", entry->d_name, pid);
    788         if (curPos >= curCount) {
    789             jsize newCount = (curCount == 0) ? 10 : (curCount*2);
    790             jintArray newArray = env->NewIntArray(newCount);
    791             if (newArray == NULL) {
    792                 closedir(dirp);
    793                 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
    794                 return NULL;
    795             }
    796             jint* newData = env->GetIntArrayElements(newArray, 0);
    797             if (curData != NULL) {
    798                 memcpy(newData, curData, sizeof(jint)*curCount);
    799                 env->ReleaseIntArrayElements(lastArray, curData, 0);
    800             }
    801             lastArray = newArray;
    802             curCount = newCount;
    803             curData = newData;
    804         }
    805 
    806         curData[curPos] = pid;
    807         curPos++;
    808     }
    809 
    810     closedir(dirp);
    811 
    812     if (curData != NULL && curPos > 0) {
    813         qsort(curData, curPos, sizeof(jint), pid_compare);
    814     }
    815 
    816     while (curPos < curCount) {
    817         curData[curPos] = -1;
    818         curPos++;
    819     }
    820 
    821     if (curData != NULL) {
    822         env->ReleaseIntArrayElements(lastArray, curData, 0);
    823     }
    824 
    825     return lastArray;
    826 }
    827 
    828 enum {
    829     PROC_TERM_MASK = 0xff,
    830     PROC_ZERO_TERM = 0,
    831     PROC_SPACE_TERM = ' ',
    832     PROC_COMBINE = 0x100,
    833     PROC_PARENS = 0x200,
    834     PROC_QUOTES = 0x400,
    835     PROC_CHAR = 0x800,
    836     PROC_OUT_STRING = 0x1000,
    837     PROC_OUT_LONG = 0x2000,
    838     PROC_OUT_FLOAT = 0x4000,
    839 };
    840 
    841 jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
    842         char* buffer, jint startIndex, jint endIndex, jintArray format,
    843         jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
    844 {
    845 
    846     const jsize NF = env->GetArrayLength(format);
    847     const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
    848     const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
    849     const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
    850 
    851     jint* formatData = env->GetIntArrayElements(format, 0);
    852     jlong* longsData = outLongs ?
    853         env->GetLongArrayElements(outLongs, 0) : NULL;
    854     jfloat* floatsData = outFloats ?
    855         env->GetFloatArrayElements(outFloats, 0) : NULL;
    856     if (formatData == NULL || (NL > 0 && longsData == NULL)
    857             || (NR > 0 && floatsData == NULL)) {
    858         if (formatData != NULL) {
    859             env->ReleaseIntArrayElements(format, formatData, 0);
    860         }
    861         if (longsData != NULL) {
    862             env->ReleaseLongArrayElements(outLongs, longsData, 0);
    863         }
    864         if (floatsData != NULL) {
    865             env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
    866         }
    867         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
    868         return JNI_FALSE;
    869     }
    870 
    871     jsize i = startIndex;
    872     jsize di = 0;
    873 
    874     jboolean res = JNI_TRUE;
    875 
    876     for (jsize fi=0; fi<NF; fi++) {
    877         jint mode = formatData[fi];
    878         if ((mode&PROC_PARENS) != 0) {
    879             i++;
    880         } else if ((mode&PROC_QUOTES) != 0) {
    881             if (buffer[i] == '"') {
    882                 i++;
    883             } else {
    884                 mode &= ~PROC_QUOTES;
    885             }
    886         }
    887         const char term = (char)(mode&PROC_TERM_MASK);
    888         const jsize start = i;
    889         if (i >= endIndex) {
    890             if (kDebugProc) {
    891                 ALOGW("Ran off end of data @%d", i);
    892             }
    893             res = JNI_FALSE;
    894             break;
    895         }
    896 
    897         jsize end = -1;
    898         if ((mode&PROC_PARENS) != 0) {
    899             while (i < endIndex && buffer[i] != ')') {
    900                 i++;
    901             }
    902             end = i;
    903             i++;
    904         } else if ((mode&PROC_QUOTES) != 0) {
    905             while (buffer[i] != '"' && i < endIndex) {
    906                 i++;
    907             }
    908             end = i;
    909             i++;
    910         }
    911         while (i < endIndex && buffer[i] != term) {
    912             i++;
    913         }
    914         if (end < 0) {
    915             end = i;
    916         }
    917 
    918         if (i < endIndex) {
    919             i++;
    920             if ((mode&PROC_COMBINE) != 0) {
    921                 while (i < endIndex && buffer[i] == term) {
    922                     i++;
    923                 }
    924             }
    925         }
    926 
    927         //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
    928 
    929         if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
    930             char c = buffer[end];
    931             buffer[end] = 0;
    932             if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
    933                 char* end;
    934                 floatsData[di] = strtof(buffer+start, &end);
    935             }
    936             if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
    937                 if ((mode&PROC_CHAR) != 0) {
    938                     // Caller wants single first character returned as one long.
    939                     longsData[di] = buffer[start];
    940                 } else {
    941                     char* end;
    942                     longsData[di] = strtoll(buffer+start, &end, 10);
    943                 }
    944             }
    945             if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
    946                 jstring str = env->NewStringUTF(buffer+start);
    947                 env->SetObjectArrayElement(outStrings, di, str);
    948             }
    949             buffer[end] = c;
    950             di++;
    951         }
    952     }
    953 
    954     env->ReleaseIntArrayElements(format, formatData, 0);
    955     if (longsData != NULL) {
    956         env->ReleaseLongArrayElements(outLongs, longsData, 0);
    957     }
    958     if (floatsData != NULL) {
    959         env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
    960     }
    961 
    962     return res;
    963 }
    964 
    965 jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
    966         jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
    967         jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
    968 {
    969         jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
    970 
    971         jboolean result = android_os_Process_parseProcLineArray(env, clazz,
    972                 (char*) bufferArray, startIndex, endIndex, format, outStrings,
    973                 outLongs, outFloats);
    974 
    975         env->ReleaseByteArrayElements(buffer, bufferArray, 0);
    976 
    977         return result;
    978 }
    979 
    980 jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
    981         jstring file, jintArray format, jobjectArray outStrings,
    982         jlongArray outLongs, jfloatArray outFloats)
    983 {
    984     if (file == NULL || format == NULL) {
    985         jniThrowNullPointerException(env, NULL);
    986         return JNI_FALSE;
    987     }
    988 
    989     const char* file8 = env->GetStringUTFChars(file, NULL);
    990     if (file8 == NULL) {
    991         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
    992         return JNI_FALSE;
    993     }
    994     int fd = open(file8, O_RDONLY);
    995 
    996     if (fd < 0) {
    997         if (kDebugProc) {
    998             ALOGW("Unable to open process file: %s\n", file8);
    999         }
   1000         env->ReleaseStringUTFChars(file, file8);
   1001         return JNI_FALSE;
   1002     }
   1003     env->ReleaseStringUTFChars(file, file8);
   1004 
   1005     char buffer[256];
   1006     const int len = read(fd, buffer, sizeof(buffer)-1);
   1007     close(fd);
   1008 
   1009     if (len < 0) {
   1010         if (kDebugProc) {
   1011             ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
   1012         }
   1013         return JNI_FALSE;
   1014     }
   1015     buffer[len] = 0;
   1016 
   1017     return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
   1018             format, outStrings, outLongs, outFloats);
   1019 
   1020 }
   1021 
   1022 void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
   1023                                              jobject binderObject)
   1024 {
   1025     if (binderObject == NULL) {
   1026         jniThrowNullPointerException(env, NULL);
   1027         return;
   1028     }
   1029 
   1030     sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
   1031 }
   1032 
   1033 void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
   1034 {
   1035     if (pid > 0) {
   1036         ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
   1037         kill(pid, sig);
   1038     }
   1039 }
   1040 
   1041 void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
   1042 {
   1043     if (pid > 0) {
   1044         kill(pid, sig);
   1045     }
   1046 }
   1047 
   1048 static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
   1049 {
   1050     struct timespec ts;
   1051 
   1052     int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
   1053 
   1054     if (res != 0) {
   1055         return (jlong) 0;
   1056     }
   1057 
   1058     nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
   1059     return (jlong) nanoseconds_to_milliseconds(when);
   1060 }
   1061 
   1062 static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
   1063 {
   1064     char filename[64];
   1065 
   1066     snprintf(filename, sizeof(filename), "/proc/%" PRId32 "/smaps", pid);
   1067 
   1068     FILE * file = fopen(filename, "r");
   1069     if (!file) {
   1070         return (jlong) -1;
   1071     }
   1072 
   1073     // Tally up all of the Pss from the various maps
   1074     char line[256];
   1075     jlong pss = 0;
   1076     while (fgets(line, sizeof(line), file)) {
   1077         jlong v;
   1078         if (sscanf(line, "Pss: %" SCNd64 " kB", &v) == 1) {
   1079             pss += v;
   1080         }
   1081     }
   1082 
   1083     fclose(file);
   1084 
   1085     // Return the Pss value in bytes, not kilobytes
   1086     return pss * 1024;
   1087 }
   1088 
   1089 jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
   1090         jobjectArray commandNames)
   1091 {
   1092     if (commandNames == NULL) {
   1093         jniThrowNullPointerException(env, NULL);
   1094         return NULL;
   1095     }
   1096 
   1097     Vector<String8> commands;
   1098 
   1099     jsize count = env->GetArrayLength(commandNames);
   1100 
   1101     for (int i=0; i<count; i++) {
   1102         jobject obj = env->GetObjectArrayElement(commandNames, i);
   1103         if (obj != NULL) {
   1104             const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
   1105             if (str8 == NULL) {
   1106                 jniThrowNullPointerException(env, "Element in commandNames");
   1107                 return NULL;
   1108             }
   1109             commands.add(String8(str8));
   1110             env->ReleaseStringUTFChars((jstring)obj, str8);
   1111         } else {
   1112             jniThrowNullPointerException(env, "Element in commandNames");
   1113             return NULL;
   1114         }
   1115     }
   1116 
   1117     Vector<jint> pids;
   1118 
   1119     DIR *proc = opendir("/proc");
   1120     if (proc == NULL) {
   1121         fprintf(stderr, "/proc: %s\n", strerror(errno));
   1122         return NULL;
   1123     }
   1124 
   1125     struct dirent *d;
   1126     while ((d = readdir(proc))) {
   1127         int pid = atoi(d->d_name);
   1128         if (pid <= 0) continue;
   1129 
   1130         char path[PATH_MAX];
   1131         char data[PATH_MAX];
   1132         snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
   1133 
   1134         int fd = open(path, O_RDONLY);
   1135         if (fd < 0) {
   1136             continue;
   1137         }
   1138         const int len = read(fd, data, sizeof(data)-1);
   1139         close(fd);
   1140 
   1141         if (len < 0) {
   1142             continue;
   1143         }
   1144         data[len] = 0;
   1145 
   1146         for (int i=0; i<len; i++) {
   1147             if (data[i] == ' ') {
   1148                 data[i] = 0;
   1149                 break;
   1150             }
   1151         }
   1152 
   1153         for (size_t i=0; i<commands.size(); i++) {
   1154             if (commands[i] == data) {
   1155                 pids.add(pid);
   1156                 break;
   1157             }
   1158         }
   1159     }
   1160 
   1161     closedir(proc);
   1162 
   1163     jintArray pidArray = env->NewIntArray(pids.size());
   1164     if (pidArray == NULL) {
   1165         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
   1166         return NULL;
   1167     }
   1168 
   1169     if (pids.size() > 0) {
   1170         env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
   1171     }
   1172 
   1173     return pidArray;
   1174 }
   1175 
   1176 jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
   1177 {
   1178     return killProcessGroup(uid, pid, SIGKILL);
   1179 }
   1180 
   1181 void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
   1182 {
   1183     return removeAllProcessGroups();
   1184 }
   1185 
   1186 static const JNINativeMethod methods[] = {
   1187     {"getUidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
   1188     {"getGidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
   1189     {"setThreadPriority",   "(II)V", (void*)android_os_Process_setThreadPriority},
   1190     {"setThreadScheduler",  "(III)V", (void*)android_os_Process_setThreadScheduler},
   1191     {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
   1192     {"setThreadPriority",   "(I)V", (void*)android_os_Process_setCallingThreadPriority},
   1193     {"getThreadPriority",   "(I)I", (void*)android_os_Process_getThreadPriority},
   1194     {"setThreadGroup",      "(II)V", (void*)android_os_Process_setThreadGroup},
   1195     {"setProcessGroup",     "(II)V", (void*)android_os_Process_setProcessGroup},
   1196     {"getProcessGroup",     "(I)I", (void*)android_os_Process_getProcessGroup},
   1197     {"getExclusiveCores",   "()[I", (void*)android_os_Process_getExclusiveCores},
   1198     {"setSwappiness",   "(IZ)Z", (void*)android_os_Process_setSwappiness},
   1199     {"setArgV0",    "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
   1200     {"setUid", "(I)I", (void*)android_os_Process_setUid},
   1201     {"setGid", "(I)I", (void*)android_os_Process_setGid},
   1202     {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
   1203     {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
   1204     {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
   1205     {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
   1206     {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
   1207     {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
   1208     {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
   1209     {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
   1210     {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
   1211     {"getPss", "(I)J", (void*)android_os_Process_getPss},
   1212     {"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
   1213     //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
   1214     {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
   1215     {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
   1216 };
   1217 
   1218 int register_android_os_Process(JNIEnv* env)
   1219 {
   1220     return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
   1221 }
   1222