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