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