android_util_Process.cpp revision 6af763bec7c3f4d50fee8dd0046409bb8a7fe8f6
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#include <unistd.h>
42
43#define POLICY_DEBUG 0
44#define GUARD_THREAD_PRIORITY 0
45
46using namespace android;
47
48#if GUARD_THREAD_PRIORITY
49Mutex gKeyCreateMutex;
50static pthread_key_t gBgKey = -1;
51#endif
52
53static void signalExceptionForPriorityError(JNIEnv* env, jobject obj, int err)
54{
55    switch (err) {
56        case EINVAL:
57            jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
58            break;
59        case ESRCH:
60            jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist");
61            break;
62        case EPERM:
63            jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread");
64            break;
65        case EACCES:
66            jniThrowException(env, "java/lang/SecurityException", "No permission to set to given priority");
67            break;
68        default:
69            jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
70            break;
71    }
72}
73
74static void signalExceptionForGroupError(JNIEnv* env, jobject obj, int err)
75{
76    switch (err) {
77        case EINVAL:
78            jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
79            break;
80        case ESRCH:
81            jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist");
82            break;
83        case EPERM:
84            jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread");
85            break;
86        case EACCES:
87            jniThrowException(env, "java/lang/SecurityException", "No permission to set to given group");
88            break;
89        default:
90            jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
91            break;
92    }
93}
94
95jint android_os_Process_myPid(JNIEnv* env, jobject clazz)
96{
97    return getpid();
98}
99
100jint android_os_Process_myUid(JNIEnv* env, jobject clazz)
101{
102    return getuid();
103}
104
105jint android_os_Process_myTid(JNIEnv* env, jobject clazz)
106{
107    return androidGetTid();
108}
109
110jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
111{
112    if (name == NULL) {
113        jniThrowNullPointerException(env, NULL);
114        return -1;
115    }
116
117    const jchar* str16 = env->GetStringCritical(name, 0);
118    String8 name8;
119    if (str16) {
120        name8 = String8(str16, env->GetStringLength(name));
121        env->ReleaseStringCritical(name, str16);
122    }
123
124    const size_t N = name8.size();
125    if (N > 0) {
126        const char* str = name8.string();
127        for (size_t i=0; i<N; i++) {
128            if (str[i] < '0' || str[i] > '9') {
129                struct passwd* pwd = getpwnam(str);
130                if (pwd == NULL) {
131                    return -1;
132                }
133                return pwd->pw_uid;
134            }
135        }
136        return atoi(str);
137    }
138    return -1;
139}
140
141jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
142{
143    if (name == NULL) {
144        jniThrowNullPointerException(env, NULL);
145        return -1;
146    }
147
148    const jchar* str16 = env->GetStringCritical(name, 0);
149    String8 name8;
150    if (str16) {
151        name8 = String8(str16, env->GetStringLength(name));
152        env->ReleaseStringCritical(name, str16);
153    }
154
155    const size_t N = name8.size();
156    if (N > 0) {
157        const char* str = name8.string();
158        for (size_t i=0; i<N; i++) {
159            if (str[i] < '0' || str[i] > '9') {
160                struct group* grp = getgrnam(str);
161                if (grp == NULL) {
162                    return -1;
163                }
164                return grp->gr_gid;
165            }
166        }
167        return atoi(str);
168    }
169    return -1;
170}
171
172void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
173{
174    int res = androidSetThreadSchedulingGroup(pid, grp);
175    if (res != NO_ERROR) {
176        signalExceptionForGroupError(env, clazz, res == BAD_VALUE ? EINVAL : errno);
177        return;
178    }
179}
180
181void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
182{
183    DIR *d;
184    FILE *fp;
185    char proc_path[255];
186    struct dirent *de;
187
188    if (grp > ANDROID_TGROUP_MAX || grp < 0) {
189        signalExceptionForGroupError(env, clazz, EINVAL);
190        return;
191    }
192
193#if POLICY_DEBUG
194    char cmdline[32];
195    int fd;
196
197    strcpy(cmdline, "unknown");
198
199    sprintf(proc_path, "/proc/%d/cmdline", pid);
200    fd = open(proc_path, O_RDONLY);
201    if (fd >= 0) {
202        int rc = read(fd, cmdline, sizeof(cmdline)-1);
203        cmdline[rc] = 0;
204        close(fd);
205    }
206
207    if (grp == ANDROID_TGROUP_BG_NONINTERACT) {
208        LOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
209    } else {
210        LOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
211    }
212#endif
213    sprintf(proc_path, "/proc/%d/task", pid);
214    if (!(d = opendir(proc_path))) {
215        // If the process exited on us, don't generate an exception
216        if (errno != ENOENT)
217            signalExceptionForGroupError(env, clazz, errno);
218        return;
219    }
220
221    while ((de = readdir(d))) {
222        int t_pid;
223        int t_pri;
224
225        if (de->d_name[0] == '.')
226            continue;
227        t_pid = atoi(de->d_name);
228
229        if (!t_pid) {
230            LOGE("Error getting pid for '%s'\n", de->d_name);
231            continue;
232        }
233
234        t_pri = getpriority(PRIO_PROCESS, t_pid);
235
236        if (grp == ANDROID_TGROUP_DEFAULT &&
237            t_pri >= ANDROID_PRIORITY_BACKGROUND) {
238            // This task wants to stay at background
239            continue;
240        }
241
242        if (androidSetThreadSchedulingGroup(t_pid, grp) != NO_ERROR) {
243            signalExceptionForGroupError(env, clazz, errno);
244            break;
245        }
246    }
247    closedir(d);
248}
249
250static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
251    // Establishes the calling thread as illegal to put into the background.
252    // Typically used only for the system process's main looper.
253#if GUARD_THREAD_PRIORITY
254    LOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, androidGetTid());
255    {
256        Mutex::Autolock _l(gKeyCreateMutex);
257        if (gBgKey == -1) {
258            pthread_key_create(&gBgKey, NULL);
259        }
260    }
261
262    // inverted:  not-okay, we set a sentinel value
263    pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
264#endif
265}
266
267void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
268                                              jint pid, jint pri)
269{
270#if GUARD_THREAD_PRIORITY
271    // if we're putting the current thread into the background, check the TLS
272    // to make sure this thread isn't guarded.  If it is, raise an exception.
273    if (pri >= ANDROID_PRIORITY_BACKGROUND) {
274        if (pid == androidGetTid()) {
275            void* bgOk = pthread_getspecific(gBgKey);
276            if (bgOk == ((void*)0xbaad)) {
277                LOGE("Thread marked fg-only put self in background!");
278                jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
279                return;
280            }
281        }
282    }
283#endif
284
285    int rc = androidSetThreadPriority(pid, pri);
286    if (rc != 0) {
287        if (rc == INVALID_OPERATION) {
288            signalExceptionForPriorityError(env, clazz, errno);
289        } else {
290            signalExceptionForGroupError(env, clazz, errno);
291        }
292    }
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        }
330        return true;
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        jniThrowNullPointerException(env, 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        jniThrowNullPointerException(env, 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                jniThrowNullPointerException(env, "Element in reqFields");
468                return;
469            }
470            fields.add(String8(str8));
471            env->ReleaseStringUTFChars((jstring)obj, str8);
472        } else {
473            jniThrowNullPointerException(env, "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        jniThrowNullPointerException(env, 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        jniThrowNullPointerException(env, 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        jniThrowNullPointerException(env, 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
815void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
816{
817    if (pid > 0) {
818        kill(pid, sig);
819    }
820}
821
822static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
823{
824    struct timespec ts;
825
826    int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
827
828    if (res != 0) {
829        return (jlong) 0;
830    }
831
832    nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
833    return (jlong) nanoseconds_to_milliseconds(when);
834}
835
836static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
837{
838    char filename[64];
839
840    snprintf(filename, sizeof(filename), "/proc/%d/smaps", pid);
841
842    FILE * file = fopen(filename, "r");
843    if (!file) {
844        return (jlong) -1;
845    }
846
847    // Tally up all of the Pss from the various maps
848    char line[256];
849    jlong pss = 0;
850    while (fgets(line, sizeof(line), file)) {
851        jlong v;
852        if (sscanf(line, "Pss: %lld kB", &v) == 1) {
853            pss += v;
854        }
855    }
856
857    fclose(file);
858
859    // Return the Pss value in bytes, not kilobytes
860    return pss * 1024;
861}
862
863static const JNINativeMethod methods[] = {
864    {"myPid",       "()I", (void*)android_os_Process_myPid},
865    {"myTid",       "()I", (void*)android_os_Process_myTid},
866    {"myUid",       "()I", (void*)android_os_Process_myUid},
867    {"getUidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
868    {"getGidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
869    {"setThreadPriority",   "(II)V", (void*)android_os_Process_setThreadPriority},
870    {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
871    {"setThreadPriority",   "(I)V", (void*)android_os_Process_setCallingThreadPriority},
872    {"getThreadPriority",   "(I)I", (void*)android_os_Process_getThreadPriority},
873    {"setThreadGroup",      "(II)V", (void*)android_os_Process_setThreadGroup},
874    {"setProcessGroup",      "(II)V", (void*)android_os_Process_setProcessGroup},
875    {"setOomAdj",   "(II)Z", (void*)android_os_Process_setOomAdj},
876    {"setArgV0",    "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
877    {"setUid", "(I)I", (void*)android_os_Process_setUid},
878    {"setGid", "(I)I", (void*)android_os_Process_setGid},
879    {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
880    {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
881    {"supportsProcesses", "()Z", (void*)android_os_Process_supportsProcesses},
882    {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
883    {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
884    {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
885    {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
886    {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
887    {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
888    {"getPss", "(I)J", (void*)android_os_Process_getPss},
889    //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
890};
891
892const char* const kProcessPathName = "android/os/Process";
893
894int register_android_os_Process(JNIEnv* env)
895{
896    return AndroidRuntime::registerNativeMethods(
897        env, kProcessPathName,
898        methods, NELEM(methods));
899}
900