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