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