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