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