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