android_util_Process.cpp revision 3b1e22e2898e27fe486ac4137692e0f20166e13e
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 GUARD_THREAD_PRIORITY 0
47
48using namespace android;
49
50static const bool kDebugPolicy = false;
51static const bool kDebugProc = false;
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    char proc_path[255];
179    struct dirent *de;
180
181    if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
182        signalExceptionForGroupError(env, EINVAL);
183        return;
184    }
185
186    bool isDefault = false;
187    if (grp < 0) {
188        grp = SP_FOREGROUND;
189        isDefault = true;
190    }
191    SchedPolicy sp = (SchedPolicy) grp;
192
193    if (kDebugPolicy) {
194        char cmdline[32];
195        int fd;
196
197        strcpy(cmdline, "unknown");
198
199        sprintf(proc_path, "/proc/%d/cmdline", pid);
200        fd = open(proc_path, O_RDONLY);
201        if (fd >= 0) {
202            int rc = read(fd, cmdline, sizeof(cmdline)-1);
203            cmdline[rc] = 0;
204            close(fd);
205        }
206
207        if (sp == SP_BACKGROUND) {
208            ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
209        } else {
210            ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
211        }
212    }
213
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            if (kDebugProc) {
733                ALOGW("Ran off end of data @%d", i);
734            }
735            res = JNI_FALSE;
736            break;
737        }
738
739        jsize end = -1;
740        if ((mode&PROC_PARENS) != 0) {
741            while (i < endIndex && buffer[i] != ')') {
742                i++;
743            }
744            end = i;
745            i++;
746        } else if ((mode&PROC_QUOTES) != 0) {
747            while (buffer[i] != '"' && i < endIndex) {
748                i++;
749            }
750            end = i;
751            i++;
752        }
753        while (i < endIndex && buffer[i] != term) {
754            i++;
755        }
756        if (end < 0) {
757            end = i;
758        }
759
760        if (i < endIndex) {
761            i++;
762            if ((mode&PROC_COMBINE) != 0) {
763                while (i < endIndex && buffer[i] == term) {
764                    i++;
765                }
766            }
767        }
768
769        //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
770
771        if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
772            char c = buffer[end];
773            buffer[end] = 0;
774            if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
775                char* end;
776                floatsData[di] = strtof(buffer+start, &end);
777            }
778            if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
779                char* end;
780                longsData[di] = strtoll(buffer+start, &end, 10);
781            }
782            if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
783                jstring str = env->NewStringUTF(buffer+start);
784                env->SetObjectArrayElement(outStrings, di, str);
785            }
786            buffer[end] = c;
787            di++;
788        }
789    }
790
791    env->ReleaseIntArrayElements(format, formatData, 0);
792    if (longsData != NULL) {
793        env->ReleaseLongArrayElements(outLongs, longsData, 0);
794    }
795    if (floatsData != NULL) {
796        env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
797    }
798
799    return res;
800}
801
802jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
803        jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
804        jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
805{
806        jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
807
808        jboolean result = android_os_Process_parseProcLineArray(env, clazz,
809                (char*) bufferArray, startIndex, endIndex, format, outStrings,
810                outLongs, outFloats);
811
812        env->ReleaseByteArrayElements(buffer, bufferArray, 0);
813
814        return result;
815}
816
817jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
818        jstring file, jintArray format, jobjectArray outStrings,
819        jlongArray outLongs, jfloatArray outFloats)
820{
821    if (file == NULL || format == NULL) {
822        jniThrowNullPointerException(env, NULL);
823        return JNI_FALSE;
824    }
825
826    const char* file8 = env->GetStringUTFChars(file, NULL);
827    if (file8 == NULL) {
828        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
829        return JNI_FALSE;
830    }
831    int fd = open(file8, O_RDONLY);
832
833    if (fd < 0) {
834        if (kDebugProc) {
835            ALOGW("Unable to open process file: %s\n", file8);
836        }
837        env->ReleaseStringUTFChars(file, file8);
838        return JNI_FALSE;
839    }
840    env->ReleaseStringUTFChars(file, file8);
841
842    char buffer[256];
843    const int len = read(fd, buffer, sizeof(buffer)-1);
844    close(fd);
845
846    if (len < 0) {
847        if (kDebugProc) {
848            ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
849        }
850        return JNI_FALSE;
851    }
852    buffer[len] = 0;
853
854    return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
855            format, outStrings, outLongs, outFloats);
856
857}
858
859void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
860                                             jobject binderObject)
861{
862    if (binderObject == NULL) {
863        jniThrowNullPointerException(env, NULL);
864        return;
865    }
866
867    sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
868}
869
870void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
871{
872    if (pid > 0) {
873        ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
874        kill(pid, sig);
875    }
876}
877
878void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
879{
880    if (pid > 0) {
881        kill(pid, sig);
882    }
883}
884
885static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
886{
887    struct timespec ts;
888
889    int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
890
891    if (res != 0) {
892        return (jlong) 0;
893    }
894
895    nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
896    return (jlong) nanoseconds_to_milliseconds(when);
897}
898
899static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
900{
901    char filename[64];
902
903    snprintf(filename, sizeof(filename), "/proc/%" PRId32 "/smaps", pid);
904
905    FILE * file = fopen(filename, "r");
906    if (!file) {
907        return (jlong) -1;
908    }
909
910    // Tally up all of the Pss from the various maps
911    char line[256];
912    jlong pss = 0;
913    while (fgets(line, sizeof(line), file)) {
914        jlong v;
915        if (sscanf(line, "Pss: %" SCNd64 " kB", &v) == 1) {
916            pss += v;
917        }
918    }
919
920    fclose(file);
921
922    // Return the Pss value in bytes, not kilobytes
923    return pss * 1024;
924}
925
926jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
927        jobjectArray commandNames)
928{
929    if (commandNames == NULL) {
930        jniThrowNullPointerException(env, NULL);
931        return NULL;
932    }
933
934    Vector<String8> commands;
935
936    jsize count = env->GetArrayLength(commandNames);
937
938    for (int i=0; i<count; i++) {
939        jobject obj = env->GetObjectArrayElement(commandNames, i);
940        if (obj != NULL) {
941            const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
942            if (str8 == NULL) {
943                jniThrowNullPointerException(env, "Element in commandNames");
944                return NULL;
945            }
946            commands.add(String8(str8));
947            env->ReleaseStringUTFChars((jstring)obj, str8);
948        } else {
949            jniThrowNullPointerException(env, "Element in commandNames");
950            return NULL;
951        }
952    }
953
954    Vector<jint> pids;
955
956    DIR *proc = opendir("/proc");
957    if (proc == NULL) {
958        fprintf(stderr, "/proc: %s\n", strerror(errno));
959        return NULL;
960    }
961
962    struct dirent *d;
963    while ((d = readdir(proc))) {
964        int pid = atoi(d->d_name);
965        if (pid <= 0) continue;
966
967        char path[PATH_MAX];
968        char data[PATH_MAX];
969        snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
970
971        int fd = open(path, O_RDONLY);
972        if (fd < 0) {
973            continue;
974        }
975        const int len = read(fd, data, sizeof(data)-1);
976        close(fd);
977
978        if (len < 0) {
979            continue;
980        }
981        data[len] = 0;
982
983        for (int i=0; i<len; i++) {
984            if (data[i] == ' ') {
985                data[i] = 0;
986                break;
987            }
988        }
989
990        for (size_t i=0; i<commands.size(); i++) {
991            if (commands[i] == data) {
992                pids.add(pid);
993                break;
994            }
995        }
996    }
997
998    closedir(proc);
999
1000    jintArray pidArray = env->NewIntArray(pids.size());
1001    if (pidArray == NULL) {
1002        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1003        return NULL;
1004    }
1005
1006    if (pids.size() > 0) {
1007        env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
1008    }
1009
1010    return pidArray;
1011}
1012
1013jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
1014{
1015    return killProcessGroup(uid, pid, SIGKILL);
1016}
1017
1018void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
1019{
1020    return removeAllProcessGroups();
1021}
1022
1023static const JNINativeMethod methods[] = {
1024    {"getUidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
1025    {"getGidForName",       "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
1026    {"setThreadPriority",   "(II)V", (void*)android_os_Process_setThreadPriority},
1027    {"setThreadScheduler",  "(III)V", (void*)android_os_Process_setThreadScheduler},
1028    {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
1029    {"setThreadPriority",   "(I)V", (void*)android_os_Process_setCallingThreadPriority},
1030    {"getThreadPriority",   "(I)I", (void*)android_os_Process_getThreadPriority},
1031    {"setThreadGroup",      "(II)V", (void*)android_os_Process_setThreadGroup},
1032    {"setProcessGroup",     "(II)V", (void*)android_os_Process_setProcessGroup},
1033    {"getProcessGroup",     "(I)I", (void*)android_os_Process_getProcessGroup},
1034    {"setSwappiness",   "(IZ)Z", (void*)android_os_Process_setSwappiness},
1035    {"setArgV0",    "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
1036    {"setUid", "(I)I", (void*)android_os_Process_setUid},
1037    {"setGid", "(I)I", (void*)android_os_Process_setGid},
1038    {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
1039    {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
1040    {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
1041    {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
1042    {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
1043    {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
1044    {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
1045    {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
1046    {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
1047    {"getPss", "(I)J", (void*)android_os_Process_getPss},
1048    {"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
1049    //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
1050    {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
1051    {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
1052};
1053
1054const char* const kProcessPathName = "android/os/Process";
1055
1056int register_android_os_Process(JNIEnv* env)
1057{
1058    return AndroidRuntime::registerNativeMethods(
1059        env, kProcessPathName,
1060        methods, NELEM(methods));
1061}
1062