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