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_getProcessGroup(JNIEnv * env,jobject clazz,jint pid)349 jint android_os_Process_getProcessGroup(JNIEnv* env, jobject clazz, jint pid)
350 {
351 SchedPolicy sp;
352 if (get_sched_policy(pid, &sp) != 0) {
353 signalExceptionForGroupError(env, errno, pid);
354 }
355 return (int) sp;
356 }
357
358 /** Sample CPUset list format:
359 * 0-3,4,6-8
360 */
parse_cpuset_cpus(char * cpus,cpu_set_t * cpu_set)361 static void parse_cpuset_cpus(char *cpus, cpu_set_t *cpu_set) {
362 unsigned int start, end, matched, i;
363 char *cpu_range = strtok(cpus, ",");
364 while (cpu_range != NULL) {
365 start = end = 0;
366 matched = sscanf(cpu_range, "%u-%u", &start, &end);
367 cpu_range = strtok(NULL, ",");
368 if (start >= CPU_SETSIZE) {
369 ALOGE("parse_cpuset_cpus: ignoring CPU number larger than %d.", CPU_SETSIZE);
370 continue;
371 } else if (end >= CPU_SETSIZE) {
372 ALOGE("parse_cpuset_cpus: ignoring CPU numbers larger than %d.", CPU_SETSIZE);
373 end = CPU_SETSIZE - 1;
374 }
375 if (matched == 1) {
376 CPU_SET(start, cpu_set);
377 } else if (matched == 2) {
378 for (i = start; i <= end; i++) {
379 CPU_SET(i, cpu_set);
380 }
381 } else {
382 ALOGE("Failed to match cpus");
383 }
384 }
385 return;
386 }
387
388 /**
389 * Stores the CPUs assigned to the cpuset corresponding to the
390 * SchedPolicy in the passed in cpu_set.
391 */
get_cpuset_cores_for_policy(SchedPolicy policy,cpu_set_t * cpu_set)392 static void get_cpuset_cores_for_policy(SchedPolicy policy, cpu_set_t *cpu_set)
393 {
394 FILE *file;
395 std::string filename;
396
397 CPU_ZERO(cpu_set);
398
399 switch (policy) {
400 case SP_BACKGROUND:
401 if (!CgroupGetAttributePath("LowCapacityCPUs", &filename)) {
402 return;
403 }
404 break;
405 case SP_FOREGROUND:
406 case SP_AUDIO_APP:
407 case SP_AUDIO_SYS:
408 case SP_RT_APP:
409 if (!CgroupGetAttributePath("HighCapacityCPUs", &filename)) {
410 return;
411 }
412 break;
413 case SP_TOP_APP:
414 if (!CgroupGetAttributePath("MaxCapacityCPUs", &filename)) {
415 return;
416 }
417 break;
418 default:
419 return;
420 }
421
422 file = fopen(filename.c_str(), "re");
423 if (file != NULL) {
424 // Parse cpus string
425 char *line = NULL;
426 size_t len = 0;
427 ssize_t num_read = getline(&line, &len, file);
428 fclose (file);
429 if (num_read > 0) {
430 parse_cpuset_cpus(line, cpu_set);
431 } else {
432 ALOGE("Failed to read %s", filename.c_str());
433 }
434 free(line);
435 }
436 return;
437 }
438
439
440 /**
441 * Determine CPU cores exclusively assigned to the
442 * cpuset corresponding to the SchedPolicy and store
443 * them in the passed in cpu_set_t
444 */
get_exclusive_cpuset_cores(SchedPolicy policy,cpu_set_t * cpu_set)445 void get_exclusive_cpuset_cores(SchedPolicy policy, cpu_set_t *cpu_set) {
446 if (cpusets_enabled()) {
447 int i;
448 cpu_set_t tmp_set;
449 get_cpuset_cores_for_policy(policy, cpu_set);
450 for (i = 0; i < SP_CNT; i++) {
451 if ((SchedPolicy) i == policy) continue;
452 get_cpuset_cores_for_policy((SchedPolicy)i, &tmp_set);
453 // First get cores exclusive to one set or the other
454 CPU_XOR(&tmp_set, cpu_set, &tmp_set);
455 // Then get the ones only in cpu_set
456 CPU_AND(cpu_set, cpu_set, &tmp_set);
457 }
458 } else {
459 CPU_ZERO(cpu_set);
460 }
461 return;
462 }
463
android_os_Process_getExclusiveCores(JNIEnv * env,jobject clazz)464 jintArray android_os_Process_getExclusiveCores(JNIEnv* env, jobject clazz) {
465 SchedPolicy sp;
466 cpu_set_t cpu_set;
467 jintArray cpus;
468 int pid = getpid();
469 if (get_sched_policy(pid, &sp) != 0) {
470 signalExceptionForGroupError(env, errno, pid);
471 return NULL;
472 }
473 get_exclusive_cpuset_cores(sp, &cpu_set);
474 int num_cpus = CPU_COUNT(&cpu_set);
475 cpus = env->NewIntArray(num_cpus);
476 if (cpus == NULL) {
477 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
478 return NULL;
479 }
480
481 jint* cpu_elements = env->GetIntArrayElements(cpus, 0);
482 int count = 0;
483 for (int i = 0; i < CPU_SETSIZE && count < num_cpus; i++) {
484 if (CPU_ISSET(i, &cpu_set)) {
485 cpu_elements[count++] = i;
486 }
487 }
488
489 env->ReleaseIntArrayElements(cpus, cpu_elements, 0);
490 return cpus;
491 }
492
android_os_Process_setCanSelfBackground(JNIEnv * env,jobject clazz,jboolean bgOk)493 static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
494 // Establishes the calling thread as illegal to put into the background.
495 // Typically used only for the system process's main looper.
496 #if GUARD_THREAD_PRIORITY
497 ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
498 {
499 Mutex::Autolock _l(gKeyCreateMutex);
500 if (gBgKey == -1) {
501 pthread_key_create(&gBgKey, NULL);
502 }
503 }
504
505 // inverted: not-okay, we set a sentinel value
506 pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
507 #endif
508 }
509
android_os_Process_getThreadScheduler(JNIEnv * env,jclass clazz,jint tid)510 jint android_os_Process_getThreadScheduler(JNIEnv* env, jclass clazz,
511 jint tid)
512 {
513 int policy = 0;
514 // linux has sched_getscheduler(), others don't.
515 #if defined(__linux__)
516 errno = 0;
517 policy = sched_getscheduler(tid);
518 if (errno != 0) {
519 signalExceptionForPriorityError(env, errno, tid);
520 }
521 #else
522 signalExceptionForPriorityError(env, ENOSYS, tid);
523 #endif
524 return policy;
525 }
526
android_os_Process_setThreadScheduler(JNIEnv * env,jclass clazz,jint tid,jint policy,jint pri)527 void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
528 jint tid, jint policy, jint pri)
529 {
530 // linux has sched_setscheduler(), others don't.
531 #if defined(__linux__)
532 struct sched_param param;
533 param.sched_priority = pri;
534 int rc = sched_setscheduler(tid, policy, ¶m);
535 if (rc) {
536 signalExceptionForPriorityError(env, errno, tid);
537 }
538 #else
539 signalExceptionForPriorityError(env, ENOSYS, tid);
540 #endif
541 }
542
android_os_Process_setThreadPriority(JNIEnv * env,jobject clazz,jint pid,jint pri)543 void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
544 jint pid, jint pri)
545 {
546 #if GUARD_THREAD_PRIORITY
547 // if we're putting the current thread into the background, check the TLS
548 // to make sure this thread isn't guarded. If it is, raise an exception.
549 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
550 if (pid == gettid()) {
551 void* bgOk = pthread_getspecific(gBgKey);
552 if (bgOk == ((void*)0xbaad)) {
553 ALOGE("Thread marked fg-only put self in background!");
554 jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
555 return;
556 }
557 }
558 }
559 #endif
560
561 int rc = androidSetThreadPriority(pid, pri);
562 if (rc != 0) {
563 if (rc == INVALID_OPERATION) {
564 signalExceptionForPriorityError(env, errno, pid);
565 } else {
566 signalExceptionForGroupError(env, errno, pid);
567 }
568 }
569
570 //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
571 // pid, pri, getpriority(PRIO_PROCESS, pid));
572 }
573
android_os_Process_setCallingThreadPriority(JNIEnv * env,jobject clazz,jint pri)574 void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
575 jint pri)
576 {
577 android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
578 }
579
android_os_Process_getThreadPriority(JNIEnv * env,jobject clazz,jint pid)580 jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
581 jint pid)
582 {
583 errno = 0;
584 jint pri = getpriority(PRIO_PROCESS, pid);
585 if (errno != 0) {
586 signalExceptionForPriorityError(env, errno, pid);
587 }
588 //ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
589 return pri;
590 }
591
android_os_Process_setSwappiness(JNIEnv * env,jobject clazz,jint pid,jboolean is_increased)592 jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
593 jint pid, jboolean is_increased)
594 {
595 char text[64];
596
597 if (is_increased) {
598 strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
599 } else {
600 strcpy(text, "/sys/fs/cgroup/memory/tasks");
601 }
602
603 struct stat st;
604 if (stat(text, &st) || !S_ISREG(st.st_mode)) {
605 return false;
606 }
607
608 int fd = open(text, O_WRONLY | O_CLOEXEC);
609 if (fd >= 0) {
610 sprintf(text, "%" PRId32, pid);
611 write(fd, text, strlen(text));
612 close(fd);
613 }
614
615 return true;
616 }
617
android_os_Process_setArgV0(JNIEnv * env,jobject clazz,jstring name)618 void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
619 {
620 if (name == NULL) {
621 jniThrowNullPointerException(env, NULL);
622 return;
623 }
624
625 const jchar* str = env->GetStringCritical(name, 0);
626 String8 name8;
627 if (str) {
628 name8 = String8(reinterpret_cast<const char16_t*>(str),
629 env->GetStringLength(name));
630 env->ReleaseStringCritical(name, str);
631 }
632
633 if (!name8.isEmpty()) {
634 AndroidRuntime::getRuntime()->setArgv0(name8.string(), true /* setProcName */);
635 }
636 }
637
android_os_Process_setUid(JNIEnv * env,jobject clazz,jint uid)638 jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
639 {
640 return setuid(uid) == 0 ? 0 : errno;
641 }
642
android_os_Process_setGid(JNIEnv * env,jobject clazz,jint uid)643 jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
644 {
645 return setgid(uid) == 0 ? 0 : errno;
646 }
647
pid_compare(const void * v1,const void * v2)648 static int pid_compare(const void* v1, const void* v2)
649 {
650 //ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
651 return *((const jint*)v1) - *((const jint*)v2);
652 }
653
android_os_Process_getFreeMemory(JNIEnv * env,jobject clazz)654 static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
655 {
656 std::array<std::string_view, 2> memFreeTags = {
657 ::android::meminfo::SysMemInfo::kMemFree,
658 ::android::meminfo::SysMemInfo::kMemCached,
659 };
660 std::vector<uint64_t> mem(memFreeTags.size());
661 ::android::meminfo::SysMemInfo smi;
662
663 if (!smi.ReadMemInfo(memFreeTags.size(),
664 memFreeTags.data(),
665 mem.data())) {
666 jniThrowRuntimeException(env, "SysMemInfo read failed to get Free Memory");
667 return -1L;
668 }
669
670 jlong sum = 0;
671 std::for_each(mem.begin(), mem.end(), [&](uint64_t val) { sum += val; });
672 return sum * 1024;
673 }
674
android_os_Process_getTotalMemory(JNIEnv * env,jobject clazz)675 static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
676 {
677 struct sysinfo si;
678 if (sysinfo(&si) == -1) {
679 ALOGE("sysinfo failed: %s", strerror(errno));
680 return -1;
681 }
682
683 return static_cast<jlong>(si.totalram) * si.mem_unit;
684 }
685
686 /*
687 * The outFields array is initialized to -1 to allow the caller to identify
688 * when the status file (and therefore the process) they specified is invalid.
689 * This array should not be overwritten or cleared before we know that the
690 * status file can be read.
691 */
android_os_Process_readProcLines(JNIEnv * env,jobject clazz,jstring fileStr,jobjectArray reqFields,jlongArray outFields)692 void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
693 jobjectArray reqFields, jlongArray outFields)
694 {
695 //ALOGI("getMemInfo: %p %p", reqFields, outFields);
696
697 if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
698 jniThrowNullPointerException(env, NULL);
699 return;
700 }
701
702 const char* file8 = env->GetStringUTFChars(fileStr, NULL);
703 if (file8 == NULL) {
704 return;
705 }
706 String8 file(file8);
707 env->ReleaseStringUTFChars(fileStr, file8);
708
709 jsize count = env->GetArrayLength(reqFields);
710 if (count > env->GetArrayLength(outFields)) {
711 jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
712 return;
713 }
714
715 Vector<String8> fields;
716 int i;
717
718 for (i=0; i<count; i++) {
719 jobject obj = env->GetObjectArrayElement(reqFields, i);
720 if (obj != NULL) {
721 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
722 //ALOGI("String at %d: %p = %s", i, obj, str8);
723 if (str8 == NULL) {
724 jniThrowNullPointerException(env, "Element in reqFields");
725 return;
726 }
727 fields.add(String8(str8));
728 env->ReleaseStringUTFChars((jstring)obj, str8);
729 } else {
730 jniThrowNullPointerException(env, "Element in reqFields");
731 return;
732 }
733 }
734
735 jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
736 if (sizesArray == NULL) {
737 return;
738 }
739
740 int fd = open(file.string(), O_RDONLY | O_CLOEXEC);
741
742 if (fd >= 0) {
743 //ALOGI("Clearing %" PRId32 " sizes", count);
744 for (i=0; i<count; i++) {
745 sizesArray[i] = 0;
746 }
747
748 const size_t BUFFER_SIZE = 4096;
749 char* buffer = (char*)malloc(BUFFER_SIZE);
750 int len = read(fd, buffer, BUFFER_SIZE-1);
751 close(fd);
752
753 if (len < 0) {
754 ALOGW("Unable to read %s", file.string());
755 len = 0;
756 }
757 buffer[len] = 0;
758
759 int foundCount = 0;
760
761 char* p = buffer;
762 while (*p && foundCount < count) {
763 bool skipToEol = true;
764 //ALOGI("Parsing at: %s", p);
765 for (i=0; i<count; i++) {
766 const String8& field = fields[i];
767 if (strncmp(p, field.string(), field.length()) == 0) {
768 p += field.length();
769 while (*p == ' ' || *p == '\t') p++;
770 char* num = p;
771 while (*p >= '0' && *p <= '9') p++;
772 skipToEol = *p != '\n';
773 if (*p != 0) {
774 *p = 0;
775 p++;
776 }
777 char* end;
778 sizesArray[i] = strtoll(num, &end, 10);
779 //ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
780 foundCount++;
781 break;
782 }
783 }
784 if (skipToEol) {
785 while (*p && *p != '\n') {
786 p++;
787 }
788 if (*p == '\n') {
789 p++;
790 }
791 }
792 }
793
794 free(buffer);
795 } else {
796 ALOGW("Unable to open %s", file.string());
797 }
798
799 //ALOGI("Done!");
800 env->ReleaseLongArrayElements(outFields, sizesArray, 0);
801 }
802
android_os_Process_getPids(JNIEnv * env,jobject clazz,jstring file,jintArray lastArray)803 jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
804 jstring file, jintArray lastArray)
805 {
806 if (file == NULL) {
807 jniThrowNullPointerException(env, NULL);
808 return NULL;
809 }
810
811 const char* file8 = env->GetStringUTFChars(file, NULL);
812 if (file8 == NULL) {
813 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
814 return NULL;
815 }
816
817 DIR* dirp = opendir(file8);
818
819 env->ReleaseStringUTFChars(file, file8);
820
821 if(dirp == NULL) {
822 return NULL;
823 }
824
825 jsize curCount = 0;
826 jint* curData = NULL;
827 if (lastArray != NULL) {
828 curCount = env->GetArrayLength(lastArray);
829 curData = env->GetIntArrayElements(lastArray, 0);
830 }
831
832 jint curPos = 0;
833
834 struct dirent* entry;
835 while ((entry=readdir(dirp)) != NULL) {
836 const char* p = entry->d_name;
837 while (*p) {
838 if (*p < '0' || *p > '9') break;
839 p++;
840 }
841 if (*p != 0) continue;
842
843 char* end;
844 int pid = strtol(entry->d_name, &end, 10);
845 //ALOGI("File %s pid=%d\n", entry->d_name, pid);
846 if (curPos >= curCount) {
847 jsize newCount = (curCount == 0) ? 10 : (curCount*2);
848 jintArray newArray = env->NewIntArray(newCount);
849 if (newArray == NULL) {
850 closedir(dirp);
851 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
852 return NULL;
853 }
854 jint* newData = env->GetIntArrayElements(newArray, 0);
855 if (curData != NULL) {
856 memcpy(newData, curData, sizeof(jint)*curCount);
857 env->ReleaseIntArrayElements(lastArray, curData, 0);
858 }
859 lastArray = newArray;
860 curCount = newCount;
861 curData = newData;
862 }
863
864 curData[curPos] = pid;
865 curPos++;
866 }
867
868 closedir(dirp);
869
870 if (curData != NULL && curPos > 0) {
871 qsort(curData, curPos, sizeof(jint), pid_compare);
872 }
873
874 while (curPos < curCount) {
875 curData[curPos] = -1;
876 curPos++;
877 }
878
879 if (curData != NULL) {
880 env->ReleaseIntArrayElements(lastArray, curData, 0);
881 }
882
883 return lastArray;
884 }
885
886 enum {
887 PROC_TERM_MASK = 0xff,
888 PROC_ZERO_TERM = 0,
889 PROC_SPACE_TERM = ' ',
890 PROC_COMBINE = 0x100,
891 PROC_PARENS = 0x200,
892 PROC_QUOTES = 0x400,
893 PROC_CHAR = 0x800,
894 PROC_OUT_STRING = 0x1000,
895 PROC_OUT_LONG = 0x2000,
896 PROC_OUT_FLOAT = 0x4000,
897 };
898
android_os_Process_parseProcLineArray(JNIEnv * env,jobject clazz,char * buffer,jint startIndex,jint endIndex,jintArray format,jobjectArray outStrings,jlongArray outLongs,jfloatArray outFloats)899 jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
900 char* buffer, jint startIndex, jint endIndex, jintArray format,
901 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
902 {
903
904 const jsize NF = env->GetArrayLength(format);
905 const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
906 const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
907 const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
908
909 jint* formatData = env->GetIntArrayElements(format, 0);
910 jlong* longsData = outLongs ?
911 env->GetLongArrayElements(outLongs, 0) : NULL;
912 jfloat* floatsData = outFloats ?
913 env->GetFloatArrayElements(outFloats, 0) : NULL;
914 if (formatData == NULL || (NL > 0 && longsData == NULL)
915 || (NR > 0 && floatsData == NULL)) {
916 if (formatData != NULL) {
917 env->ReleaseIntArrayElements(format, formatData, 0);
918 }
919 if (longsData != NULL) {
920 env->ReleaseLongArrayElements(outLongs, longsData, 0);
921 }
922 if (floatsData != NULL) {
923 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
924 }
925 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
926 return JNI_FALSE;
927 }
928
929 jsize i = startIndex;
930 jsize di = 0;
931
932 jboolean res = JNI_TRUE;
933
934 for (jsize fi=0; fi<NF; fi++) {
935 jint mode = formatData[fi];
936 if ((mode&PROC_PARENS) != 0) {
937 i++;
938 } else if ((mode&PROC_QUOTES) != 0) {
939 if (buffer[i] == '"') {
940 i++;
941 } else {
942 mode &= ~PROC_QUOTES;
943 }
944 }
945 const char term = (char)(mode&PROC_TERM_MASK);
946 const jsize start = i;
947 if (i >= endIndex) {
948 if (kDebugProc) {
949 ALOGW("Ran off end of data @%d", i);
950 }
951 res = JNI_FALSE;
952 break;
953 }
954
955 jsize end = -1;
956 if ((mode&PROC_PARENS) != 0) {
957 while (i < endIndex && buffer[i] != ')') {
958 i++;
959 }
960 end = i;
961 i++;
962 } else if ((mode&PROC_QUOTES) != 0) {
963 while (buffer[i] != '"' && i < endIndex) {
964 i++;
965 }
966 end = i;
967 i++;
968 }
969 while (i < endIndex && buffer[i] != term) {
970 i++;
971 }
972 if (end < 0) {
973 end = i;
974 }
975
976 if (i < endIndex) {
977 i++;
978 if ((mode&PROC_COMBINE) != 0) {
979 while (i < endIndex && buffer[i] == term) {
980 i++;
981 }
982 }
983 }
984
985 //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
986
987 if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
988 char c = buffer[end];
989 buffer[end] = 0;
990 if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
991 char* end;
992 floatsData[di] = strtof(buffer+start, &end);
993 }
994 if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
995 if ((mode&PROC_CHAR) != 0) {
996 // Caller wants single first character returned as one long.
997 longsData[di] = buffer[start];
998 } else {
999 char* end;
1000 longsData[di] = strtoll(buffer+start, &end, 10);
1001 }
1002 }
1003 if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
1004 jstring str = env->NewStringUTF(buffer+start);
1005 env->SetObjectArrayElement(outStrings, di, str);
1006 }
1007 buffer[end] = c;
1008 di++;
1009 }
1010 }
1011
1012 env->ReleaseIntArrayElements(format, formatData, 0);
1013 if (longsData != NULL) {
1014 env->ReleaseLongArrayElements(outLongs, longsData, 0);
1015 }
1016 if (floatsData != NULL) {
1017 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
1018 }
1019
1020 return res;
1021 }
1022
android_os_Process_parseProcLine(JNIEnv * env,jobject clazz,jbyteArray buffer,jint startIndex,jint endIndex,jintArray format,jobjectArray outStrings,jlongArray outLongs,jfloatArray outFloats)1023 jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
1024 jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
1025 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
1026 {
1027 jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
1028
1029 jboolean result = android_os_Process_parseProcLineArray(env, clazz,
1030 (char*) bufferArray, startIndex, endIndex, format, outStrings,
1031 outLongs, outFloats);
1032
1033 env->ReleaseByteArrayElements(buffer, bufferArray, 0);
1034
1035 return result;
1036 }
1037
android_os_Process_readProcFile(JNIEnv * env,jobject clazz,jstring file,jintArray format,jobjectArray outStrings,jlongArray outLongs,jfloatArray outFloats)1038 jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
1039 jstring file, jintArray format, jobjectArray outStrings,
1040 jlongArray outLongs, jfloatArray outFloats)
1041 {
1042 if (file == NULL || format == NULL) {
1043 jniThrowNullPointerException(env, NULL);
1044 return JNI_FALSE;
1045 }
1046
1047 const char* file8 = env->GetStringUTFChars(file, NULL);
1048 if (file8 == NULL) {
1049 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1050 return JNI_FALSE;
1051 }
1052
1053 ::android::base::unique_fd fd(open(file8, O_RDONLY | O_CLOEXEC));
1054 if (!fd.ok()) {
1055 if (kDebugProc) {
1056 ALOGW("Unable to open process file: %s\n", file8);
1057 }
1058 env->ReleaseStringUTFChars(file, file8);
1059 return JNI_FALSE;
1060 }
1061 env->ReleaseStringUTFChars(file, file8);
1062
1063 // Most proc files we read are small, so we only go through the
1064 // loop once and use the stack buffer. We allocate a buffer big
1065 // enough for the whole file.
1066
1067 char readBufferStack[kProcReadStackBufferSize];
1068 std::unique_ptr<char[]> readBufferHeap;
1069 char* readBuffer = &readBufferStack[0];
1070 ssize_t readBufferSize = kProcReadStackBufferSize;
1071 ssize_t numberBytesRead;
1072 for (;;) {
1073 // By using pread, we can avoid an lseek to rewind the FD
1074 // before retry, saving a system call.
1075 numberBytesRead = pread(fd, readBuffer, readBufferSize, 0);
1076 if (numberBytesRead < 0 && errno == EINTR) {
1077 continue;
1078 }
1079 if (numberBytesRead < 0) {
1080 if (kDebugProc) {
1081 ALOGW("Unable to open process file: %s fd=%d\n", file8, fd.get());
1082 }
1083 return JNI_FALSE;
1084 }
1085 if (numberBytesRead < readBufferSize) {
1086 break;
1087 }
1088 if (readBufferSize > std::numeric_limits<ssize_t>::max() / 2) {
1089 if (kDebugProc) {
1090 ALOGW("Proc file too big: %s fd=%d\n", file8, fd.get());
1091 }
1092 return JNI_FALSE;
1093 }
1094 readBufferSize = std::max(readBufferSize * 2,
1095 kProcReadMinHeapBufferSize);
1096 readBufferHeap.reset(); // Free address space before getting more.
1097 readBufferHeap = std::make_unique<char[]>(readBufferSize);
1098 if (!readBufferHeap) {
1099 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1100 return JNI_FALSE;
1101 }
1102 readBuffer = readBufferHeap.get();
1103 }
1104
1105 // parseProcLineArray below modifies the buffer while parsing!
1106 return android_os_Process_parseProcLineArray(
1107 env, clazz, readBuffer, 0, numberBytesRead,
1108 format, outStrings, outLongs, outFloats);
1109 }
1110
android_os_Process_setApplicationObject(JNIEnv * env,jobject clazz,jobject binderObject)1111 void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
1112 jobject binderObject)
1113 {
1114 if (binderObject == NULL) {
1115 jniThrowNullPointerException(env, NULL);
1116 return;
1117 }
1118
1119 sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
1120 }
1121
android_os_Process_sendSignal(JNIEnv * env,jobject clazz,jint pid,jint sig)1122 void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
1123 {
1124 if (pid > 0) {
1125 ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
1126 kill(pid, sig);
1127 }
1128 }
1129
android_os_Process_sendSignalQuiet(JNIEnv * env,jobject clazz,jint pid,jint sig)1130 void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
1131 {
1132 if (pid > 0) {
1133 kill(pid, sig);
1134 }
1135 }
1136
android_os_Process_getElapsedCpuTime(JNIEnv * env,jobject clazz)1137 static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
1138 {
1139 struct timespec ts;
1140
1141 int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
1142
1143 if (res != 0) {
1144 return (jlong) 0;
1145 }
1146
1147 nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
1148 return (jlong) nanoseconds_to_milliseconds(when);
1149 }
1150
android_os_Process_getPss(JNIEnv * env,jobject clazz,jint pid)1151 static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
1152 {
1153 ::android::meminfo::ProcMemInfo proc_mem(pid);
1154 uint64_t pss;
1155 if (!proc_mem.SmapsOrRollupPss(&pss)) {
1156 return (jlong) -1;
1157 }
1158
1159 // Return the Pss value in bytes, not kilobytes
1160 return pss * 1024;
1161 }
1162
android_os_Process_getRss(JNIEnv * env,jobject clazz,jint pid)1163 static jlongArray android_os_Process_getRss(JNIEnv* env, jobject clazz, jint pid)
1164 {
1165 // total, file, anon, swap
1166 jlong rss[4] = {0, 0, 0, 0};
1167 std::string status_path =
1168 android::base::StringPrintf("/proc/%d/status", pid);
1169 UniqueFile file = MakeUniqueFile(status_path.c_str(), "re");
1170
1171 char line[256];
1172 while (file != nullptr && fgets(line, sizeof(line), file.get())) {
1173 jlong v;
1174 if ( sscanf(line, "VmRSS: %" SCNd64 " kB", &v) == 1) {
1175 rss[0] = v;
1176 } else if ( sscanf(line, "RssFile: %" SCNd64 " kB", &v) == 1) {
1177 rss[1] = v;
1178 } else if ( sscanf(line, "RssAnon: %" SCNd64 " kB", &v) == 1) {
1179 rss[2] = v;
1180 } else if ( sscanf(line, "VmSwap: %" SCNd64 " kB", &v) == 1) {
1181 rss[3] = v;
1182 }
1183 }
1184
1185 jlongArray rssArray = env->NewLongArray(4);
1186 if (rssArray == NULL) {
1187 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1188 return NULL;
1189 }
1190
1191 env->SetLongArrayRegion(rssArray, 0, 4, rss);
1192
1193 return rssArray;
1194 }
1195
android_os_Process_getPidsForCommands(JNIEnv * env,jobject clazz,jobjectArray commandNames)1196 jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
1197 jobjectArray commandNames)
1198 {
1199 if (commandNames == NULL) {
1200 jniThrowNullPointerException(env, NULL);
1201 return NULL;
1202 }
1203
1204 Vector<String8> commands;
1205
1206 jsize count = env->GetArrayLength(commandNames);
1207
1208 for (int i=0; i<count; i++) {
1209 jobject obj = env->GetObjectArrayElement(commandNames, i);
1210 if (obj != NULL) {
1211 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
1212 if (str8 == NULL) {
1213 jniThrowNullPointerException(env, "Element in commandNames");
1214 return NULL;
1215 }
1216 commands.add(String8(str8));
1217 env->ReleaseStringUTFChars((jstring)obj, str8);
1218 } else {
1219 jniThrowNullPointerException(env, "Element in commandNames");
1220 return NULL;
1221 }
1222 }
1223
1224 Vector<jint> pids;
1225
1226 DIR *proc = opendir("/proc");
1227 if (proc == NULL) {
1228 fprintf(stderr, "/proc: %s\n", strerror(errno));
1229 return NULL;
1230 }
1231
1232 struct dirent *d;
1233 while ((d = readdir(proc))) {
1234 int pid = atoi(d->d_name);
1235 if (pid <= 0) continue;
1236
1237 char path[PATH_MAX];
1238 char data[PATH_MAX];
1239 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
1240
1241 int fd = open(path, O_RDONLY | O_CLOEXEC);
1242 if (fd < 0) {
1243 continue;
1244 }
1245 const int len = read(fd, data, sizeof(data)-1);
1246 close(fd);
1247
1248 if (len < 0) {
1249 continue;
1250 }
1251 data[len] = 0;
1252
1253 for (int i=0; i<len; i++) {
1254 if (data[i] == ' ') {
1255 data[i] = 0;
1256 break;
1257 }
1258 }
1259
1260 for (size_t i=0; i<commands.size(); i++) {
1261 if (commands[i] == data) {
1262 pids.add(pid);
1263 break;
1264 }
1265 }
1266 }
1267
1268 closedir(proc);
1269
1270 jintArray pidArray = env->NewIntArray(pids.size());
1271 if (pidArray == NULL) {
1272 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1273 return NULL;
1274 }
1275
1276 if (pids.size() > 0) {
1277 env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
1278 }
1279
1280 return pidArray;
1281 }
1282
android_os_Process_killProcessGroup(JNIEnv * env,jobject clazz,jint uid,jint pid)1283 jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
1284 {
1285 return killProcessGroup(uid, pid, SIGKILL);
1286 }
1287
android_os_Process_removeAllProcessGroups(JNIEnv * env,jobject clazz)1288 void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
1289 {
1290 return removeAllProcessGroups();
1291 }
1292
throwErrnoException(JNIEnv * env,const char * functionName,int error)1293 static void throwErrnoException(JNIEnv* env, const char* functionName, int error) {
1294 ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName));
1295 if (detailMessage.get() == NULL) {
1296 // Not really much we can do here. We're probably dead in the water,
1297 // but let's try to stumble on...
1298 env->ExceptionClear();
1299 }
1300 static jclass errnoExceptionClass =
1301 MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/system/ErrnoException"));
1302
1303 static jmethodID errnoExceptionCtor =
1304 GetMethodIDOrDie(env, errnoExceptionClass, "<init>", "(Ljava/lang/String;I)V");
1305
1306 jobject exception =
1307 env->NewObject(errnoExceptionClass, errnoExceptionCtor, detailMessage.get(), error);
1308 env->Throw(reinterpret_cast<jthrowable>(exception));
1309 }
1310
1311 // Wrapper function to the syscall pidfd_open, which creates a file
1312 // descriptor that refers to the process whose PID is specified in pid.
sys_pidfd_open(pid_t pid,unsigned int flags)1313 static inline int sys_pidfd_open(pid_t pid, unsigned int flags) {
1314 return syscall(__NR_pidfd_open, pid, flags);
1315 }
1316
android_os_Process_nativePidFdOpen(JNIEnv * env,jobject,jint pid,jint flags)1317 static jint android_os_Process_nativePidFdOpen(JNIEnv* env, jobject, jint pid, jint flags) {
1318 int fd = sys_pidfd_open(pid, flags);
1319 if (fd < 0) {
1320 throwErrnoException(env, "nativePidFdOpen", errno);
1321 return -1;
1322 }
1323 return fd;
1324 }
1325
1326 static const JNINativeMethod methods[] = {
1327 {"getUidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
1328 {"getGidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
1329 {"setThreadPriority", "(II)V", (void*)android_os_Process_setThreadPriority},
1330 {"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler},
1331 {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
1332 {"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority},
1333 {"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority},
1334 {"getThreadScheduler", "(I)I", (void*)android_os_Process_getThreadScheduler},
1335 {"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup},
1336 {"setThreadGroupAndCpuset", "(II)V", (void*)android_os_Process_setThreadGroupAndCpuset},
1337 {"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup},
1338 {"getProcessGroup", "(I)I", (void*)android_os_Process_getProcessGroup},
1339 {"getExclusiveCores", "()[I", (void*)android_os_Process_getExclusiveCores},
1340 {"setSwappiness", "(IZ)Z", (void*)android_os_Process_setSwappiness},
1341 {"setArgV0", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
1342 {"setUid", "(I)I", (void*)android_os_Process_setUid},
1343 {"setGid", "(I)I", (void*)android_os_Process_setGid},
1344 {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
1345 {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
1346 {"setProcessFrozen", "(IIZ)V", (void*)android_os_Process_setProcessFrozen},
1347 {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
1348 {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
1349 {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V",
1350 (void*)android_os_Process_readProcLines},
1351 {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
1352 {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z",
1353 (void*)android_os_Process_readProcFile},
1354 {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z",
1355 (void*)android_os_Process_parseProcLine},
1356 {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
1357 {"getPss", "(I)J", (void*)android_os_Process_getPss},
1358 {"getRss", "(I)[J", (void*)android_os_Process_getRss},
1359 {"getPidsForCommands", "([Ljava/lang/String;)[I",
1360 (void*)android_os_Process_getPidsForCommands},
1361 //{"setApplicationObject", "(Landroid/os/IBinder;)V",
1362 //(void*)android_os_Process_setApplicationObject},
1363 {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
1364 {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
1365 {"nativePidFdOpen", "(II)I", (void*)android_os_Process_nativePidFdOpen},
1366 };
1367
register_android_os_Process(JNIEnv * env)1368 int register_android_os_Process(JNIEnv* env)
1369 {
1370 return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
1371 }
1372