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