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