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