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