• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_getSchedAffinity(JNIEnv * env,jobject clazz,jint pid)493 jlongArray android_os_Process_getSchedAffinity(JNIEnv* env, jobject clazz, jint pid) {
494     // sched_getaffinity will do memset 0 for the unset bits within set_alloc_size_byte
495     cpu_set_t cpu_set;
496     if (sched_getaffinity(pid, sizeof(cpu_set_t), &cpu_set) != 0) {
497         signalExceptionForError(env, errno, pid);
498         return nullptr;
499     }
500     int cpu_cnt = std::min(CPU_SETSIZE, get_nprocs_conf());
501     int masks_len = (int)(CPU_ALLOC_SIZE(cpu_cnt) / sizeof(__CPU_BITTYPE));
502     jlongArray masks = env->NewLongArray(masks_len);
503     if (masks == nullptr) {
504         jniThrowException(env, "java/lang/OutOfMemoryError", nullptr);
505         return nullptr;
506     }
507     jlong* mask_elements = env->GetLongArrayElements(masks, 0);
508     for (int i = 0; i < masks_len; i++) {
509         mask_elements[i] = cpu_set.__bits[i];
510     }
511     env->ReleaseLongArrayElements(masks, mask_elements, 0);
512     return masks;
513 }
514 
android_os_Process_setCanSelfBackground(JNIEnv * env,jobject clazz,jboolean bgOk)515 static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
516     // Establishes the calling thread as illegal to put into the background.
517     // Typically used only for the system process's main looper.
518 #if GUARD_THREAD_PRIORITY
519     ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
520     {
521         Mutex::Autolock _l(gKeyCreateMutex);
522         if (gBgKey == -1) {
523             pthread_key_create(&gBgKey, NULL);
524         }
525     }
526 
527     // inverted:  not-okay, we set a sentinel value
528     pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
529 #endif
530 }
531 
android_os_Process_getThreadScheduler(JNIEnv * env,jclass clazz,jint tid)532 jint android_os_Process_getThreadScheduler(JNIEnv* env, jclass clazz,
533                                               jint tid)
534 {
535     int policy = 0;
536 // linux has sched_getscheduler(), others don't.
537 #if defined(__linux__)
538     errno = 0;
539     policy = sched_getscheduler(tid);
540     if (errno != 0) {
541         signalExceptionForPriorityError(env, errno, tid);
542     }
543 #else
544     signalExceptionForPriorityError(env, ENOSYS, tid);
545 #endif
546     return policy;
547 }
548 
android_os_Process_setThreadScheduler(JNIEnv * env,jclass clazz,jint tid,jint policy,jint pri)549 void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
550                                               jint tid, jint policy, jint pri)
551 {
552 // linux has sched_setscheduler(), others don't.
553 #if defined(__linux__)
554     struct sched_param param;
555     param.sched_priority = pri;
556     int rc = sched_setscheduler(tid, policy, &param);
557     if (rc) {
558         signalExceptionForPriorityError(env, errno, tid);
559     }
560 #else
561     signalExceptionForPriorityError(env, ENOSYS, tid);
562 #endif
563 }
564 
android_os_Process_setThreadPriority(JNIEnv * env,jobject clazz,jint pid,jint pri)565 void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
566                                               jint pid, jint pri)
567 {
568 #if GUARD_THREAD_PRIORITY
569     // if we're putting the current thread into the background, check the TLS
570     // to make sure this thread isn't guarded.  If it is, raise an exception.
571     if (pri >= ANDROID_PRIORITY_BACKGROUND) {
572         if (pid == gettid()) {
573             void* bgOk = pthread_getspecific(gBgKey);
574             if (bgOk == ((void*)0xbaad)) {
575                 ALOGE("Thread marked fg-only put self in background!");
576                 jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
577                 return;
578             }
579         }
580     }
581 #endif
582 
583     int rc = androidSetThreadPriority(pid, pri);
584     if (rc != 0) {
585         if (rc == INVALID_OPERATION) {
586             signalExceptionForPriorityError(env, errno, pid);
587         } else {
588             signalExceptionForGroupError(env, errno, pid);
589         }
590     }
591 
592     //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
593     //     pid, pri, getpriority(PRIO_PROCESS, pid));
594 }
595 
android_os_Process_setCallingThreadPriority(JNIEnv * env,jobject clazz,jint pri)596 void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
597                                                         jint pri)
598 {
599     android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
600 }
601 
android_os_Process_getThreadPriority(JNIEnv * env,jobject clazz,jint pid)602 jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
603                                               jint pid)
604 {
605     errno = 0;
606     jint pri = getpriority(PRIO_PROCESS, pid);
607     if (errno != 0) {
608         signalExceptionForPriorityError(env, errno, pid);
609     }
610     //ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
611     return pri;
612 }
613 
android_os_Process_setArgV0(JNIEnv * env,jobject clazz,jstring name)614 void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
615 {
616     if (name == NULL) {
617         jniThrowNullPointerException(env, NULL);
618         return;
619     }
620 
621     const jchar* str = env->GetStringCritical(name, 0);
622     String8 name8;
623     if (str) {
624         name8 = String8(reinterpret_cast<const char16_t*>(str),
625                         env->GetStringLength(name));
626         env->ReleaseStringCritical(name, str);
627     }
628 
629     if (!name8.empty()) {
630         AndroidRuntime::getRuntime()->setArgv0(name8.c_str(), true /* setProcName */);
631     }
632 }
633 
android_os_Process_setUid(JNIEnv * env,jobject clazz,jint uid)634 jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
635 {
636     if (uid < 0) {
637         return jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
638                                     "uid is negative: %d", uid);
639     }
640 
641     return setuid(uid) == 0 ? 0 : errno;
642 }
643 
android_os_Process_setGid(JNIEnv * env,jobject clazz,jint gid)644 jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint gid) {
645     if (gid < 0) {
646         return jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
647                                     "gid is negative: %d", gid);
648     }
649 
650     return setgid(gid) == 0 ? 0 : errno;
651 }
652 
pid_compare(const void * v1,const void * v2)653 static int pid_compare(const void* v1, const void* v2)
654 {
655     //ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
656     return *((const jint*)v1) - *((const jint*)v2);
657 }
658 
android_os_Process_getFreeMemory(JNIEnv * env,jobject clazz)659 static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
660 {
661     std::array<std::string_view, 1> memFreeTags = {
662             ::android::meminfo::SysMemInfo::kMemAvailable,
663     };
664     std::vector<uint64_t> mem(memFreeTags.size());
665     ::android::meminfo::SysMemInfo smi;
666 
667     if (!smi.ReadMemInfo(memFreeTags.size(),
668                          memFreeTags.data(),
669                          mem.data())) {
670         jniThrowRuntimeException(env, "SysMemInfo read failed to get Free Memory");
671         return -1L;
672     }
673 
674     jlong sum = 0;
675     std::for_each(mem.begin(), mem.end(), [&](uint64_t val) { sum += val; });
676     return sum * 1024;
677 }
678 
android_os_Process_getTotalMemory(JNIEnv * env,jobject clazz)679 static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
680 {
681     struct sysinfo si;
682     if (sysinfo(&si) == -1) {
683         ALOGE("sysinfo failed: %s", strerror(errno));
684         return -1;
685     }
686 
687     return static_cast<jlong>(si.totalram) * si.mem_unit;
688 }
689 
690 /*
691  * The outFields array is initialized to -1 to allow the caller to identify
692  * when the status file (and therefore the process) they specified is invalid.
693  * This array should not be overwritten or cleared before we know that the
694  * status file can be read.
695  */
android_os_Process_readProcLines(JNIEnv * env,jobject clazz,jstring fileStr,jobjectArray reqFields,jlongArray outFields)696 void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
697                                       jobjectArray reqFields, jlongArray outFields)
698 {
699     //ALOGI("getMemInfo: %p %p", reqFields, outFields);
700 
701     if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
702         jniThrowNullPointerException(env, NULL);
703         return;
704     }
705 
706     const char* file8 = env->GetStringUTFChars(fileStr, NULL);
707     if (file8 == NULL) {
708         return;
709     }
710     String8 file(file8);
711     env->ReleaseStringUTFChars(fileStr, file8);
712 
713     jsize count = env->GetArrayLength(reqFields);
714     if (count > env->GetArrayLength(outFields)) {
715         jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
716         return;
717     }
718 
719     Vector<String8> fields;
720     int i;
721 
722     for (i=0; i<count; i++) {
723         jobject obj = env->GetObjectArrayElement(reqFields, i);
724         if (obj != NULL) {
725             const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
726             //ALOGI("String at %d: %p = %s", i, obj, str8);
727             if (str8 == NULL) {
728                 jniThrowNullPointerException(env, "Element in reqFields");
729                 return;
730             }
731             fields.add(String8(str8));
732             env->ReleaseStringUTFChars((jstring)obj, str8);
733         } else {
734             jniThrowNullPointerException(env, "Element in reqFields");
735             return;
736         }
737     }
738 
739     jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
740     if (sizesArray == NULL) {
741         return;
742     }
743 
744     int fd = open(file.c_str(), O_RDONLY | O_CLOEXEC);
745 
746     if (fd >= 0) {
747         //ALOGI("Clearing %" PRId32 " sizes", count);
748         for (i=0; i<count; i++) {
749             sizesArray[i] = 0;
750         }
751 
752         const size_t BUFFER_SIZE = 4096;
753         char* buffer = (char*)malloc(BUFFER_SIZE);
754         int len = read(fd, buffer, BUFFER_SIZE-1);
755         close(fd);
756 
757         if (len < 0) {
758             ALOGW("Unable to read %s", file.c_str());
759             len = 0;
760         }
761         buffer[len] = 0;
762 
763         int foundCount = 0;
764 
765         char* p = buffer;
766         while (*p && foundCount < count) {
767             bool skipToEol = true;
768             //ALOGI("Parsing at: %s", p);
769             for (i=0; i<count; i++) {
770                 const String8& field = fields[i];
771                 if (strncmp(p, field.c_str(), field.length()) == 0) {
772                     p += field.length();
773                     while (*p == ' ' || *p == '\t') p++;
774                     char* num = p;
775                     while (*p >= '0' && *p <= '9') p++;
776                     skipToEol = *p != '\n';
777                     if (*p != 0) {
778                         *p = 0;
779                         p++;
780                     }
781                     char* end;
782                     sizesArray[i] = strtoll(num, &end, 10);
783                     // ALOGI("Field %s = %" PRId64, field.c_str(), sizesArray[i]);
784                     foundCount++;
785                     break;
786                 }
787             }
788             if (skipToEol) {
789                 while (*p && *p != '\n') {
790                     p++;
791                 }
792                 if (*p == '\n') {
793                     p++;
794                 }
795             }
796         }
797 
798         free(buffer);
799     } else {
800         ALOGW("Unable to open %s", file.c_str());
801     }
802 
803     //ALOGI("Done!");
804     env->ReleaseLongArrayElements(outFields, sizesArray, 0);
805 }
806 
android_os_Process_getPids(JNIEnv * env,jobject clazz,jstring file,jintArray lastArray)807 jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
808                                      jstring file, jintArray lastArray)
809 {
810     if (file == NULL) {
811         jniThrowNullPointerException(env, NULL);
812         return NULL;
813     }
814 
815     const char* file8 = env->GetStringUTFChars(file, NULL);
816     if (file8 == NULL) {
817         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
818         return NULL;
819     }
820 
821     DIR* dirp = opendir(file8);
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                 if (curData) env->ReleaseIntArrayElements(lastArray, curData, 0);
855                 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
856                 return NULL;
857             }
858             jint* newData = env->GetIntArrayElements(newArray, 0);
859             if (curData != NULL) {
860                 memcpy(newData, curData, sizeof(jint)*curCount);
861                 env->ReleaseIntArrayElements(lastArray, curData, 0);
862             }
863             lastArray = newArray;
864             curCount = newCount;
865             curData = newData;
866         }
867 
868         curData[curPos] = pid;
869         curPos++;
870     }
871 
872     closedir(dirp);
873 
874     if (curData != NULL && curPos > 0) {
875         qsort(curData, curPos, sizeof(jint), pid_compare);
876     }
877 
878     while (curPos < curCount) {
879         curData[curPos] = -1;
880         curPos++;
881     }
882 
883     if (curData != NULL) {
884         env->ReleaseIntArrayElements(lastArray, curData, 0);
885     }
886 
887     return lastArray;
888 }
889 
890 enum {
891     PROC_TERM_MASK = 0xff,
892     PROC_ZERO_TERM = 0,
893     PROC_SPACE_TERM = ' ',
894     PROC_COMBINE = 0x100,
895     PROC_PARENS = 0x200,
896     PROC_QUOTES = 0x400,
897     PROC_CHAR = 0x800,
898     PROC_OUT_STRING = 0x1000,
899     PROC_OUT_LONG = 0x2000,
900     PROC_OUT_FLOAT = 0x4000,
901 };
902 
android_os_Process_parseProcLineArray(JNIEnv * env,jobject clazz,char * buffer,jint startIndex,jint endIndex,jintArray format,jobjectArray outStrings,jlongArray outLongs,jfloatArray outFloats)903 jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
904         char* buffer, jint startIndex, jint endIndex, jintArray format,
905         jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
906 {
907 
908     const jsize NF = env->GetArrayLength(format);
909     const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
910     const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
911     const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
912 
913     jint* formatData = env->GetIntArrayElements(format, 0);
914     jlong* longsData = outLongs ?
915         env->GetLongArrayElements(outLongs, 0) : NULL;
916     jfloat* floatsData = outFloats ?
917         env->GetFloatArrayElements(outFloats, 0) : NULL;
918     if (formatData == NULL || (NL > 0 && longsData == NULL)
919             || (NR > 0 && floatsData == NULL)) {
920         if (formatData != NULL) {
921             env->ReleaseIntArrayElements(format, formatData, 0);
922         }
923         if (longsData != NULL) {
924             env->ReleaseLongArrayElements(outLongs, longsData, 0);
925         }
926         if (floatsData != NULL) {
927             env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
928         }
929         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
930         return JNI_FALSE;
931     }
932 
933     jsize i = startIndex;
934     jsize di = 0;
935 
936     jboolean res = JNI_TRUE;
937 
938     for (jsize fi=0; fi<NF; fi++) {
939         jint mode = formatData[fi];
940         if ((mode&PROC_PARENS) != 0) {
941             i++;
942         } else if ((mode&PROC_QUOTES) != 0) {
943             if (buffer[i] == '"') {
944                 i++;
945             } else {
946                 mode &= ~PROC_QUOTES;
947             }
948         }
949         const char term = (char)(mode&PROC_TERM_MASK);
950         const jsize start = i;
951         if (i >= endIndex) {
952             if (kDebugProc) {
953                 ALOGW("Ran off end of data @%d", i);
954             }
955             res = JNI_FALSE;
956             break;
957         }
958 
959         jsize end = -1;
960         if ((mode&PROC_PARENS) != 0) {
961             while (i < endIndex && buffer[i] != ')') {
962                 i++;
963             }
964             end = i;
965             i++;
966         } else if ((mode&PROC_QUOTES) != 0) {
967             while (i < endIndex && buffer[i] != '"') {
968                 i++;
969             }
970             end = i;
971             i++;
972         }
973         while (i < endIndex && buffer[i] != term) {
974             i++;
975         }
976         if (end < 0) {
977             end = i;
978         }
979 
980         if (i < endIndex) {
981             i++;
982             if ((mode&PROC_COMBINE) != 0) {
983                 while (i < endIndex && buffer[i] == term) {
984                     i++;
985                 }
986             }
987         }
988 
989         //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
990 
991         if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
992             char c = buffer[end];
993             buffer[end] = 0;
994             if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
995                 char* end;
996                 floatsData[di] = strtof(buffer+start, &end);
997             }
998             if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
999                 if ((mode&PROC_CHAR) != 0) {
1000                     // Caller wants single first character returned as one long.
1001                     longsData[di] = buffer[start];
1002                 } else {
1003                     char* end;
1004                     longsData[di] = strtoll(buffer+start, &end, 10);
1005                 }
1006             }
1007             if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
1008                 std::replace_if(buffer+start, buffer+end,
1009                                 [](unsigned char c){ return !std::isprint(c); }, '?');
1010                 jstring str = env->NewStringUTF(buffer+start);
1011                 env->SetObjectArrayElement(outStrings, di, str);
1012             }
1013             buffer[end] = c;
1014             di++;
1015         }
1016     }
1017 
1018     env->ReleaseIntArrayElements(format, formatData, 0);
1019     if (longsData != NULL) {
1020         env->ReleaseLongArrayElements(outLongs, longsData, 0);
1021     }
1022     if (floatsData != NULL) {
1023         env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
1024     }
1025 
1026     return res;
1027 }
1028 
android_os_Process_parseProcLine(JNIEnv * env,jobject clazz,jbyteArray buffer,jint startIndex,jint endIndex,jintArray format,jobjectArray outStrings,jlongArray outLongs,jfloatArray outFloats)1029 jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
1030         jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
1031         jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
1032 {
1033         jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
1034 
1035         jboolean result = android_os_Process_parseProcLineArray(env, clazz,
1036                 (char*) bufferArray, startIndex, endIndex, format, outStrings,
1037                 outLongs, outFloats);
1038 
1039         env->ReleaseByteArrayElements(buffer, bufferArray, 0);
1040 
1041         return result;
1042 }
1043 
android_os_Process_readProcFile(JNIEnv * env,jobject clazz,jstring file,jintArray format,jobjectArray outStrings,jlongArray outLongs,jfloatArray outFloats)1044 jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
1045         jstring file, jintArray format, jobjectArray outStrings,
1046         jlongArray outLongs, jfloatArray outFloats)
1047 {
1048     if (file == NULL || format == NULL) {
1049         jniThrowNullPointerException(env, NULL);
1050         return JNI_FALSE;
1051     }
1052 
1053     auto releaser = [&](const char* jniStr) { env->ReleaseStringUTFChars(file, jniStr); };
1054     std::unique_ptr<const char[], decltype(releaser)> file8(env->GetStringUTFChars(file, NULL),
1055                                                             releaser);
1056     if (!file8) {
1057         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1058         return JNI_FALSE;
1059     }
1060 
1061     ::android::base::unique_fd fd(open(file8.get(), O_RDONLY | O_CLOEXEC));
1062     if (!fd.ok()) {
1063         if (kDebugProc) {
1064             ALOGW("Unable to open process file: %s\n", file8.get());
1065         }
1066         return JNI_FALSE;
1067     }
1068 
1069     // Most proc files we read are small, so we go through the loop
1070     // with the stack buffer first. We allocate a buffer big enough
1071     // for most files.
1072 
1073     char stackBuf[kProcReadStackBufferSize];
1074     std::vector<char> heapBuf;
1075     char* buf = stackBuf;
1076 
1077     size_t remaining = sizeof(stackBuf);
1078     off_t offset = 0;
1079     ssize_t numBytesRead;
1080 
1081     do {
1082         numBytesRead = TEMP_FAILURE_RETRY(pread(fd, buf + offset, remaining, offset));
1083         if (numBytesRead < 0) {
1084             if (kDebugProc) {
1085                 ALOGW("Unable to read process file err: %s file: %s fd=%d\n",
1086                       strerror_r(errno, stackBuf, sizeof(stackBuf)), file8.get(), fd.get());
1087             }
1088             return JNI_FALSE;
1089         }
1090 
1091         offset += numBytesRead;
1092         remaining -= numBytesRead;
1093 
1094         if (numBytesRead && !remaining) {
1095             if (buf == stackBuf) {
1096                 heapBuf.resize(kProcReadMinHeapBufferSize);
1097                 static_assert(kProcReadMinHeapBufferSize > sizeof(stackBuf));
1098                 std::memcpy(heapBuf.data(), stackBuf, sizeof(stackBuf));
1099             } else {
1100                 constexpr size_t MAX_READABLE_PROCFILE_SIZE = 64 << 20;
1101                 if (heapBuf.size() >= MAX_READABLE_PROCFILE_SIZE) {
1102                     if (kDebugProc) {
1103                         ALOGW("Proc file too big: %s fd=%d size=%zu\n",
1104                               file8.get(), fd.get(), heapBuf.size());
1105                     }
1106                     return JNI_FALSE;
1107                 }
1108                 heapBuf.resize(2 * heapBuf.size());
1109             }
1110             buf = heapBuf.data();
1111             remaining = heapBuf.size() - offset;
1112         }
1113     } while (numBytesRead != 0);
1114 
1115     // parseProcLineArray below modifies the buffer while parsing!
1116     return android_os_Process_parseProcLineArray(
1117         env, clazz, buf, 0, offset, format, outStrings, outLongs, outFloats);
1118 }
1119 
android_os_Process_setApplicationObject(JNIEnv * env,jobject clazz,jobject binderObject)1120 void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
1121                                              jobject binderObject)
1122 {
1123     if (binderObject == NULL) {
1124         jniThrowNullPointerException(env, NULL);
1125         return;
1126     }
1127 
1128     sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
1129 }
1130 
android_os_Process_sendSignal(JNIEnv * env,jobject clazz,jint pid,jint sig)1131 void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
1132 {
1133     if (pid > 0) {
1134         ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
1135         kill(pid, sig);
1136     }
1137 }
1138 
android_os_Process_sendSignalQuiet(JNIEnv * env,jobject clazz,jint pid,jint sig)1139 void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
1140 {
1141     if (pid > 0) {
1142         kill(pid, sig);
1143     }
1144 }
1145 
android_os_Process_sendSignalThrows(JNIEnv * env,jobject clazz,jint pid,jint sig)1146 void android_os_Process_sendSignalThrows(JNIEnv* env, jobject clazz, jint pid, jint sig) {
1147     if (pid <= 0) {
1148         jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException", "Invalid argument: pid(%d)",
1149                              pid);
1150         return;
1151     }
1152     int ret = kill(pid, sig);
1153     if (ret < 0) {
1154         if (errno == ESRCH) {
1155             jniThrowExceptionFmt(env, "java/util/NoSuchElementException",
1156                                  "Process with pid %d not found", pid);
1157         } else {
1158             signalExceptionForError(env, errno, pid);
1159         }
1160     }
1161 }
1162 
android_os_Process_sendTgSignalThrows(JNIEnv * env,jobject clazz,jint tgid,jint tid,jint sig)1163 void android_os_Process_sendTgSignalThrows(JNIEnv* env, jobject clazz, jint tgid, jint tid,
1164                                            jint sig) {
1165     if (tgid <= 0 || tid <= 0) {
1166         jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
1167                              "Invalid argument: tgid(%d), tid(%d)", tid, tgid);
1168         return;
1169     }
1170     int ret = tgkill(tgid, tid, sig);
1171     if (ret < 0) {
1172         if (errno == ESRCH) {
1173             jniThrowExceptionFmt(env, "java/util/NoSuchElementException",
1174                                  "Process with tid %d and tgid %d not found", tid, tgid);
1175         } else {
1176             signalExceptionForError(env, errno, tid);
1177         }
1178     }
1179 }
1180 
android_os_Process_getElapsedCpuTime(JNIEnv * env,jobject clazz)1181 static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
1182 {
1183     struct timespec ts;
1184 
1185     int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
1186 
1187     if (res != 0) {
1188         return (jlong) 0;
1189     }
1190 
1191     nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
1192     return (jlong) nanoseconds_to_milliseconds(when);
1193 }
1194 
android_os_Process_getPss(JNIEnv * env,jobject clazz,jint pid)1195 static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
1196 {
1197     ::android::meminfo::ProcMemInfo proc_mem(pid);
1198     uint64_t pss;
1199     if (!proc_mem.SmapsOrRollupPss(&pss)) {
1200         return (jlong) -1;
1201     }
1202 
1203     // Return the Pss value in bytes, not kilobytes
1204     return pss * 1024;
1205 }
1206 
android_os_Process_getRss(JNIEnv * env,jobject clazz,jint pid)1207 static jlongArray android_os_Process_getRss(JNIEnv* env, jobject clazz, jint pid)
1208 {
1209     // total, file, anon, swap, shmem
1210     jlong rss[5] = {0, 0, 0, 0, 0};
1211     std::string status_path =
1212             android::base::StringPrintf("/proc/%d/status", pid);
1213     UniqueFile file = MakeUniqueFile(status_path.c_str(), "re");
1214     char line[256];
1215     while (file != nullptr && fgets(line, sizeof(line), file.get())) {
1216         jlong v;
1217         if ( sscanf(line, "VmRSS: %" SCNd64 " kB", &v) == 1) {
1218             rss[0] = v;
1219         } else if ( sscanf(line, "RssFile: %" SCNd64 " kB", &v) == 1) {
1220             rss[1] = v;
1221         } else if ( sscanf(line, "RssAnon: %" SCNd64 " kB", &v) == 1) {
1222             rss[2] = v;
1223         } else if ( sscanf(line, "VmSwap: %" SCNd64 " kB", &v) == 1) {
1224             rss[3] = v;
1225         } else if ( sscanf(line, "RssShmem: %" SCNd64 " kB", &v) == 1) {
1226             rss[4] = v;
1227         }
1228     }
1229 
1230     jlongArray rssArray = env->NewLongArray(5);
1231     if (rssArray == NULL) {
1232         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1233         return NULL;
1234     }
1235 
1236     env->SetLongArrayRegion(rssArray, 0, 5, rss);
1237     return rssArray;
1238 }
1239 
android_os_Process_getPidsForCommands(JNIEnv * env,jobject clazz,jobjectArray commandNames)1240 jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
1241         jobjectArray commandNames)
1242 {
1243     if (commandNames == NULL) {
1244         jniThrowNullPointerException(env, NULL);
1245         return NULL;
1246     }
1247 
1248     Vector<String8> commands;
1249 
1250     jsize count = env->GetArrayLength(commandNames);
1251 
1252     for (int i=0; i<count; i++) {
1253         jobject obj = env->GetObjectArrayElement(commandNames, i);
1254         if (obj != NULL) {
1255             const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
1256             if (str8 == NULL) {
1257                 jniThrowNullPointerException(env, "Element in commandNames");
1258                 return NULL;
1259             }
1260             commands.add(String8(str8));
1261             env->ReleaseStringUTFChars((jstring)obj, str8);
1262         } else {
1263             jniThrowNullPointerException(env, "Element in commandNames");
1264             return NULL;
1265         }
1266     }
1267 
1268     Vector<jint> pids;
1269 
1270     DIR *proc = opendir("/proc");
1271     if (proc == NULL) {
1272         fprintf(stderr, "/proc: %s\n", strerror(errno));
1273         return NULL;
1274     }
1275 
1276     struct dirent *d;
1277     while ((d = readdir(proc))) {
1278         int pid = atoi(d->d_name);
1279         if (pid <= 0) continue;
1280 
1281         char path[PATH_MAX];
1282         char data[PATH_MAX];
1283         snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
1284 
1285         int fd = open(path, O_RDONLY | O_CLOEXEC);
1286         if (fd < 0) {
1287             continue;
1288         }
1289         const int len = read(fd, data, sizeof(data)-1);
1290         close(fd);
1291 
1292         if (len < 0) {
1293             continue;
1294         }
1295         data[len] = 0;
1296 
1297         for (int i=0; i<len; i++) {
1298             if (data[i] == ' ') {
1299                 data[i] = 0;
1300                 break;
1301             }
1302         }
1303 
1304         for (size_t i=0; i<commands.size(); i++) {
1305             if (commands[i] == data) {
1306                 pids.add(pid);
1307                 break;
1308             }
1309         }
1310     }
1311 
1312     closedir(proc);
1313 
1314     jintArray pidArray = env->NewIntArray(pids.size());
1315     if (pidArray == NULL) {
1316         jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1317         return NULL;
1318     }
1319 
1320     if (pids.size() > 0) {
1321         env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
1322     }
1323 
1324     return pidArray;
1325 }
1326 
android_os_Process_killProcessGroup(JNIEnv * env,jobject clazz,jint uid,jint pid)1327 jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
1328 {
1329     if (uid < 0) {
1330         return jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
1331                                     "uid is negative: %d", uid);
1332     }
1333 
1334     return killProcessGroup(uid, pid, SIGKILL);
1335 }
1336 
android_os_Process_sendSignalToProcessGroup(JNIEnv * env,jobject clazz,jint uid,jint pid,jint signal)1337 jboolean android_os_Process_sendSignalToProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid,
1338                                                  jint signal) {
1339     if (uid < 0) {
1340         return jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
1341                                     "uid is negative: %d", uid);
1342     }
1343 
1344     return sendSignalToProcessGroup(uid, pid, signal);
1345 }
1346 
android_os_Process_removeAllProcessGroups(JNIEnv * env,jobject clazz)1347 void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
1348 {
1349     return removeAllEmptyProcessGroups();
1350 }
1351 
android_os_Process_nativePidFdOpen(JNIEnv * env,jobject,jint pid,jint flags)1352 static jint android_os_Process_nativePidFdOpen(JNIEnv* env, jobject, jint pid, jint flags) {
1353     int fd = pidfd_open(pid, flags);
1354     if (fd < 0) {
1355         jniThrowErrnoException(env, "nativePidFdOpen", errno);
1356         return -1;
1357     }
1358     return fd;
1359 }
1360 
android_os_Process_freezeCgroupUID(JNIEnv * env,jobject clazz,jint uid,jboolean freeze)1361 void android_os_Process_freezeCgroupUID(JNIEnv* env, jobject clazz, jint uid, jboolean freeze) {
1362     if (uid < 0) {
1363         jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException", "uid is negative: %d", uid);
1364         return;
1365     }
1366 
1367     bool success = true;
1368 
1369     if (freeze) {
1370         success = SetUserProfiles(uid, {"Frozen"});
1371     } else {
1372         success = SetUserProfiles(uid, {"Unfrozen"});
1373     }
1374 
1375     if (!success) {
1376         jniThrowRuntimeException(env, "Could not apply user profile");
1377     }
1378 }
1379 
1380 static const JNINativeMethod methods[] = {
getUidForName(Ljava/lang/String;)1381         {"getUidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
getGidForName(Ljava/lang/String;)1382         {"getGidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
setThreadPriority(II)1383         {"setThreadPriority", "(II)V", (void*)android_os_Process_setThreadPriority},
setThreadScheduler(III)1384         {"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler},
setCanSelfBackground(Z)1385         {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
setThreadPriority(I)1386         {"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority},
getThreadPriority(I)1387         {"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority},
getThreadScheduler(I)1388         {"getThreadScheduler", "(I)I", (void*)android_os_Process_getThreadScheduler},
setThreadGroup(II)1389         {"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup},
setThreadGroupAndCpuset(II)1390         {"setThreadGroupAndCpuset", "(II)V", (void*)android_os_Process_setThreadGroupAndCpuset},
setProcessGroup(II)1391         {"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup},
getProcessGroup(I)1392         {"getProcessGroup", "(I)I", (void*)android_os_Process_getProcessGroup},
createProcessGroup(II)1393         {"createProcessGroup", "(II)I", (void*)android_os_Process_createProcessGroup},
getExclusiveCores()1394         {"getExclusiveCores", "()[I", (void*)android_os_Process_getExclusiveCores},
getSchedAffinity(I)1395         {"getSchedAffinity", "(I)[J", (void*)android_os_Process_getSchedAffinity},
setArgV0Native(Ljava/lang/String;)1396         {"setArgV0Native", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
setUid(I)1397         {"setUid", "(I)I", (void*)android_os_Process_setUid},
setGid(I)1398         {"setGid", "(I)I", (void*)android_os_Process_setGid},
sendSignal(II)1399         {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
sendSignalQuiet(II)1400         {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
sendSignalThrows(II)1401         {"sendSignalThrows", "(II)V", (void*)android_os_Process_sendSignalThrows},
sendTgSignalThrows(III)1402         {"sendTgSignalThrows", "(III)V", (void*)android_os_Process_sendTgSignalThrows},
setProcessFrozen(IIZ)1403         {"setProcessFrozen", "(IIZ)V", (void*)android_os_Process_setProcessFrozen},
getFreeMemory()1404         {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
getTotalMemory()1405         {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
readProcLines(Ljava/lang/String;[Ljava/lang/String;[J)1406         {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V",
1407          (void*)android_os_Process_readProcLines},
getPids(Ljava/lang/String;[I)1408         {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
readProcFile(Ljava/lang/String;[I[Ljava/lang/String;[J[F)1409         {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z",
1410          (void*)android_os_Process_readProcFile},
parseProcLine([BII[I[Ljava/lang/String;[J[F)1411         {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z",
1412          (void*)android_os_Process_parseProcLine},
getElapsedCpuTime()1413         {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
getPss(I)1414         {"getPss", "(I)J", (void*)android_os_Process_getPss},
getRss(I)1415         {"getRss", "(I)[J", (void*)android_os_Process_getRss},
getPidsForCommands([Ljava/lang/String;)1416         {"getPidsForCommands", "([Ljava/lang/String;)[I",
1417          (void*)android_os_Process_getPidsForCommands},
1418         //{"setApplicationObject", "(Landroid/os/IBinder;)V",
1419         //(void*)android_os_Process_setApplicationObject},
killProcessGroup(II)1420         {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
sendSignalToProcessGroup(III)1421         {"sendSignalToProcessGroup", "(III)Z", (void*)android_os_Process_sendSignalToProcessGroup},
removeAllProcessGroups()1422         {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
nativePidFdOpen(II)1423         {"nativePidFdOpen", "(II)I", (void*)android_os_Process_nativePidFdOpen},
freezeCgroupUid(IZ)1424         {"freezeCgroupUid", "(IZ)V", (void*)android_os_Process_freezeCgroupUID},
1425 };
1426 
register_android_os_Process(JNIEnv * env)1427 int register_android_os_Process(JNIEnv* env)
1428 {
1429     return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
1430 }
1431