android_util_Process.cpp revision a7f656206550dea94e51dd8c9bb2dd8734bcdf92
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, 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, 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, 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, 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        ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
209    } else {
210        ALOGD("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, 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            ALOGE("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, 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    ALOGV("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_setThreadScheduler(JNIEnv* env, jclass clazz,
268                                              jint tid, jint policy, jint pri)
269{
270    struct sched_param param;
271    param.sched_priority = pri;
272    int rc = sched_setscheduler(tid, policy, &param);
273    if (rc) {
274        signalExceptionForPriorityError(env, errno);
275    }
276}
277
278void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
279                                              jint pid, jint pri)
280{
281#if GUARD_THREAD_PRIORITY
282    // if we're putting the current thread into the background, check the TLS
283    // to make sure this thread isn't guarded.  If it is, raise an exception.
284    if (pri >= ANDROID_PRIORITY_BACKGROUND) {
285        if (pid == androidGetTid()) {
286            void* bgOk = pthread_getspecific(gBgKey);
287            if (bgOk == ((void*)0xbaad)) {
288                ALOGE("Thread marked fg-only put self in background!");
289                jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
290                return;
291            }
292        }
293    }
294#endif
295
296    int rc = androidSetThreadPriority(pid, pri);
297    if (rc != 0) {
298        if (rc == INVALID_OPERATION) {
299            signalExceptionForPriorityError(env, errno);
300        } else {
301            signalExceptionForGroupError(env, errno);
302        }
303    }
304
305    //ALOGI("Setting priority of %d: %d, getpriority returns %d\n",
306    //     pid, pri, getpriority(PRIO_PROCESS, pid));
307}
308
309void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
310                                                        jint pri)
311{
312    jint tid = android_os_Process_myTid(env, clazz);
313    android_os_Process_setThreadPriority(env, clazz, tid, pri);
314}
315
316jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
317                                              jint pid)
318{
319    errno = 0;
320    jint pri = getpriority(PRIO_PROCESS, pid);
321    if (errno != 0) {
322        signalExceptionForPriorityError(env, errno);
323    }
324    //ALOGI("Returning priority of %d: %d\n", pid, pri);
325    return pri;
326}
327
328jboolean android_os_Process_setOomAdj(JNIEnv* env, jobject clazz,
329                                      jint pid, jint adj)
330{
331#ifdef HAVE_OOM_ADJ
332    char text[64];
333    sprintf(text, "/proc/%d/oom_adj", pid);
334    int fd = open(text, O_WRONLY);
335    if (fd >= 0) {
336        sprintf(text, "%d", adj);
337        write(fd, text, strlen(text));
338        close(fd);
339    }
340    return true;
341#endif
342    return false;
343}
344
345void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
346{
347    if (name == NULL) {
348        jniThrowNullPointerException(env, NULL);
349        return;
350    }
351
352    const jchar* str = env->GetStringCritical(name, 0);
353    String8 name8;
354    if (str) {
355        name8 = String8(str, env->GetStringLength(name));
356        env->ReleaseStringCritical(name, str);
357    }
358
359    if (name8.size() > 0) {
360        ProcessState::self()->setArgV0(name8.string());
361    }
362}
363
364jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
365{
366    return setuid(uid) == 0 ? 0 : errno;
367}
368
369jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
370{
371    return setgid(uid) == 0 ? 0 : errno;
372}
373
374static int pid_compare(const void* v1, const void* v2)
375{
376    //ALOGI("Compare %d vs %d\n", *((const jint*)v1), *((const jint*)v2));
377    return *((const jint*)v1) - *((const jint*)v2);
378}
379
380static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
381{
382    int fd = open("/proc/meminfo", O_RDONLY);
383
384    if (fd < 0) {
385        ALOGW("Unable to open /proc/meminfo");
386        return -1;
387    }
388
389    char buffer[256];
390    const int len = read(fd, buffer, sizeof(buffer)-1);
391    close(fd);
392
393    if (len < 0) {
394        ALOGW("Unable to read /proc/meminfo");
395        return -1;
396    }
397    buffer[len] = 0;
398
399    int numFound = 0;
400    jlong mem = 0;
401
402    static const char* const sums[] = { "MemFree:", "Cached:", NULL };
403    static const int sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 };
404
405    char* p = buffer;
406    while (*p && numFound < 2) {
407        int i = 0;
408        while (sums[i]) {
409            if (strncmp(p, sums[i], sumsLen[i]) == 0) {
410                p += sumsLen[i];
411                while (*p == ' ') p++;
412                char* num = p;
413                while (*p >= '0' && *p <= '9') p++;
414                if (*p != 0) {
415                    *p = 0;
416                    p++;
417                    if (*p == 0) p--;
418                }
419                mem += atoll(num) * 1024;
420                numFound++;
421                break;
422            }
423            i++;
424        }
425        p++;
426    }
427
428    return numFound > 0 ? mem : -1;
429}
430
431void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
432                                      jobjectArray reqFields, jlongArray outFields)
433{
434    //ALOGI("getMemInfo: %p %p", reqFields, outFields);
435
436    if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
437        jniThrowNullPointerException(env, NULL);
438        return;
439    }
440
441    const char* file8 = env->GetStringUTFChars(fileStr, NULL);
442    if (file8 == NULL) {
443        return;
444    }
445    String8 file(file8);
446    env->ReleaseStringUTFChars(fileStr, file8);
447
448    jsize count = env->GetArrayLength(reqFields);
449    if (count > env->GetArrayLength(outFields)) {
450        jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
451        return;
452    }
453
454    Vector<String8> fields;
455    int i;
456
457    for (i=0; i<count; i++) {
458        jobject obj = env->GetObjectArrayElement(reqFields, i);
459        if (obj != NULL) {
460            const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
461            //ALOGI("String at %d: %p = %s", i, obj, str8);
462            if (str8 == NULL) {
463                jniThrowNullPointerException(env, "Element in reqFields");
464                return;
465            }
466            fields.add(String8(str8));
467            env->ReleaseStringUTFChars((jstring)obj, str8);
468        } else {
469            jniThrowNullPointerException(env, "Element in reqFields");
470            return;
471        }
472    }
473
474    jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
475    if (sizesArray == NULL) {
476        return;
477    }
478
479    //ALOGI("Clearing %d sizes", count);
480    for (i=0; i<count; i++) {
481        sizesArray[i] = 0;
482    }
483
484    int fd = open(file.string(), O_RDONLY);
485
486    if (fd >= 0) {
487        const size_t BUFFER_SIZE = 2048;
488        char* buffer = (char*)malloc(BUFFER_SIZE);
489        int len = read(fd, buffer, BUFFER_SIZE-1);
490        close(fd);
491
492        if (len < 0) {
493            ALOGW("Unable to read %s", file.string());
494            len = 0;
495        }
496        buffer[len] = 0;
497
498        int foundCount = 0;
499
500        char* p = buffer;
501        while (*p && foundCount < count) {
502            bool skipToEol = true;
503            //ALOGI("Parsing at: %s", p);
504            for (i=0; i<count; i++) {
505                const String8& field = fields[i];
506                if (strncmp(p, field.string(), field.length()) == 0) {
507                    p += field.length();
508                    while (*p == ' ' || *p == '\t') p++;
509                    char* num = p;
510                    while (*p >= '0' && *p <= '9') p++;
511                    skipToEol = *p != '\n';
512                    if (*p != 0) {
513                        *p = 0;
514                        p++;
515                    }
516                    char* end;
517                    sizesArray[i] = strtoll(num, &end, 10);
518                    //ALOGI("Field %s = %d", field.string(), sizesArray[i]);
519                    foundCount++;
520                    break;
521                }
522            }
523            if (skipToEol) {
524                while (*p && *p != '\n') {
525                    p++;
526                }
527                if (*p == '\n') {
528                    p++;
529                }
530            }
531        }
532
533        free(buffer);
534    } else {
535        ALOGW("Unable to open %s", file.string());
536    }
537
538    //ALOGI("Done!");
539    env->ReleaseLongArrayElements(outFields, sizesArray, 0);
540}
541
542jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
543                                     jstring file, jintArray lastArray)
544{
545    if (file == NULL) {
546        jniThrowNullPointerException(env, NULL);
547        return NULL;
548    }
549
550    const char* file8 = env->GetStringUTFChars(file, NULL);
551    if (file8 == NULL) {
552        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
553        return NULL;
554    }
555
556    DIR* dirp = opendir(file8);
557
558    env->ReleaseStringUTFChars(file, file8);
559
560    if(dirp == NULL) {
561        return NULL;
562    }
563
564    jsize curCount = 0;
565    jint* curData = NULL;
566    if (lastArray != NULL) {
567        curCount = env->GetArrayLength(lastArray);
568        curData = env->GetIntArrayElements(lastArray, 0);
569    }
570
571    jint curPos = 0;
572
573    struct dirent* entry;
574    while ((entry=readdir(dirp)) != NULL) {
575        const char* p = entry->d_name;
576        while (*p) {
577            if (*p < '0' || *p > '9') break;
578            p++;
579        }
580        if (*p != 0) continue;
581
582        char* end;
583        int pid = strtol(entry->d_name, &end, 10);
584        //ALOGI("File %s pid=%d\n", entry->d_name, pid);
585        if (curPos >= curCount) {
586            jsize newCount = (curCount == 0) ? 10 : (curCount*2);
587            jintArray newArray = env->NewIntArray(newCount);
588            if (newArray == NULL) {
589                closedir(dirp);
590                jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
591                return NULL;
592            }
593            jint* newData = env->GetIntArrayElements(newArray, 0);
594            if (curData != NULL) {
595                memcpy(newData, curData, sizeof(jint)*curCount);
596                env->ReleaseIntArrayElements(lastArray, curData, 0);
597            }
598            lastArray = newArray;
599            curCount = newCount;
600            curData = newData;
601        }
602
603        curData[curPos] = pid;
604        curPos++;
605    }
606
607    closedir(dirp);
608
609    if (curData != NULL && curPos > 0) {
610        qsort(curData, curPos, sizeof(jint), pid_compare);
611    }
612
613    while (curPos < curCount) {
614        curData[curPos] = -1;
615        curPos++;
616    }
617
618    if (curData != NULL) {
619        env->ReleaseIntArrayElements(lastArray, curData, 0);
620    }
621
622    return lastArray;
623}
624
625enum {
626    PROC_TERM_MASK = 0xff,
627    PROC_ZERO_TERM = 0,
628    PROC_SPACE_TERM = ' ',
629    PROC_COMBINE = 0x100,
630    PROC_PARENS = 0x200,
631    PROC_OUT_STRING = 0x1000,
632    PROC_OUT_LONG = 0x2000,
633    PROC_OUT_FLOAT = 0x4000,
634};
635
636jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
637        char* buffer, jint startIndex, jint endIndex, jintArray format,
638        jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
639{
640
641    const jsize NF = env->GetArrayLength(format);
642    const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
643    const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
644    const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
645
646    jint* formatData = env->GetIntArrayElements(format, 0);
647    jlong* longsData = outLongs ?
648        env->GetLongArrayElements(outLongs, 0) : NULL;
649    jfloat* floatsData = outFloats ?
650        env->GetFloatArrayElements(outFloats, 0) : NULL;
651    if (formatData == NULL || (NL > 0 && longsData == NULL)
652            || (NR > 0 && floatsData == NULL)) {
653        if (formatData != NULL) {
654            env->ReleaseIntArrayElements(format, formatData, 0);
655        }
656        if (longsData != NULL) {
657            env->ReleaseLongArrayElements(outLongs, longsData, 0);
658        }
659        if (floatsData != NULL) {
660            env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
661        }
662        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
663        return JNI_FALSE;
664    }
665
666    jsize i = startIndex;
667    jsize di = 0;
668
669    jboolean res = JNI_TRUE;
670
671    for (jsize fi=0; fi<NF; fi++) {
672        const jint mode = formatData[fi];
673        if ((mode&PROC_PARENS) != 0) {
674            i++;
675        }
676        const char term = (char)(mode&PROC_TERM_MASK);
677        const jsize start = i;
678        if (i >= endIndex) {
679            res = JNI_FALSE;
680            break;
681        }
682
683        jsize end = -1;
684        if ((mode&PROC_PARENS) != 0) {
685            while (buffer[i] != ')' && i < endIndex) {
686                i++;
687            }
688            end = i;
689            i++;
690        }
691        while (buffer[i] != term && i < endIndex) {
692            i++;
693        }
694        if (end < 0) {
695            end = i;
696        }
697
698        if (i < endIndex) {
699            i++;
700            if ((mode&PROC_COMBINE) != 0) {
701                while (buffer[i] == term && i < endIndex) {
702                    i++;
703                }
704            }
705        }
706
707        //ALOGI("Field %d: %d-%d dest=%d mode=0x%x\n", i, start, end, di, mode);
708
709        if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
710            char c = buffer[end];
711            buffer[end] = 0;
712            if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
713                char* end;
714                floatsData[di] = strtof(buffer+start, &end);
715            }
716            if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
717                char* end;
718                longsData[di] = strtoll(buffer+start, &end, 10);
719            }
720            if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
721                jstring str = env->NewStringUTF(buffer+start);
722                env->SetObjectArrayElement(outStrings, di, str);
723            }
724            buffer[end] = c;
725            di++;
726        }
727    }
728
729    env->ReleaseIntArrayElements(format, formatData, 0);
730    if (longsData != NULL) {
731        env->ReleaseLongArrayElements(outLongs, longsData, 0);
732    }
733    if (floatsData != NULL) {
734        env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
735    }
736
737    return res;
738}
739
740jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
741        jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
742        jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
743{
744        jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
745
746        jboolean result = android_os_Process_parseProcLineArray(env, clazz,
747                (char*) bufferArray, startIndex, endIndex, format, outStrings,
748                outLongs, outFloats);
749
750        env->ReleaseByteArrayElements(buffer, bufferArray, 0);
751
752        return result;
753}
754
755jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
756        jstring file, jintArray format, jobjectArray outStrings,
757        jlongArray outLongs, jfloatArray outFloats)
758{
759    if (file == NULL || format == NULL) {
760        jniThrowNullPointerException(env, NULL);
761        return JNI_FALSE;
762    }
763
764    const char* file8 = env->GetStringUTFChars(file, NULL);
765    if (file8 == NULL) {
766        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
767        return JNI_FALSE;
768    }
769    int fd = open(file8, O_RDONLY);
770    env->ReleaseStringUTFChars(file, file8);
771
772    if (fd < 0) {
773        //ALOGW("Unable to open process file: %s\n", file8);
774        return JNI_FALSE;
775    }
776
777    char buffer[256];
778    const int len = read(fd, buffer, sizeof(buffer)-1);
779    close(fd);
780
781    if (len < 0) {
782        //ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
783        return JNI_FALSE;
784    }
785    buffer[len] = 0;
786
787    return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
788            format, outStrings, outLongs, outFloats);
789
790}
791
792void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
793                                             jobject binderObject)
794{
795    if (binderObject == NULL) {
796        jniThrowNullPointerException(env, NULL);
797        return;
798    }
799
800    sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
801}
802
803void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
804{
805    if (pid > 0) {
806        ALOGI("Sending signal. PID: %d SIG: %d", pid, sig);
807        kill(pid, sig);
808    }
809}
810
811void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
812{
813    if (pid > 0) {
814        kill(pid, sig);
815    }
816}
817
818static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
819{
820    struct timespec ts;
821
822    int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
823
824    if (res != 0) {
825        return (jlong) 0;
826    }
827
828    nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
829    return (jlong) nanoseconds_to_milliseconds(when);
830}
831
832static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
833{
834    char filename[64];
835
836    snprintf(filename, sizeof(filename), "/proc/%d/smaps", pid);
837
838    FILE * file = fopen(filename, "r");
839    if (!file) {
840        return (jlong) -1;
841    }
842
843    // Tally up all of the Pss from the various maps
844    char line[256];
845    jlong pss = 0;
846    while (fgets(line, sizeof(line), file)) {
847        jlong v;
848        if (sscanf(line, "Pss: %lld kB", &v) == 1) {
849            pss += v;
850        }
851    }
852
853    fclose(file);
854
855    // Return the Pss value in bytes, not kilobytes
856    return pss * 1024;
857}
858
859static const JNINativeMethod methods[] = {
860    {"myPid",       "()I", (void*)android_os_Process_myPid},
861    {"myTid",       "()I", (void*)android_os_Process_myTid},
862    {"myUid",       "()I", (void*)android_os_Process_myUid},
863    {"getUidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
864    {"getGidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
865    {"setThreadPriority",   "(II)V", (void*)android_os_Process_setThreadPriority},
866    {"setThreadScheduler",  "(III)V", (void*)android_os_Process_setThreadScheduler},
867    {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
868    {"setThreadPriority",   "(I)V", (void*)android_os_Process_setCallingThreadPriority},
869    {"getThreadPriority",   "(I)I", (void*)android_os_Process_getThreadPriority},
870    {"setThreadGroup",      "(II)V", (void*)android_os_Process_setThreadGroup},
871    {"setProcessGroup",      "(II)V", (void*)android_os_Process_setProcessGroup},
872    {"setOomAdj",   "(II)Z", (void*)android_os_Process_setOomAdj},
873    {"setArgV0",    "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
874    {"setUid", "(I)I", (void*)android_os_Process_setUid},
875    {"setGid", "(I)I", (void*)android_os_Process_setGid},
876    {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
877    {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
878    {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
879    {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
880    {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
881    {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
882    {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
883    {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
884    {"getPss", "(I)J", (void*)android_os_Process_getPss},
885    //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
886};
887
888const char* const kProcessPathName = "android/os/Process";
889
890int register_android_os_Process(JNIEnv* env)
891{
892    return AndroidRuntime::registerNativeMethods(
893        env, kProcessPathName,
894        methods, NELEM(methods));
895}
896