android_util_Process.cpp revision 181b31a0d87d525ea64102a965210331e0c6885b
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 <utils/String8.h>
25#include <utils/Vector.h>
26
27#include <android_runtime/AndroidRuntime.h>
28
29#include "android_util_Binder.h"
30#include "JNIHelp.h"
31
32#include <sys/errno.h>
33#include <sys/resource.h>
34#include <sys/types.h>
35#include <dirent.h>
36#include <fcntl.h>
37#include <grp.h>
38#include <pwd.h>
39#include <signal.h>
40
41/* desktop Linux needs a little help with gettid() */
42#if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
43#define __KERNEL__
44# include <linux/unistd.h>
45#ifdef _syscall0
46_syscall0(pid_t,gettid)
47#else
48pid_t gettid() { return syscall(__NR_gettid);}
49#endif
50#undef __KERNEL__
51#endif
52
53using namespace android;
54
55static void signalExceptionForPriorityError(JNIEnv* env, jobject obj, 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, jobject obj, 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
97
98static void fakeProcessEntry(void* arg)
99{
100    String8* cls = (String8*)arg;
101
102    AndroidRuntime* jr = AndroidRuntime::getRuntime();
103    jr->callMain(cls->string(), 0, NULL);
104
105    delete cls;
106}
107
108jint android_os_Process_myPid(JNIEnv* env, jobject clazz)
109{
110    return getpid();
111}
112
113jint android_os_Process_myUid(JNIEnv* env, jobject clazz)
114{
115    return getuid();
116}
117
118jint android_os_Process_myTid(JNIEnv* env, jobject clazz)
119{
120#ifdef HAVE_GETTID
121    return gettid();
122#else
123    return getpid();
124#endif
125}
126
127jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
128{
129    if (name == NULL) {
130        jniThrowException(env, "java/lang/NullPointerException", NULL);
131        return -1;
132    }
133
134    const jchar* str16 = env->GetStringCritical(name, 0);
135    String8 name8;
136    if (str16) {
137        name8 = String8(str16, env->GetStringLength(name));
138        env->ReleaseStringCritical(name, str16);
139    }
140
141    const size_t N = name8.size();
142    if (N > 0) {
143        const char* str = name8.string();
144        for (size_t i=0; i<N; i++) {
145            if (str[i] < '0' || str[i] > '9') {
146                struct passwd* pwd = getpwnam(str);
147                if (pwd == NULL) {
148                    return -1;
149                }
150                return pwd->pw_uid;
151            }
152        }
153        return atoi(str);
154    }
155    return -1;
156}
157
158jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
159{
160    if (name == NULL) {
161        jniThrowException(env, "java/lang/NullPointerException", NULL);
162        return -1;
163    }
164
165    const jchar* str16 = env->GetStringCritical(name, 0);
166    String8 name8;
167    if (str16) {
168        name8 = String8(str16, env->GetStringLength(name));
169        env->ReleaseStringCritical(name, str16);
170    }
171
172    const size_t N = name8.size();
173    if (N > 0) {
174        const char* str = name8.string();
175        for (size_t i=0; i<N; i++) {
176            if (str[i] < '0' || str[i] > '9') {
177                struct group* grp = getgrnam(str);
178                if (grp == NULL) {
179                    return -1;
180                }
181                return grp->gr_gid;
182            }
183        }
184        return atoi(str);
185    }
186    return -1;
187}
188
189static int add_pid_to_cgroup(int pid, const char *grp_name)
190{
191    int fd;
192    char path[255];
193    char text[64];
194
195    sprintf(path, "/dev/cpuctl/%s/tasks", grp_name);
196
197    if ((fd = open(path, O_WRONLY)) < 0)
198        return -1;
199
200    sprintf(text, "%d", pid);
201    if (write(fd, text, strlen(text)) < 0) {
202        close(fd);
203        return -1;
204    }
205
206    close(fd);
207    return 0;
208}
209
210void setSchedPolicy(JNIEnv* env, jobject clazz, int pid, SchedPolicy policy)
211{
212    static int __sys_supports_schedgroups = -1;
213
214    if (__sys_supports_schedgroups < 0) {
215        if (!access("/dev/cpuctl/tasks", F_OK)) {
216            __sys_supports_schedgroups = 1;
217        } else {
218            __sys_supports_schedgroups = 0;
219        }
220    }
221
222    if (__sys_supports_schedgroups) {
223        const char *grp = NULL;
224
225        if (policy == SP_BACKGROUND) {
226            grp = "bg_non_interactive";
227        }
228
229        if (add_pid_to_cgroup(pid, grp)) {
230            if (errno != ESRCH && errno != ENOENT)
231                signalExceptionForGroupError(env, clazz, errno);
232        }
233    } else {
234        struct sched_param param;
235
236        param.sched_priority = 0;
237        sched_setscheduler(pid, (policy == SP_BACKGROUND) ? 5 : 0, &param);
238    }
239}
240
241void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
242{
243    if (grp > ANDROID_TGROUP_MAX || grp < 0) {
244        signalExceptionForGroupError(env, clazz, EINVAL);
245        return;
246    }
247
248    setSchedPolicy(env, clazz, pid,
249                   (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
250                           SP_BACKGROUND : SP_FOREGROUND);
251}
252
253void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
254{
255    DIR *d;
256    FILE *fp;
257    char proc_path[255];
258    struct dirent *de;
259
260    if (grp > ANDROID_TGROUP_MAX || grp < 0) {
261        signalExceptionForGroupError(env, clazz, EINVAL);
262        return;
263    }
264
265    sprintf(proc_path, "/proc/%d/task", pid);
266    if (!(d = opendir(proc_path))) {
267        // If the process exited on us, don't generate an exception
268        if (errno != ENOENT)
269            signalExceptionForGroupError(env, clazz, errno);
270        return;
271    }
272
273    while ((de = readdir(d))) {
274        int t_pid;
275        int t_pri;
276
277        if (de->d_name[0] == '.')
278            continue;
279        t_pid = atoi(de->d_name);
280
281        if (!t_pid) {
282            LOGE("Error getting pid for '%s'\n", de->d_name);
283            continue;
284        }
285
286        t_pri = getpriority(PRIO_PROCESS, t_pid);
287
288        if (grp == ANDROID_TGROUP_DEFAULT &&
289            t_pri >= ANDROID_PRIORITY_BACKGROUND) {
290            // This task wants to stay at background
291            continue;
292        }
293
294        setSchedPolicy(env, clazz, t_pid,
295                       (grp == ANDROID_TGROUP_BG_NONINTERACT) ?
296                               SP_BACKGROUND : SP_FOREGROUND);
297    }
298    closedir(d);
299}
300
301void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
302                                              jint pid, jint pri)
303{
304    if (pri >= ANDROID_PRIORITY_BACKGROUND) {
305        setSchedPolicy(env, clazz, pid, SP_BACKGROUND);
306    } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
307        setSchedPolicy(env, clazz, pid, SP_FOREGROUND);
308    }
309
310    if (setpriority(PRIO_PROCESS, pid, pri) < 0) {
311        signalExceptionForPriorityError(env, clazz, errno);
312    }
313    //LOGI("Setting priority of %d: %d, getpriority returns %d\n",
314    //     pid, pri, getpriority(PRIO_PROCESS, pid));
315}
316
317void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
318                                                        jint pri)
319{
320    jint tid = android_os_Process_myTid(env, clazz);
321    android_os_Process_setThreadPriority(env, clazz, tid, pri);
322}
323
324jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
325                                              jint pid)
326{
327    errno = 0;
328    jint pri = getpriority(PRIO_PROCESS, pid);
329    if (errno != 0) {
330        signalExceptionForPriorityError(env, clazz, errno);
331    }
332    //LOGI("Returning priority of %d: %d\n", pid, pri);
333    return pri;
334}
335
336jboolean android_os_Process_setOomAdj(JNIEnv* env, jobject clazz,
337                                      jint pid, jint adj)
338{
339#ifdef HAVE_OOM_ADJ
340    if (ProcessState::self()->supportsProcesses()) {
341        char text[64];
342        sprintf(text, "/proc/%d/oom_adj", pid);
343        int fd = open(text, O_WRONLY);
344        if (fd >= 0) {
345            sprintf(text, "%d", adj);
346            write(fd, text, strlen(text));
347            close(fd);
348            return true;
349        }
350    }
351#endif
352    return false;
353}
354
355void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
356{
357    if (name == NULL) {
358        jniThrowException(env, "java/lang/NullPointerException", NULL);
359        return;
360    }
361
362    const jchar* str = env->GetStringCritical(name, 0);
363    String8 name8;
364    if (str) {
365        name8 = String8(str, env->GetStringLength(name));
366        env->ReleaseStringCritical(name, str);
367    }
368
369    if (name8.size() > 0) {
370        ProcessState::self()->setArgV0(name8.string());
371    }
372}
373
374jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
375{
376    #if HAVE_ANDROID_OS
377    return setuid(uid) == 0 ? 0 : errno;
378    #else
379    return ENOSYS;
380    #endif
381}
382
383jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
384{
385    #if HAVE_ANDROID_OS
386    return setgid(uid) == 0 ? 0 : errno;
387    #else
388    return ENOSYS;
389    #endif
390}
391
392jboolean android_os_Process_supportsProcesses(JNIEnv* env, jobject clazz)
393{
394    return ProcessState::self()->supportsProcesses();
395}
396
397static int pid_compare(const void* v1, const void* v2)
398{
399    //LOGI("Compare %d vs %d\n", *((const jint*)v1), *((const jint*)v2));
400    return *((const jint*)v1) - *((const jint*)v2);
401}
402
403static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
404{
405    int fd = open("/proc/meminfo", O_RDONLY);
406
407    if (fd < 0) {
408        LOGW("Unable to open /proc/meminfo");
409        return -1;
410    }
411
412    char buffer[256];
413    const int len = read(fd, buffer, sizeof(buffer)-1);
414    close(fd);
415
416    if (len < 0) {
417        LOGW("Unable to read /proc/meminfo");
418        return -1;
419    }
420    buffer[len] = 0;
421
422    int numFound = 0;
423    jlong mem = 0;
424
425    static const char* const sums[] = { "MemFree:", "Cached:", NULL };
426    static const int sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), NULL };
427
428    char* p = buffer;
429    while (*p && numFound < 2) {
430        int i = 0;
431        while (sums[i]) {
432            if (strncmp(p, sums[i], sumsLen[i]) == 0) {
433                p += sumsLen[i];
434                while (*p == ' ') p++;
435                char* num = p;
436                while (*p >= '0' && *p <= '9') p++;
437                if (*p != 0) {
438                    *p = 0;
439                    p++;
440                    if (*p == 0) p--;
441                }
442                mem += atoll(num) * 1024;
443                numFound++;
444                break;
445            }
446            i++;
447        }
448        p++;
449    }
450
451    return numFound > 0 ? mem : -1;
452}
453
454void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
455                                      jobjectArray reqFields, jlongArray outFields)
456{
457    //LOGI("getMemInfo: %p %p", reqFields, outFields);
458
459    if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
460        jniThrowException(env, "java/lang/NullPointerException", NULL);
461        return;
462    }
463
464    const char* file8 = env->GetStringUTFChars(fileStr, NULL);
465    if (file8 == NULL) {
466        return;
467    }
468    String8 file(file8);
469    env->ReleaseStringUTFChars(fileStr, file8);
470
471    jsize count = env->GetArrayLength(reqFields);
472    if (count > env->GetArrayLength(outFields)) {
473        jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
474        return;
475    }
476
477    Vector<String8> fields;
478    int i;
479
480    for (i=0; i<count; i++) {
481        jobject obj = env->GetObjectArrayElement(reqFields, i);
482        if (obj != NULL) {
483            const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
484            //LOGI("String at %d: %p = %s", i, obj, str8);
485            if (str8 == NULL) {
486                jniThrowException(env, "java/lang/NullPointerException", "Element in reqFields");
487                return;
488            }
489            fields.add(String8(str8));
490            env->ReleaseStringUTFChars((jstring)obj, str8);
491        } else {
492            jniThrowException(env, "java/lang/NullPointerException", "Element in reqFields");
493            return;
494        }
495    }
496
497    jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
498    if (sizesArray == NULL) {
499        return;
500    }
501
502    //LOGI("Clearing %d sizes", count);
503    for (i=0; i<count; i++) {
504        sizesArray[i] = 0;
505    }
506
507    int fd = open(file.string(), O_RDONLY);
508
509    if (fd >= 0) {
510        const size_t BUFFER_SIZE = 2048;
511        char* buffer = (char*)malloc(BUFFER_SIZE);
512        int len = read(fd, buffer, BUFFER_SIZE-1);
513        close(fd);
514
515        if (len < 0) {
516            LOGW("Unable to read %s", file.string());
517            len = 0;
518        }
519        buffer[len] = 0;
520
521        int foundCount = 0;
522
523        char* p = buffer;
524        while (*p && foundCount < count) {
525            bool skipToEol = true;
526            //LOGI("Parsing at: %s", p);
527            for (i=0; i<count; i++) {
528                const String8& field = fields[i];
529                if (strncmp(p, field.string(), field.length()) == 0) {
530                    p += field.length();
531                    while (*p == ' ' || *p == '\t') p++;
532                    char* num = p;
533                    while (*p >= '0' && *p <= '9') p++;
534                    skipToEol = *p != '\n';
535                    if (*p != 0) {
536                        *p = 0;
537                        p++;
538                    }
539                    char* end;
540                    sizesArray[i] = strtoll(num, &end, 10);
541                    //LOGI("Field %s = %d", field.string(), sizesArray[i]);
542                    foundCount++;
543                    break;
544                }
545            }
546            if (skipToEol) {
547                while (*p && *p != '\n') {
548                    p++;
549                }
550                if (*p == '\n') {
551                    p++;
552                }
553            }
554        }
555
556        free(buffer);
557    } else {
558        LOGW("Unable to open %s", file.string());
559    }
560
561    //LOGI("Done!");
562    env->ReleaseLongArrayElements(outFields, sizesArray, 0);
563}
564
565jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
566                                     jstring file, jintArray lastArray)
567{
568    if (file == NULL) {
569        jniThrowException(env, "java/lang/NullPointerException", NULL);
570        return NULL;
571    }
572
573    const char* file8 = env->GetStringUTFChars(file, NULL);
574    if (file8 == NULL) {
575        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
576        return NULL;
577    }
578
579    DIR* dirp = opendir(file8);
580
581    env->ReleaseStringUTFChars(file, file8);
582
583    if(dirp == NULL) {
584        return NULL;
585    }
586
587    jsize curCount = 0;
588    jint* curData = NULL;
589    if (lastArray != NULL) {
590        curCount = env->GetArrayLength(lastArray);
591        curData = env->GetIntArrayElements(lastArray, 0);
592    }
593
594    jint curPos = 0;
595
596    struct dirent* entry;
597    while ((entry=readdir(dirp)) != NULL) {
598        const char* p = entry->d_name;
599        while (*p) {
600            if (*p < '0' || *p > '9') break;
601            p++;
602        }
603        if (*p != 0) continue;
604
605        char* end;
606        int pid = strtol(entry->d_name, &end, 10);
607        //LOGI("File %s pid=%d\n", entry->d_name, pid);
608        if (curPos >= curCount) {
609            jsize newCount = (curCount == 0) ? 10 : (curCount*2);
610            jintArray newArray = env->NewIntArray(newCount);
611            if (newArray == NULL) {
612                closedir(dirp);
613                jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
614                return NULL;
615            }
616            jint* newData = env->GetIntArrayElements(newArray, 0);
617            if (curData != NULL) {
618                memcpy(newData, curData, sizeof(jint)*curCount);
619                env->ReleaseIntArrayElements(lastArray, curData, 0);
620            }
621            lastArray = newArray;
622            curCount = newCount;
623            curData = newData;
624        }
625
626        curData[curPos] = pid;
627        curPos++;
628    }
629
630    closedir(dirp);
631
632    if (curData != NULL && curPos > 0) {
633        qsort(curData, curPos, sizeof(jint), pid_compare);
634    }
635
636    while (curPos < curCount) {
637        curData[curPos] = -1;
638        curPos++;
639    }
640
641    if (curData != NULL) {
642        env->ReleaseIntArrayElements(lastArray, curData, 0);
643    }
644
645    return lastArray;
646}
647
648enum {
649    PROC_TERM_MASK = 0xff,
650    PROC_ZERO_TERM = 0,
651    PROC_SPACE_TERM = ' ',
652    PROC_COMBINE = 0x100,
653    PROC_PARENS = 0x200,
654    PROC_OUT_STRING = 0x1000,
655    PROC_OUT_LONG = 0x2000,
656    PROC_OUT_FLOAT = 0x4000,
657};
658
659jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
660        char* buffer, jint startIndex, jint endIndex, jintArray format,
661        jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
662{
663
664    const jsize NF = env->GetArrayLength(format);
665    const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
666    const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
667    const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
668
669    jint* formatData = env->GetIntArrayElements(format, 0);
670    jlong* longsData = outLongs ?
671        env->GetLongArrayElements(outLongs, 0) : NULL;
672    jfloat* floatsData = outFloats ?
673        env->GetFloatArrayElements(outFloats, 0) : NULL;
674    if (formatData == NULL || (NL > 0 && longsData == NULL)
675            || (NR > 0 && floatsData == NULL)) {
676        if (formatData != NULL) {
677            env->ReleaseIntArrayElements(format, formatData, 0);
678        }
679        if (longsData != NULL) {
680            env->ReleaseLongArrayElements(outLongs, longsData, 0);
681        }
682        if (floatsData != NULL) {
683            env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
684        }
685        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
686        return JNI_FALSE;
687    }
688
689    jsize i = startIndex;
690    jsize di = 0;
691
692    jboolean res = JNI_TRUE;
693
694    for (jsize fi=0; fi<NF; fi++) {
695        const jint mode = formatData[fi];
696        if ((mode&PROC_PARENS) != 0) {
697            i++;
698        }
699        const char term = (char)(mode&PROC_TERM_MASK);
700        const jsize start = i;
701        if (i >= endIndex) {
702            res = JNI_FALSE;
703            break;
704        }
705
706        jsize end = -1;
707        if ((mode&PROC_PARENS) != 0) {
708            while (buffer[i] != ')' && i < endIndex) {
709                i++;
710            }
711            end = i;
712            i++;
713        }
714        while (buffer[i] != term && i < endIndex) {
715            i++;
716        }
717        if (end < 0) {
718            end = i;
719        }
720
721        if (i < endIndex) {
722            i++;
723            if ((mode&PROC_COMBINE) != 0) {
724                while (buffer[i] == term && i < endIndex) {
725                    i++;
726                }
727            }
728        }
729
730        //LOGI("Field %d: %d-%d dest=%d mode=0x%x\n", i, start, end, di, mode);
731
732        if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
733            char c = buffer[end];
734            buffer[end] = 0;
735            if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
736                char* end;
737                floatsData[di] = strtof(buffer+start, &end);
738            }
739            if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
740                char* end;
741                longsData[di] = strtoll(buffer+start, &end, 10);
742            }
743            if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
744                jstring str = env->NewStringUTF(buffer+start);
745                env->SetObjectArrayElement(outStrings, di, str);
746            }
747            buffer[end] = c;
748            di++;
749        }
750    }
751
752    env->ReleaseIntArrayElements(format, formatData, 0);
753    if (longsData != NULL) {
754        env->ReleaseLongArrayElements(outLongs, longsData, 0);
755    }
756    if (floatsData != NULL) {
757        env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
758    }
759
760    return res;
761}
762
763jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
764        jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
765        jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
766{
767        jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
768
769        jboolean result = android_os_Process_parseProcLineArray(env, clazz,
770                (char*) bufferArray, startIndex, endIndex, format, outStrings,
771                outLongs, outFloats);
772
773        env->ReleaseByteArrayElements(buffer, bufferArray, 0);
774
775        return result;
776}
777
778jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
779        jstring file, jintArray format, jobjectArray outStrings,
780        jlongArray outLongs, jfloatArray outFloats)
781{
782    if (file == NULL || format == NULL) {
783        jniThrowException(env, "java/lang/NullPointerException", NULL);
784        return JNI_FALSE;
785    }
786
787    const char* file8 = env->GetStringUTFChars(file, NULL);
788    if (file8 == NULL) {
789        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
790        return JNI_FALSE;
791    }
792    int fd = open(file8, O_RDONLY);
793    env->ReleaseStringUTFChars(file, file8);
794
795    if (fd < 0) {
796        //LOGW("Unable to open process file: %s\n", file8);
797        return JNI_FALSE;
798    }
799
800    char buffer[256];
801    const int len = read(fd, buffer, sizeof(buffer)-1);
802    close(fd);
803
804    if (len < 0) {
805        //LOGW("Unable to open process file: %s fd=%d\n", file8, fd);
806        return JNI_FALSE;
807    }
808    buffer[len] = 0;
809
810    return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
811            format, outStrings, outLongs, outFloats);
812
813}
814
815void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
816                                             jobject binderObject)
817{
818    if (binderObject == NULL) {
819        jniThrowException(env, "java/lang/NullPointerException", NULL);
820        return;
821    }
822
823    sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
824}
825
826void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
827{
828    if (pid > 0) {
829        LOGI("Sending signal. PID: %d SIG: %d", pid, sig);
830        kill(pid, sig);
831    }
832}
833
834static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
835{
836    struct timespec ts;
837
838    int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
839
840    if (res != 0) {
841        return (jlong) 0;
842    }
843
844    nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
845    return (jlong) nanoseconds_to_milliseconds(when);
846}
847
848static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
849{
850    char filename[64];
851
852    snprintf(filename, sizeof(filename), "/proc/%d/smaps", pid);
853
854    FILE * file = fopen(filename, "r");
855    if (!file) {
856        return (jlong) -1;
857    }
858
859    // Tally up all of the Pss from the various maps
860    char line[256];
861    jlong pss = 0;
862    while (fgets(line, sizeof(line), file)) {
863        jlong v;
864        if (sscanf(line, "Pss: %lld kB", &v) == 1) {
865            pss += v;
866        }
867    }
868
869    fclose(file);
870
871    // Return the Pss value in bytes, not kilobytes
872    return pss * 1024;
873}
874
875static const JNINativeMethod methods[] = {
876    {"myPid",       "()I", (void*)android_os_Process_myPid},
877    {"myTid",       "()I", (void*)android_os_Process_myTid},
878    {"myUid",       "()I", (void*)android_os_Process_myUid},
879    {"getUidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
880    {"getGidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
881    {"setThreadPriority",   "(II)V", (void*)android_os_Process_setThreadPriority},
882    {"setThreadPriority",   "(I)V", (void*)android_os_Process_setCallingThreadPriority},
883    {"getThreadPriority",   "(I)I", (void*)android_os_Process_getThreadPriority},
884    {"setThreadGroup",      "(II)V", (void*)android_os_Process_setThreadGroup},
885    {"setProcessGroup",      "(II)V", (void*)android_os_Process_setProcessGroup},
886    {"setOomAdj",   "(II)Z", (void*)android_os_Process_setOomAdj},
887    {"setArgV0",    "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
888    {"setUid", "(I)I", (void*)android_os_Process_setUid},
889    {"setGid", "(I)I", (void*)android_os_Process_setGid},
890    {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
891    {"supportsProcesses", "()Z", (void*)android_os_Process_supportsProcesses},
892    {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
893    {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
894    {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
895    {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
896    {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
897    {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
898    {"getPss", "(I)J", (void*)android_os_Process_getPss},
899    //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
900};
901
902const char* const kProcessPathName = "android/os/Process";
903
904int register_android_os_Process(JNIEnv* env)
905{
906    jclass clazz;
907
908    clazz = env->FindClass(kProcessPathName);
909    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Process");
910
911    return AndroidRuntime::registerNativeMethods(
912        env, kProcessPathName,
913        methods, NELEM(methods));
914}
915