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