android_util_Process.cpp revision 71ae2bd42be21de6d25d1f8c52e3973c172462df
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_setSwappiness(JNIEnv *env, jobject clazz,
348                                          jint pid, jboolean is_increased)
349{
350    char text[64];
351
352    if (is_increased) {
353        strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
354    } else {
355        strcpy(text, "/sys/fs/cgroup/memory/tasks");
356    }
357
358    struct stat st;
359    if (stat(text, &st) || !S_ISREG(st.st_mode)) {
360        return false;
361    }
362
363    int fd = open(text, O_WRONLY);
364    if (fd >= 0) {
365        sprintf(text, "%d", pid);
366        write(fd, text, strlen(text));
367        close(fd);
368    }
369
370    return true;
371}
372
373void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
374{
375    if (name == NULL) {
376        jniThrowNullPointerException(env, NULL);
377        return;
378    }
379
380    const jchar* str = env->GetStringCritical(name, 0);
381    String8 name8;
382    if (str) {
383        name8 = String8(str, env->GetStringLength(name));
384        env->ReleaseStringCritical(name, str);
385    }
386
387    if (name8.size() > 0) {
388        const char* procName = name8.string();
389        set_process_name(procName);
390        AndroidRuntime::getRuntime()->setArgv0(procName);
391    }
392}
393
394jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
395{
396    return setuid(uid) == 0 ? 0 : errno;
397}
398
399jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
400{
401    return setgid(uid) == 0 ? 0 : errno;
402}
403
404static int pid_compare(const void* v1, const void* v2)
405{
406    //ALOGI("Compare %d vs %d\n", *((const jint*)v1), *((const jint*)v2));
407    return *((const jint*)v1) - *((const jint*)v2);
408}
409
410static jlong getFreeMemoryImpl(const char* const sums[], const size_t sumsLen[], size_t num)
411{
412    int fd = open("/proc/meminfo", O_RDONLY);
413
414    if (fd < 0) {
415        ALOGW("Unable to open /proc/meminfo");
416        return -1;
417    }
418
419    char buffer[256];
420    const int len = read(fd, buffer, sizeof(buffer)-1);
421    close(fd);
422
423    if (len < 0) {
424        ALOGW("Unable to read /proc/meminfo");
425        return -1;
426    }
427    buffer[len] = 0;
428
429    size_t numFound = 0;
430    jlong mem = 0;
431
432    char* p = buffer;
433    while (*p && numFound < num) {
434        int i = 0;
435        while (sums[i]) {
436            if (strncmp(p, sums[i], sumsLen[i]) == 0) {
437                p += sumsLen[i];
438                while (*p == ' ') p++;
439                char* num = p;
440                while (*p >= '0' && *p <= '9') p++;
441                if (*p != 0) {
442                    *p = 0;
443                    p++;
444                    if (*p == 0) p--;
445                }
446                mem += atoll(num) * 1024;
447                numFound++;
448                break;
449            }
450            i++;
451        }
452        p++;
453    }
454
455    return numFound > 0 ? mem : -1;
456}
457
458static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
459{
460    static const char* const sums[] = { "MemFree:", "Cached:", NULL };
461    static const size_t sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 };
462    return getFreeMemoryImpl(sums, sumsLen, 2);
463}
464
465static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
466{
467    static const char* const sums[] = { "MemTotal:", NULL };
468    static const size_t sumsLen[] = { strlen("MemTotal:"), 0 };
469    return getFreeMemoryImpl(sums, sumsLen, 1);
470}
471
472void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
473                                      jobjectArray reqFields, jlongArray outFields)
474{
475    //ALOGI("getMemInfo: %p %p", reqFields, outFields);
476
477    if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
478        jniThrowNullPointerException(env, NULL);
479        return;
480    }
481
482    const char* file8 = env->GetStringUTFChars(fileStr, NULL);
483    if (file8 == NULL) {
484        return;
485    }
486    String8 file(file8);
487    env->ReleaseStringUTFChars(fileStr, file8);
488
489    jsize count = env->GetArrayLength(reqFields);
490    if (count > env->GetArrayLength(outFields)) {
491        jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
492        return;
493    }
494
495    Vector<String8> fields;
496    int i;
497
498    for (i=0; i<count; i++) {
499        jobject obj = env->GetObjectArrayElement(reqFields, i);
500        if (obj != NULL) {
501            const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
502            //ALOGI("String at %d: %p = %s", i, obj, str8);
503            if (str8 == NULL) {
504                jniThrowNullPointerException(env, "Element in reqFields");
505                return;
506            }
507            fields.add(String8(str8));
508            env->ReleaseStringUTFChars((jstring)obj, str8);
509        } else {
510            jniThrowNullPointerException(env, "Element in reqFields");
511            return;
512        }
513    }
514
515    jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
516    if (sizesArray == NULL) {
517        return;
518    }
519
520    //ALOGI("Clearing %d sizes", count);
521    for (i=0; i<count; i++) {
522        sizesArray[i] = 0;
523    }
524
525    int fd = open(file.string(), O_RDONLY);
526
527    if (fd >= 0) {
528        const size_t BUFFER_SIZE = 2048;
529        char* buffer = (char*)malloc(BUFFER_SIZE);
530        int len = read(fd, buffer, BUFFER_SIZE-1);
531        close(fd);
532
533        if (len < 0) {
534            ALOGW("Unable to read %s", file.string());
535            len = 0;
536        }
537        buffer[len] = 0;
538
539        int foundCount = 0;
540
541        char* p = buffer;
542        while (*p && foundCount < count) {
543            bool skipToEol = true;
544            //ALOGI("Parsing at: %s", p);
545            for (i=0; i<count; i++) {
546                const String8& field = fields[i];
547                if (strncmp(p, field.string(), field.length()) == 0) {
548                    p += field.length();
549                    while (*p == ' ' || *p == '\t') p++;
550                    char* num = p;
551                    while (*p >= '0' && *p <= '9') p++;
552                    skipToEol = *p != '\n';
553                    if (*p != 0) {
554                        *p = 0;
555                        p++;
556                    }
557                    char* end;
558                    sizesArray[i] = strtoll(num, &end, 10);
559                    //ALOGI("Field %s = %d", field.string(), sizesArray[i]);
560                    foundCount++;
561                    break;
562                }
563            }
564            if (skipToEol) {
565                while (*p && *p != '\n') {
566                    p++;
567                }
568                if (*p == '\n') {
569                    p++;
570                }
571            }
572        }
573
574        free(buffer);
575    } else {
576        ALOGW("Unable to open %s", file.string());
577    }
578
579    //ALOGI("Done!");
580    env->ReleaseLongArrayElements(outFields, sizesArray, 0);
581}
582
583jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
584                                     jstring file, jintArray lastArray)
585{
586    if (file == NULL) {
587        jniThrowNullPointerException(env, NULL);
588        return NULL;
589    }
590
591    const char* file8 = env->GetStringUTFChars(file, NULL);
592    if (file8 == NULL) {
593        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
594        return NULL;
595    }
596
597    DIR* dirp = opendir(file8);
598
599    env->ReleaseStringUTFChars(file, file8);
600
601    if(dirp == NULL) {
602        return NULL;
603    }
604
605    jsize curCount = 0;
606    jint* curData = NULL;
607    if (lastArray != NULL) {
608        curCount = env->GetArrayLength(lastArray);
609        curData = env->GetIntArrayElements(lastArray, 0);
610    }
611
612    jint curPos = 0;
613
614    struct dirent* entry;
615    while ((entry=readdir(dirp)) != NULL) {
616        const char* p = entry->d_name;
617        while (*p) {
618            if (*p < '0' || *p > '9') break;
619            p++;
620        }
621        if (*p != 0) continue;
622
623        char* end;
624        int pid = strtol(entry->d_name, &end, 10);
625        //ALOGI("File %s pid=%d\n", entry->d_name, pid);
626        if (curPos >= curCount) {
627            jsize newCount = (curCount == 0) ? 10 : (curCount*2);
628            jintArray newArray = env->NewIntArray(newCount);
629            if (newArray == NULL) {
630                closedir(dirp);
631                jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
632                return NULL;
633            }
634            jint* newData = env->GetIntArrayElements(newArray, 0);
635            if (curData != NULL) {
636                memcpy(newData, curData, sizeof(jint)*curCount);
637                env->ReleaseIntArrayElements(lastArray, curData, 0);
638            }
639            lastArray = newArray;
640            curCount = newCount;
641            curData = newData;
642        }
643
644        curData[curPos] = pid;
645        curPos++;
646    }
647
648    closedir(dirp);
649
650    if (curData != NULL && curPos > 0) {
651        qsort(curData, curPos, sizeof(jint), pid_compare);
652    }
653
654    while (curPos < curCount) {
655        curData[curPos] = -1;
656        curPos++;
657    }
658
659    if (curData != NULL) {
660        env->ReleaseIntArrayElements(lastArray, curData, 0);
661    }
662
663    return lastArray;
664}
665
666enum {
667    PROC_TERM_MASK = 0xff,
668    PROC_ZERO_TERM = 0,
669    PROC_SPACE_TERM = ' ',
670    PROC_COMBINE = 0x100,
671    PROC_PARENS = 0x200,
672    PROC_QUOTES = 0x400,
673    PROC_OUT_STRING = 0x1000,
674    PROC_OUT_LONG = 0x2000,
675    PROC_OUT_FLOAT = 0x4000,
676};
677
678jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
679        char* buffer, jint startIndex, jint endIndex, jintArray format,
680        jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
681{
682
683    const jsize NF = env->GetArrayLength(format);
684    const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
685    const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
686    const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
687
688    jint* formatData = env->GetIntArrayElements(format, 0);
689    jlong* longsData = outLongs ?
690        env->GetLongArrayElements(outLongs, 0) : NULL;
691    jfloat* floatsData = outFloats ?
692        env->GetFloatArrayElements(outFloats, 0) : NULL;
693    if (formatData == NULL || (NL > 0 && longsData == NULL)
694            || (NR > 0 && floatsData == NULL)) {
695        if (formatData != NULL) {
696            env->ReleaseIntArrayElements(format, formatData, 0);
697        }
698        if (longsData != NULL) {
699            env->ReleaseLongArrayElements(outLongs, longsData, 0);
700        }
701        if (floatsData != NULL) {
702            env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
703        }
704        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
705        return JNI_FALSE;
706    }
707
708    jsize i = startIndex;
709    jsize di = 0;
710
711    jboolean res = JNI_TRUE;
712
713    for (jsize fi=0; fi<NF; fi++) {
714        jint mode = formatData[fi];
715        if ((mode&PROC_PARENS) != 0) {
716            i++;
717        } else if ((mode&PROC_QUOTES != 0)) {
718            if (buffer[i] == '"') {
719                i++;
720            } else {
721                mode &= ~PROC_QUOTES;
722            }
723        }
724        const char term = (char)(mode&PROC_TERM_MASK);
725        const jsize start = i;
726        if (i >= endIndex) {
727            res = JNI_FALSE;
728            break;
729        }
730
731        jsize end = -1;
732        if ((mode&PROC_PARENS) != 0) {
733            while (i < endIndex && buffer[i] != ')') {
734                i++;
735            }
736            end = i;
737            i++;
738        } else if ((mode&PROC_QUOTES) != 0) {
739            while (buffer[i] != '"' && i < endIndex) {
740                i++;
741            }
742            end = i;
743            i++;
744        }
745        while (i < endIndex && buffer[i] != term) {
746            i++;
747        }
748        if (end < 0) {
749            end = i;
750        }
751
752        if (i < endIndex) {
753            i++;
754            if ((mode&PROC_COMBINE) != 0) {
755                while (i < endIndex && buffer[i] == term) {
756                    i++;
757                }
758            }
759        }
760
761        //ALOGI("Field %d: %d-%d dest=%d mode=0x%x\n", i, start, end, di, mode);
762
763        if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
764            char c = buffer[end];
765            buffer[end] = 0;
766            if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
767                char* end;
768                floatsData[di] = strtof(buffer+start, &end);
769            }
770            if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
771                char* end;
772                longsData[di] = strtoll(buffer+start, &end, 10);
773            }
774            if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
775                jstring str = env->NewStringUTF(buffer+start);
776                env->SetObjectArrayElement(outStrings, di, str);
777            }
778            buffer[end] = c;
779            di++;
780        }
781    }
782
783    env->ReleaseIntArrayElements(format, formatData, 0);
784    if (longsData != NULL) {
785        env->ReleaseLongArrayElements(outLongs, longsData, 0);
786    }
787    if (floatsData != NULL) {
788        env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
789    }
790
791    return res;
792}
793
794jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
795        jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
796        jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
797{
798        jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
799
800        jboolean result = android_os_Process_parseProcLineArray(env, clazz,
801                (char*) bufferArray, startIndex, endIndex, format, outStrings,
802                outLongs, outFloats);
803
804        env->ReleaseByteArrayElements(buffer, bufferArray, 0);
805
806        return result;
807}
808
809jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
810        jstring file, jintArray format, jobjectArray outStrings,
811        jlongArray outLongs, jfloatArray outFloats)
812{
813    if (file == NULL || format == NULL) {
814        jniThrowNullPointerException(env, NULL);
815        return JNI_FALSE;
816    }
817
818    const char* file8 = env->GetStringUTFChars(file, NULL);
819    if (file8 == NULL) {
820        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
821        return JNI_FALSE;
822    }
823    int fd = open(file8, O_RDONLY);
824    env->ReleaseStringUTFChars(file, file8);
825
826    if (fd < 0) {
827        //ALOGW("Unable to open process file: %s\n", file8);
828        return JNI_FALSE;
829    }
830
831    char buffer[256];
832    const int len = read(fd, buffer, sizeof(buffer)-1);
833    close(fd);
834
835    if (len < 0) {
836        //ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
837        return JNI_FALSE;
838    }
839    buffer[len] = 0;
840
841    return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
842            format, outStrings, outLongs, outFloats);
843
844}
845
846void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
847                                             jobject binderObject)
848{
849    if (binderObject == NULL) {
850        jniThrowNullPointerException(env, NULL);
851        return;
852    }
853
854    sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
855}
856
857void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
858{
859    if (pid > 0) {
860        ALOGI("Sending signal. PID: %d SIG: %d", pid, sig);
861        kill(pid, sig);
862    }
863}
864
865void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
866{
867    if (pid > 0) {
868        kill(pid, sig);
869    }
870}
871
872static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
873{
874    struct timespec ts;
875
876    int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
877
878    if (res != 0) {
879        return (jlong) 0;
880    }
881
882    nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
883    return (jlong) nanoseconds_to_milliseconds(when);
884}
885
886static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
887{
888    char filename[64];
889
890    snprintf(filename, sizeof(filename), "/proc/%d/smaps", pid);
891
892    FILE * file = fopen(filename, "r");
893    if (!file) {
894        return (jlong) -1;
895    }
896
897    // Tally up all of the Pss from the various maps
898    char line[256];
899    jlong pss = 0;
900    while (fgets(line, sizeof(line), file)) {
901        jlong v;
902        if (sscanf(line, "Pss: %lld kB", &v) == 1) {
903            pss += v;
904        }
905    }
906
907    fclose(file);
908
909    // Return the Pss value in bytes, not kilobytes
910    return pss * 1024;
911}
912
913jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
914        jobjectArray commandNames)
915{
916    if (commandNames == NULL) {
917        jniThrowNullPointerException(env, NULL);
918        return NULL;
919    }
920
921    Vector<String8> commands;
922
923    jsize count = env->GetArrayLength(commandNames);
924
925    for (int i=0; i<count; i++) {
926        jobject obj = env->GetObjectArrayElement(commandNames, i);
927        if (obj != NULL) {
928            const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
929            if (str8 == NULL) {
930                jniThrowNullPointerException(env, "Element in commandNames");
931                return NULL;
932            }
933            commands.add(String8(str8));
934            env->ReleaseStringUTFChars((jstring)obj, str8);
935        } else {
936            jniThrowNullPointerException(env, "Element in commandNames");
937            return NULL;
938        }
939    }
940
941    Vector<jint> pids;
942
943    DIR *proc = opendir("/proc");
944    if (proc == NULL) {
945        fprintf(stderr, "/proc: %s\n", strerror(errno));
946        return NULL;
947    }
948
949    struct dirent *d;
950    while ((d = readdir(proc))) {
951        int pid = atoi(d->d_name);
952        if (pid <= 0) continue;
953
954        char path[PATH_MAX];
955        char data[PATH_MAX];
956        snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
957
958        int fd = open(path, O_RDONLY);
959        if (fd < 0) {
960            continue;
961        }
962        const int len = read(fd, data, sizeof(data)-1);
963        close(fd);
964
965        if (len < 0) {
966            continue;
967        }
968        data[len] = 0;
969
970        for (int i=0; i<len; i++) {
971            if (data[i] == ' ') {
972                data[i] = 0;
973                break;
974            }
975        }
976
977        for (size_t i=0; i<commands.size(); i++) {
978            if (commands[i] == data) {
979                pids.add(pid);
980                break;
981            }
982        }
983    }
984
985    closedir(proc);
986
987    jintArray pidArray = env->NewIntArray(pids.size());
988    if (pidArray == NULL) {
989        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
990        return NULL;
991    }
992
993    if (pids.size() > 0) {
994        env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
995    }
996
997    return pidArray;
998}
999
1000static const JNINativeMethod methods[] = {
1001    {"getUidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
1002    {"getGidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
1003    {"setThreadPriority",   "(II)V", (void*)android_os_Process_setThreadPriority},
1004    {"setThreadScheduler",  "(III)V", (void*)android_os_Process_setThreadScheduler},
1005    {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
1006    {"setThreadPriority",   "(I)V", (void*)android_os_Process_setCallingThreadPriority},
1007    {"getThreadPriority",   "(I)I", (void*)android_os_Process_getThreadPriority},
1008    {"setThreadGroup",      "(II)V", (void*)android_os_Process_setThreadGroup},
1009    {"setProcessGroup",     "(II)V", (void*)android_os_Process_setProcessGroup},
1010    {"getProcessGroup",     "(I)I", (void*)android_os_Process_getProcessGroup},
1011    {"setSwappiness",   "(IZ)Z", (void*)android_os_Process_setSwappiness},
1012    {"setArgV0",    "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
1013    {"setUid", "(I)I", (void*)android_os_Process_setUid},
1014    {"setGid", "(I)I", (void*)android_os_Process_setGid},
1015    {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
1016    {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
1017    {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
1018    {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
1019    {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
1020    {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
1021    {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
1022    {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
1023    {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
1024    {"getPss", "(I)J", (void*)android_os_Process_getPss},
1025    {"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
1026    //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
1027};
1028
1029const char* const kProcessPathName = "android/os/Process";
1030
1031int register_android_os_Process(JNIEnv* env)
1032{
1033    return AndroidRuntime::registerNativeMethods(
1034        env, kProcessPathName,
1035        methods, NELEM(methods));
1036}
1037