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