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