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