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