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