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