blob: 62aa1f38ca30b3fb30dc2f9f8592279878bdbd76 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/* //device/libs/android_runtime/android_util_Process.cpp
2**
3** Copyright 2006, The Android Open Source Project
4**
Elliott Hughes69a017b2011-04-08 14:10:28 -07005** 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008**
Elliott Hughes69a017b2011-04-08 14:10:28 -07009** http://www.apache.org/licenses/LICENSE-2.0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010**
Elliott Hughes69a017b2011-04-08 14:10:28 -070011** 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015** limitations under the License.
16*/
17
18#define LOG_TAG "Process"
19
Martijn Coenencd4bdf32016-03-03 17:30:52 +010020// To make sure cpu_set_t is included from sched.h
21#define _GNU_SOURCE 1
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070023#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070024#include <binder/IServiceManager.h>
Glenn Kastenf1b56442012-03-15 16:33:43 -070025#include <cutils/sched_policy.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026#include <utils/String8.h>
27#include <utils/Vector.h>
Colin Cross0769e552014-06-03 13:25:35 -070028#include <processgroup/processgroup.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Andreas Gampeed6b9df2014-11-20 22:02:20 -080030#include "core_jni_helpers.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
32#include "android_util_Binder.h"
Steven Moreland2279b252017-07-19 09:50:45 -070033#include <nativehelper/JNIHelp.h>
Daniel Colascione6c518102017-07-27 03:33:34 -070034#include "android_os_Debug.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036#include <dirent.h>
37#include <fcntl.h>
38#include <grp.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070039#include <inttypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040#include <pwd.h>
41#include <signal.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070042#include <sys/errno.h>
43#include <sys/resource.h>
44#include <sys/stat.h>
45#include <sys/types.h>
Glenn Kasten6af763b2011-05-04 17:58:57 -070046#include <unistd.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
Christopher Tate160edb32010-06-30 17:46:30 -070048#define GUARD_THREAD_PRIORITY 0
San Mehata5109a82009-10-29 11:48:50 -070049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050using namespace android;
51
Andreas Gampe0f0b4912014-11-12 08:03:48 -080052static const bool kDebugPolicy = false;
53static const bool kDebugProc = false;
54
Christopher Tate160edb32010-06-30 17:46:30 -070055#if GUARD_THREAD_PRIORITY
56Mutex gKeyCreateMutex;
57static pthread_key_t gBgKey = -1;
58#endif
59
Glenn Kastenf1b56442012-03-15 16:33:43 -070060// For both of these, err should be in the errno range (positive), not a status_t (negative)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070061static void signalExceptionForError(JNIEnv* env, int err, int tid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 switch (err) {
63 case EINVAL:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070064 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
65 "Invalid argument: %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 break;
67 case ESRCH:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070068 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
69 "Given thread %d does not exist", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 break;
71 case EPERM:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070072 jniThrowExceptionFmt(env, "java/lang/SecurityException",
73 "No permission to modify given thread %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 break;
75 default:
76 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
77 break;
78 }
79}
80
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070081static void signalExceptionForPriorityError(JNIEnv* env, int err, int tid) {
San Mehate9d376b2009-04-21 14:06:36 -070082 switch (err) {
San Mehate9d376b2009-04-21 14:06:36 -070083 case EACCES:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070084 jniThrowExceptionFmt(env, "java/lang/SecurityException",
85 "No permission to set the priority of %d", tid);
San Mehate9d376b2009-04-21 14:06:36 -070086 break;
87 default:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070088 signalExceptionForError(env, err, tid);
89 break;
90 }
91
92}
93
94static void signalExceptionForGroupError(JNIEnv* env, int err, int tid) {
95 switch (err) {
96 case EACCES:
97 jniThrowExceptionFmt(env, "java/lang/SecurityException",
98 "No permission to set the group of %d", tid);
99 break;
100 default:
101 signalExceptionForError(env, err, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700102 break;
103 }
104}
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
107{
108 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700109 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 return -1;
111 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 const jchar* str16 = env->GetStringCritical(name, 0);
114 String8 name8;
115 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800116 name8 = String8(reinterpret_cast<const char16_t*>(str16),
117 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 env->ReleaseStringCritical(name, str16);
119 }
120
121 const size_t N = name8.size();
122 if (N > 0) {
123 const char* str = name8.string();
124 for (size_t i=0; i<N; i++) {
125 if (str[i] < '0' || str[i] > '9') {
126 struct passwd* pwd = getpwnam(str);
127 if (pwd == NULL) {
128 return -1;
129 }
130 return pwd->pw_uid;
131 }
132 }
133 return atoi(str);
134 }
135 return -1;
136}
137
138jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
139{
140 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700141 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 return -1;
143 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 const jchar* str16 = env->GetStringCritical(name, 0);
146 String8 name8;
147 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800148 name8 = String8(reinterpret_cast<const char16_t*>(str16),
149 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 env->ReleaseStringCritical(name, str16);
151 }
152
153 const size_t N = name8.size();
154 if (N > 0) {
155 const char* str = name8.string();
156 for (size_t i=0; i<N; i++) {
157 if (str[i] < '0' || str[i] > '9') {
158 struct group* grp = getgrnam(str);
159 if (grp == NULL) {
160 return -1;
161 }
162 return grp->gr_gid;
163 }
164 }
165 return atoi(str);
166 }
167 return -1;
168}
169
Glenn Kastenf1b56442012-03-15 16:33:43 -0700170void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int tid, jint grp)
San Mehate9d376b2009-04-21 14:06:36 -0700171{
Mark Salyzync6a41012014-04-24 13:05:18 -0700172 ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
Glenn Kastenf1b56442012-03-15 16:33:43 -0700173 SchedPolicy sp = (SchedPolicy) grp;
174 int res = set_sched_policy(tid, sp);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800175 if (res != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700176 signalExceptionForGroupError(env, -res, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700177 }
San Mehate9d376b2009-04-21 14:06:36 -0700178}
179
Joel Fernandes474d3112017-04-04 16:32:15 -0700180void android_os_Process_setThreadGroupAndCpuset(JNIEnv* env, jobject clazz, int tid, jint grp)
181{
182 ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
183 SchedPolicy sp = (SchedPolicy) grp;
184 int res = set_sched_policy(tid, sp);
185
186 if (res != NO_ERROR) {
187 signalExceptionForGroupError(env, -res, tid);
188 }
189
190 res = set_cpuset_policy(tid, sp);
191 if (res != NO_ERROR) {
192 signalExceptionForGroupError(env, -res, tid);
193 }
194}
195
Elliott Hughes69a017b2011-04-08 14:10:28 -0700196void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
San Mehat3e458242009-05-19 14:44:16 -0700197{
Mark Salyzync6a41012014-04-24 13:05:18 -0700198 ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp);
San Mehat3e458242009-05-19 14:44:16 -0700199 DIR *d;
San Mehat3e458242009-05-19 14:44:16 -0700200 char proc_path[255];
201 struct dirent *de;
202
Glenn Kastenf1b56442012-03-15 16:33:43 -0700203 if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700204 signalExceptionForGroupError(env, EINVAL, pid);
San Mehat3e458242009-05-19 14:44:16 -0700205 return;
206 }
207
Glenn Kastenf1b56442012-03-15 16:33:43 -0700208 bool isDefault = false;
209 if (grp < 0) {
210 grp = SP_FOREGROUND;
211 isDefault = true;
212 }
213 SchedPolicy sp = (SchedPolicy) grp;
214
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800215 if (kDebugPolicy) {
216 char cmdline[32];
217 int fd;
San Mehata5109a82009-10-29 11:48:50 -0700218
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800219 strcpy(cmdline, "unknown");
San Mehata5109a82009-10-29 11:48:50 -0700220
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800221 sprintf(proc_path, "/proc/%d/cmdline", pid);
Nick Kralevich422dd00f2017-10-19 17:51:50 -0700222 fd = open(proc_path, O_RDONLY | O_CLOEXEC);
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800223 if (fd >= 0) {
224 int rc = read(fd, cmdline, sizeof(cmdline)-1);
225 cmdline[rc] = 0;
226 close(fd);
227 }
228
229 if (sp == SP_BACKGROUND) {
230 ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
231 } else {
232 ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
233 }
San Mehata5109a82009-10-29 11:48:50 -0700234 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700235
San Mehat3e458242009-05-19 14:44:16 -0700236 sprintf(proc_path, "/proc/%d/task", pid);
237 if (!(d = opendir(proc_path))) {
San Mehat1fd0ec72009-06-15 16:56:52 -0700238 // If the process exited on us, don't generate an exception
239 if (errno != ENOENT)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700240 signalExceptionForGroupError(env, errno, pid);
San Mehat3e458242009-05-19 14:44:16 -0700241 return;
242 }
243
244 while ((de = readdir(d))) {
San Mehat7e637892009-08-06 13:19:19 -0700245 int t_pid;
246 int t_pri;
247
San Mehat3e458242009-05-19 14:44:16 -0700248 if (de->d_name[0] == '.')
249 continue;
San Mehat7e637892009-08-06 13:19:19 -0700250 t_pid = atoi(de->d_name);
San Mehat1fd0ec72009-06-15 16:56:52 -0700251
San Mehat7e637892009-08-06 13:19:19 -0700252 if (!t_pid) {
Steve Block3762c312012-01-06 19:20:56 +0000253 ALOGE("Error getting pid for '%s'\n", de->d_name);
San Mehat7e637892009-08-06 13:19:19 -0700254 continue;
255 }
256
Glenn Kasten07b04652012-04-23 15:00:43 -0700257 t_pri = getpriority(PRIO_PROCESS, t_pid);
San Mehat7e637892009-08-06 13:19:19 -0700258
Glenn Kasten07b04652012-04-23 15:00:43 -0700259 if (t_pri <= ANDROID_PRIORITY_AUDIO) {
Tim Murray20375fe2016-12-20 11:47:24 -0800260 int scheduler = sched_getscheduler(t_pid) & ~SCHED_RESET_ON_FORK;
Glenn Kasten07b04652012-04-23 15:00:43 -0700261 if ((scheduler == SCHED_FIFO) || (scheduler == SCHED_RR)) {
Tim Murray9e41c742015-06-08 14:56:53 -0700262 // This task wants to stay in its current audio group so it can keep its budget
263 // don't update its cpuset or cgroup
Glenn Kasten07b04652012-04-23 15:00:43 -0700264 continue;
265 }
266 }
267
268 if (isDefault) {
Glenn Kastenf1b56442012-03-15 16:33:43 -0700269 if (t_pri >= ANDROID_PRIORITY_BACKGROUND) {
270 // This task wants to stay at background
Tim Murray9e41c742015-06-08 14:56:53 -0700271 // update its cpuset so it doesn't only run on bg core(s)
Isaac Chend34fac52017-02-16 11:51:08 +0800272 if (cpusets_enabled()) {
273 int err = set_cpuset_policy(t_pid, sp);
274 if (err != NO_ERROR) {
275 signalExceptionForGroupError(env, -err, t_pid);
276 break;
277 }
Tim Murray9e41c742015-06-08 14:56:53 -0700278 }
Glenn Kastenf1b56442012-03-15 16:33:43 -0700279 continue;
280 }
San Mehat7e637892009-08-06 13:19:19 -0700281 }
Tim Murray9e41c742015-06-08 14:56:53 -0700282 int err;
Isaac Chend34fac52017-02-16 11:51:08 +0800283
284 if (cpusets_enabled()) {
285 // set both cpuset and cgroup for general threads
286 err = set_cpuset_policy(t_pid, sp);
287 if (err != NO_ERROR) {
288 signalExceptionForGroupError(env, -err, t_pid);
289 break;
290 }
San Mehat242d65b2009-09-12 10:10:37 -0700291 }
Tim Murray9e41c742015-06-08 14:56:53 -0700292
293 err = set_sched_policy(t_pid, sp);
294 if (err != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700295 signalExceptionForGroupError(env, -err, t_pid);
Tim Murray9e41c742015-06-08 14:56:53 -0700296 break;
297 }
298
San Mehat3e458242009-05-19 14:44:16 -0700299 }
300 closedir(d);
301}
302
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800303jint android_os_Process_getProcessGroup(JNIEnv* env, jobject clazz, jint pid)
304{
305 SchedPolicy sp;
306 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700307 signalExceptionForGroupError(env, errno, pid);
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800308 }
309 return (int) sp;
310}
311
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100312/** Sample CPUset list format:
313 * 0-3,4,6-8
314 */
315static void parse_cpuset_cpus(char *cpus, cpu_set_t *cpu_set) {
316 unsigned int start, end, matched, i;
317 char *cpu_range = strtok(cpus, ",");
318 while (cpu_range != NULL) {
319 start = end = 0;
320 matched = sscanf(cpu_range, "%u-%u", &start, &end);
321 cpu_range = strtok(NULL, ",");
322 if (start >= CPU_SETSIZE) {
323 ALOGE("parse_cpuset_cpus: ignoring CPU number larger than %d.", CPU_SETSIZE);
324 continue;
325 } else if (end >= CPU_SETSIZE) {
326 ALOGE("parse_cpuset_cpus: ignoring CPU numbers larger than %d.", CPU_SETSIZE);
327 end = CPU_SETSIZE - 1;
328 }
329 if (matched == 1) {
330 CPU_SET(start, cpu_set);
331 } else if (matched == 2) {
332 for (i = start; i <= end; i++) {
333 CPU_SET(i, cpu_set);
334 }
335 } else {
336 ALOGE("Failed to match cpus");
337 }
338 }
339 return;
340}
341
342/**
343 * Stores the CPUs assigned to the cpuset corresponding to the
344 * SchedPolicy in the passed in cpu_set.
345 */
346static void get_cpuset_cores_for_policy(SchedPolicy policy, cpu_set_t *cpu_set)
347{
348 FILE *file;
349 const char *filename;
350
351 CPU_ZERO(cpu_set);
352
353 switch (policy) {
354 case SP_BACKGROUND:
355 filename = "/dev/cpuset/background/cpus";
356 break;
357 case SP_FOREGROUND:
358 case SP_AUDIO_APP:
359 case SP_AUDIO_SYS:
Glenn Kasten73a78002017-04-27 15:29:23 -0700360 case SP_RT_APP:
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100361 filename = "/dev/cpuset/foreground/cpus";
362 break;
363 case SP_TOP_APP:
364 filename = "/dev/cpuset/top-app/cpus";
365 break;
366 default:
367 filename = NULL;
368 }
369
370 if (!filename) return;
371
372 file = fopen(filename, "re");
373 if (file != NULL) {
374 // Parse cpus string
375 char *line = NULL;
376 size_t len = 0;
377 ssize_t num_read = getline(&line, &len, file);
378 fclose (file);
379 if (num_read > 0) {
380 parse_cpuset_cpus(line, cpu_set);
381 } else {
382 ALOGE("Failed to read %s", filename);
383 }
384 free(line);
385 }
386 return;
387}
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100388
389
390/**
391 * Determine CPU cores exclusively assigned to the
392 * cpuset corresponding to the SchedPolicy and store
393 * them in the passed in cpu_set_t
394 */
395void get_exclusive_cpuset_cores(SchedPolicy policy, cpu_set_t *cpu_set) {
Isaac Chend34fac52017-02-16 11:51:08 +0800396 if (cpusets_enabled()) {
397 int i;
398 cpu_set_t tmp_set;
399 get_cpuset_cores_for_policy(policy, cpu_set);
400 for (i = 0; i < SP_CNT; i++) {
401 if ((SchedPolicy) i == policy) continue;
402 get_cpuset_cores_for_policy((SchedPolicy)i, &tmp_set);
403 // First get cores exclusive to one set or the other
404 CPU_XOR(&tmp_set, cpu_set, &tmp_set);
405 // Then get the ones only in cpu_set
406 CPU_AND(cpu_set, cpu_set, &tmp_set);
407 }
408 } else {
409 CPU_ZERO(cpu_set);
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100410 }
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100411 return;
412}
413
414jintArray android_os_Process_getExclusiveCores(JNIEnv* env, jobject clazz) {
415 SchedPolicy sp;
416 cpu_set_t cpu_set;
417 jintArray cpus;
418 int pid = getpid();
419 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700420 signalExceptionForGroupError(env, errno, pid);
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100421 return NULL;
422 }
423 get_exclusive_cpuset_cores(sp, &cpu_set);
424 int num_cpus = CPU_COUNT(&cpu_set);
425 cpus = env->NewIntArray(num_cpus);
426 if (cpus == NULL) {
427 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
428 return NULL;
429 }
430
431 jint* cpu_elements = env->GetIntArrayElements(cpus, 0);
432 int count = 0;
433 for (int i = 0; i < CPU_SETSIZE && count < num_cpus; i++) {
434 if (CPU_ISSET(i, &cpu_set)) {
435 cpu_elements[count++] = i;
436 }
437 }
438
439 env->ReleaseIntArrayElements(cpus, cpu_elements, 0);
440 return cpus;
441}
442
Christopher Tate160edb32010-06-30 17:46:30 -0700443static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
444 // Establishes the calling thread as illegal to put into the background.
445 // Typically used only for the system process's main looper.
446#if GUARD_THREAD_PRIORITY
Elliott Hughes06451fe2014-08-18 10:26:52 -0700447 ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
Christopher Tate160edb32010-06-30 17:46:30 -0700448 {
449 Mutex::Autolock _l(gKeyCreateMutex);
450 if (gBgKey == -1) {
451 pthread_key_create(&gBgKey, NULL);
452 }
453 }
454
455 // inverted: not-okay, we set a sentinel value
456 pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
457#endif
458}
459
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700460jint android_os_Process_getThreadScheduler(JNIEnv* env, jclass clazz,
461 jint tid)
462{
463 int policy = 0;
464// linux has sched_getscheduler(), others don't.
465#if defined(__linux__)
466 errno = 0;
467 policy = sched_getscheduler(tid);
468 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700469 signalExceptionForPriorityError(env, errno, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700470 }
471#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700472 signalExceptionForPriorityError(env, ENOSYS, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700473#endif
474 return policy;
475}
476
Glenn Kasten6793ac92011-07-13 12:44:12 -0700477void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
478 jint tid, jint policy, jint pri)
479{
Yabin Cui65b4a682014-11-10 12:15:46 -0800480// linux has sched_setscheduler(), others don't.
481#if defined(__linux__)
Glenn Kasten6793ac92011-07-13 12:44:12 -0700482 struct sched_param param;
483 param.sched_priority = pri;
484 int rc = sched_setscheduler(tid, policy, &param);
485 if (rc) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700486 signalExceptionForPriorityError(env, errno, tid);
Glenn Kasten6793ac92011-07-13 12:44:12 -0700487 }
Glenn Kastencc767192012-01-17 08:38:51 -0800488#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700489 signalExceptionForPriorityError(env, ENOSYS, tid);
Glenn Kastencc767192012-01-17 08:38:51 -0800490#endif
Glenn Kasten6793ac92011-07-13 12:44:12 -0700491}
492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
494 jint pid, jint pri)
495{
Christopher Tate160edb32010-06-30 17:46:30 -0700496#if GUARD_THREAD_PRIORITY
497 // if we're putting the current thread into the background, check the TLS
498 // to make sure this thread isn't guarded. If it is, raise an exception.
499 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Elliott Hughes06451fe2014-08-18 10:26:52 -0700500 if (pid == gettid()) {
Christopher Tate160edb32010-06-30 17:46:30 -0700501 void* bgOk = pthread_getspecific(gBgKey);
502 if (bgOk == ((void*)0xbaad)) {
Steve Block3762c312012-01-06 19:20:56 +0000503 ALOGE("Thread marked fg-only put self in background!");
Christopher Tate160edb32010-06-30 17:46:30 -0700504 jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
505 return;
506 }
507 }
508 }
509#endif
510
Dianne Hackborn887f3552009-12-07 17:59:37 -0800511 int rc = androidSetThreadPriority(pid, pri);
512 if (rc != 0) {
513 if (rc == INVALID_OPERATION) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700514 signalExceptionForPriorityError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800515 } else {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700516 signalExceptionForGroupError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800517 }
San Mehat242d65b2009-09-12 10:10:37 -0700518 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700519
Mark Salyzync6a41012014-04-24 13:05:18 -0700520 //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 // pid, pri, getpriority(PRIO_PROCESS, pid));
522}
523
524void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
525 jint pri)
526{
Elliott Hughes06451fe2014-08-18 10:26:52 -0700527 android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528}
529
530jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
531 jint pid)
532{
533 errno = 0;
534 jint pri = getpriority(PRIO_PROCESS, pid);
535 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700536 signalExceptionForPriorityError(env, errno, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 }
Mark Salyzync6a41012014-04-24 13:05:18 -0700538 //ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 return pri;
540}
541
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700542jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
543 jint pid, jboolean is_increased)
544{
545 char text[64];
546
547 if (is_increased) {
548 strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
549 } else {
550 strcpy(text, "/sys/fs/cgroup/memory/tasks");
551 }
552
553 struct stat st;
554 if (stat(text, &st) || !S_ISREG(st.st_mode)) {
555 return false;
556 }
557
Nick Kralevich422dd00f2017-10-19 17:51:50 -0700558 int fd = open(text, O_WRONLY | O_CLOEXEC);
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700559 if (fd >= 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -0700560 sprintf(text, "%" PRId32, pid);
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700561 write(fd, text, strlen(text));
562 close(fd);
563 }
564
565 return true;
566}
567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
569{
570 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700571 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 return;
573 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 const jchar* str = env->GetStringCritical(name, 0);
576 String8 name8;
577 if (str) {
Dan Albert66987492014-11-20 11:41:21 -0800578 name8 = String8(reinterpret_cast<const char16_t*>(str),
579 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 env->ReleaseStringCritical(name, str);
581 }
582
Dmitriy Filchenko342c7dc2016-07-12 15:40:54 -0700583 if (!name8.isEmpty()) {
Dmitriy Filchenkof5b6e552016-07-18 16:00:35 -0700584 AndroidRuntime::getRuntime()->setArgv0(name8.string(), true /* setProcName */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
586}
587
588jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
589{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 return setuid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591}
592
593jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
594{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 return setgid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596}
597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598static int pid_compare(const void* v1, const void* v2)
599{
Mark Salyzync6a41012014-04-24 13:05:18 -0700600 //ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 return *((const jint*)v1) - *((const jint*)v2);
602}
603
Elliott Hughesc367d482013-10-29 13:12:55 -0700604static jlong getFreeMemoryImpl(const char* const sums[], const size_t sumsLen[], size_t num)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605{
Nick Kralevich422dd00f2017-10-19 17:51:50 -0700606 int fd = open("/proc/meminfo", O_RDONLY | O_CLOEXEC);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 if (fd < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000609 ALOGW("Unable to open /proc/meminfo");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 return -1;
611 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700612
Dianne Hackborne17b4452018-01-10 13:15:40 -0800613 char buffer[2048];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 const int len = read(fd, buffer, sizeof(buffer)-1);
615 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 if (len < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000618 ALOGW("Unable to read /proc/meminfo");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 return -1;
620 }
621 buffer[len] = 0;
622
Elliott Hughesc367d482013-10-29 13:12:55 -0700623 size_t numFound = 0;
Marco Nelissen0bca96b2009-07-17 12:59:25 -0700624 jlong mem = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 char* p = buffer;
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700627 while (*p && numFound < num) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 int i = 0;
629 while (sums[i]) {
630 if (strncmp(p, sums[i], sumsLen[i]) == 0) {
631 p += sumsLen[i];
632 while (*p == ' ') p++;
633 char* num = p;
634 while (*p >= '0' && *p <= '9') p++;
635 if (*p != 0) {
636 *p = 0;
637 p++;
638 if (*p == 0) p--;
639 }
Marco Nelissen0bca96b2009-07-17 12:59:25 -0700640 mem += atoll(num) * 1024;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 numFound++;
642 break;
643 }
644 i++;
645 }
646 p++;
647 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 return numFound > 0 ? mem : -1;
650}
651
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700652static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
653{
654 static const char* const sums[] = { "MemFree:", "Cached:", NULL };
Elliott Hughesc367d482013-10-29 13:12:55 -0700655 static const size_t sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 };
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700656 return getFreeMemoryImpl(sums, sumsLen, 2);
657}
658
659static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
660{
661 static const char* const sums[] = { "MemTotal:", NULL };
Elliott Hughesc367d482013-10-29 13:12:55 -0700662 static const size_t sumsLen[] = { strlen("MemTotal:"), 0 };
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700663 return getFreeMemoryImpl(sums, sumsLen, 1);
664}
665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
667 jobjectArray reqFields, jlongArray outFields)
668{
Steve Block6215d3f2012-01-04 20:05:49 +0000669 //ALOGI("getMemInfo: %p %p", reqFields, outFields);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700672 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 return;
674 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 const char* file8 = env->GetStringUTFChars(fileStr, NULL);
677 if (file8 == NULL) {
678 return;
679 }
680 String8 file(file8);
681 env->ReleaseStringUTFChars(fileStr, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 jsize count = env->GetArrayLength(reqFields);
684 if (count > env->GetArrayLength(outFields)) {
685 jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
686 return;
687 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 Vector<String8> fields;
690 int i;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 for (i=0; i<count; i++) {
693 jobject obj = env->GetObjectArrayElement(reqFields, i);
694 if (obj != NULL) {
695 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
Steve Block6215d3f2012-01-04 20:05:49 +0000696 //ALOGI("String at %d: %p = %s", i, obj, str8);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 if (str8 == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700698 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 return;
700 }
701 fields.add(String8(str8));
702 env->ReleaseStringUTFChars((jstring)obj, str8);
703 } else {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700704 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 return;
706 }
707 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
710 if (sizesArray == NULL) {
711 return;
712 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700713
Mark Salyzync6a41012014-04-24 13:05:18 -0700714 //ALOGI("Clearing %" PRId32 " sizes", count);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 for (i=0; i<count; i++) {
716 sizesArray[i] = 0;
717 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700718
Nick Kralevich422dd00f2017-10-19 17:51:50 -0700719 int fd = open(file.string(), O_RDONLY | O_CLOEXEC);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (fd >= 0) {
Dianne Hackborne17b4452018-01-10 13:15:40 -0800722 const size_t BUFFER_SIZE = 4096;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 char* buffer = (char*)malloc(BUFFER_SIZE);
724 int len = read(fd, buffer, BUFFER_SIZE-1);
725 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 if (len < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000728 ALOGW("Unable to read %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 len = 0;
730 }
731 buffer[len] = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 int foundCount = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 char* p = buffer;
736 while (*p && foundCount < count) {
737 bool skipToEol = true;
Steve Block6215d3f2012-01-04 20:05:49 +0000738 //ALOGI("Parsing at: %s", p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 for (i=0; i<count; i++) {
740 const String8& field = fields[i];
741 if (strncmp(p, field.string(), field.length()) == 0) {
742 p += field.length();
Amith Yamasaniadd868c2009-06-25 11:57:40 -0700743 while (*p == ' ' || *p == '\t') p++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 char* num = p;
745 while (*p >= '0' && *p <= '9') p++;
746 skipToEol = *p != '\n';
747 if (*p != 0) {
748 *p = 0;
749 p++;
750 }
751 char* end;
752 sizesArray[i] = strtoll(num, &end, 10);
Mark Salyzync6a41012014-04-24 13:05:18 -0700753 //ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 foundCount++;
755 break;
756 }
757 }
758 if (skipToEol) {
759 while (*p && *p != '\n') {
760 p++;
761 }
762 if (*p == '\n') {
763 p++;
764 }
765 }
766 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 free(buffer);
769 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000770 ALOGW("Unable to open %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700772
Steve Block6215d3f2012-01-04 20:05:49 +0000773 //ALOGI("Done!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 env->ReleaseLongArrayElements(outFields, sizesArray, 0);
775}
776
777jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
778 jstring file, jintArray lastArray)
779{
780 if (file == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700781 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 return NULL;
783 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 const char* file8 = env->GetStringUTFChars(file, NULL);
786 if (file8 == NULL) {
787 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
788 return NULL;
789 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 DIR* dirp = opendir(file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 if(dirp == NULL) {
796 return NULL;
797 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 jsize curCount = 0;
800 jint* curData = NULL;
801 if (lastArray != NULL) {
802 curCount = env->GetArrayLength(lastArray);
803 curData = env->GetIntArrayElements(lastArray, 0);
804 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 jint curPos = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 struct dirent* entry;
809 while ((entry=readdir(dirp)) != NULL) {
810 const char* p = entry->d_name;
811 while (*p) {
812 if (*p < '0' || *p > '9') break;
813 p++;
814 }
815 if (*p != 0) continue;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 char* end;
818 int pid = strtol(entry->d_name, &end, 10);
Steve Block6215d3f2012-01-04 20:05:49 +0000819 //ALOGI("File %s pid=%d\n", entry->d_name, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 if (curPos >= curCount) {
821 jsize newCount = (curCount == 0) ? 10 : (curCount*2);
822 jintArray newArray = env->NewIntArray(newCount);
823 if (newArray == NULL) {
824 closedir(dirp);
825 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
826 return NULL;
827 }
828 jint* newData = env->GetIntArrayElements(newArray, 0);
829 if (curData != NULL) {
830 memcpy(newData, curData, sizeof(jint)*curCount);
831 env->ReleaseIntArrayElements(lastArray, curData, 0);
832 }
833 lastArray = newArray;
834 curCount = newCount;
835 curData = newData;
836 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 curData[curPos] = pid;
839 curPos++;
840 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 closedir(dirp);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 if (curData != NULL && curPos > 0) {
845 qsort(curData, curPos, sizeof(jint), pid_compare);
846 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 while (curPos < curCount) {
849 curData[curPos] = -1;
850 curPos++;
851 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 if (curData != NULL) {
854 env->ReleaseIntArrayElements(lastArray, curData, 0);
855 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 return lastArray;
858}
859
860enum {
861 PROC_TERM_MASK = 0xff,
862 PROC_ZERO_TERM = 0,
863 PROC_SPACE_TERM = ' ',
864 PROC_COMBINE = 0x100,
865 PROC_PARENS = 0x200,
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700866 PROC_QUOTES = 0x400,
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700867 PROC_CHAR = 0x800,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 PROC_OUT_STRING = 0x1000,
869 PROC_OUT_LONG = 0x2000,
870 PROC_OUT_FLOAT = 0x4000,
871};
872
Evan Millarc64edde2009-04-18 12:26:32 -0700873jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700874 char* buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700875 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876{
Elliott Hughes69a017b2011-04-08 14:10:28 -0700877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 const jsize NF = env->GetArrayLength(format);
879 const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
880 const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
881 const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 jint* formatData = env->GetIntArrayElements(format, 0);
884 jlong* longsData = outLongs ?
885 env->GetLongArrayElements(outLongs, 0) : NULL;
886 jfloat* floatsData = outFloats ?
887 env->GetFloatArrayElements(outFloats, 0) : NULL;
888 if (formatData == NULL || (NL > 0 && longsData == NULL)
889 || (NR > 0 && floatsData == NULL)) {
890 if (formatData != NULL) {
891 env->ReleaseIntArrayElements(format, formatData, 0);
892 }
893 if (longsData != NULL) {
894 env->ReleaseLongArrayElements(outLongs, longsData, 0);
895 }
896 if (floatsData != NULL) {
897 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
898 }
899 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
900 return JNI_FALSE;
901 }
902
Evan Millarc64edde2009-04-18 12:26:32 -0700903 jsize i = startIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 jsize di = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 jboolean res = JNI_TRUE;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 for (jsize fi=0; fi<NF; fi++) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700909 jint mode = formatData[fi];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 if ((mode&PROC_PARENS) != 0) {
911 i++;
Bernhard Rosenkränzer3b1e22e2014-11-17 22:30:56 +0100912 } else if ((mode&PROC_QUOTES) != 0) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700913 if (buffer[i] == '"') {
914 i++;
915 } else {
916 mode &= ~PROC_QUOTES;
917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
919 const char term = (char)(mode&PROC_TERM_MASK);
920 const jsize start = i;
Evan Millarc64edde2009-04-18 12:26:32 -0700921 if (i >= endIndex) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800922 if (kDebugProc) {
923 ALOGW("Ran off end of data @%d", i);
924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 res = JNI_FALSE;
926 break;
927 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 jsize end = -1;
930 if ((mode&PROC_PARENS) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700931 while (i < endIndex && buffer[i] != ')') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 i++;
933 }
934 end = i;
935 i++;
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700936 } else if ((mode&PROC_QUOTES) != 0) {
937 while (buffer[i] != '"' && i < endIndex) {
938 i++;
939 }
940 end = i;
941 i++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700943 while (i < endIndex && buffer[i] != term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 i++;
945 }
946 if (end < 0) {
947 end = i;
948 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700949
Evan Millarc64edde2009-04-18 12:26:32 -0700950 if (i < endIndex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 i++;
952 if ((mode&PROC_COMBINE) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700953 while (i < endIndex && buffer[i] == term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 i++;
955 }
956 }
957 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700958
Mark Salyzync6a41012014-04-24 13:05:18 -0700959 //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
962 char c = buffer[end];
963 buffer[end] = 0;
964 if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
965 char* end;
966 floatsData[di] = strtof(buffer+start, &end);
967 }
968 if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700969 if ((mode&PROC_CHAR) != 0) {
970 // Caller wants single first character returned as one long.
971 longsData[di] = buffer[start];
972 } else {
973 char* end;
974 longsData[di] = strtoll(buffer+start, &end, 10);
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977 if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
978 jstring str = env->NewStringUTF(buffer+start);
979 env->SetObjectArrayElement(outStrings, di, str);
980 }
981 buffer[end] = c;
982 di++;
983 }
984 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 env->ReleaseIntArrayElements(format, formatData, 0);
987 if (longsData != NULL) {
988 env->ReleaseLongArrayElements(outLongs, longsData, 0);
989 }
990 if (floatsData != NULL) {
991 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
992 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 return res;
995}
996
Evan Millarc64edde2009-04-18 12:26:32 -0700997jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700998 jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700999 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
1000{
1001 jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
1002
Elliott Hughes69a017b2011-04-08 14:10:28 -07001003 jboolean result = android_os_Process_parseProcLineArray(env, clazz,
1004 (char*) bufferArray, startIndex, endIndex, format, outStrings,
Evan Millarc64edde2009-04-18 12:26:32 -07001005 outLongs, outFloats);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001006
Evan Millarc64edde2009-04-18 12:26:32 -07001007 env->ReleaseByteArrayElements(buffer, bufferArray, 0);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001008
Evan Millarc64edde2009-04-18 12:26:32 -07001009 return result;
1010}
1011
1012jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
1013 jstring file, jintArray format, jobjectArray outStrings,
1014 jlongArray outLongs, jfloatArray outFloats)
1015{
1016 if (file == NULL || format == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001017 jniThrowNullPointerException(env, NULL);
Evan Millarc64edde2009-04-18 12:26:32 -07001018 return JNI_FALSE;
1019 }
1020
1021 const char* file8 = env->GetStringUTFChars(file, NULL);
1022 if (file8 == NULL) {
1023 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1024 return JNI_FALSE;
1025 }
Nick Kralevich422dd00f2017-10-19 17:51:50 -07001026 int fd = open(file8, O_RDONLY | O_CLOEXEC);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001027
Evan Millarc64edde2009-04-18 12:26:32 -07001028 if (fd < 0) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001029 if (kDebugProc) {
1030 ALOGW("Unable to open process file: %s\n", file8);
1031 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001032 env->ReleaseStringUTFChars(file, file8);
Evan Millarc64edde2009-04-18 12:26:32 -07001033 return JNI_FALSE;
1034 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001035 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001036
Evan Millarc64edde2009-04-18 12:26:32 -07001037 char buffer[256];
1038 const int len = read(fd, buffer, sizeof(buffer)-1);
1039 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001040
Evan Millarc64edde2009-04-18 12:26:32 -07001041 if (len < 0) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001042 if (kDebugProc) {
1043 ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
1044 }
Evan Millarc64edde2009-04-18 12:26:32 -07001045 return JNI_FALSE;
1046 }
1047 buffer[len] = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -07001048
1049 return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
Evan Millarc64edde2009-04-18 12:26:32 -07001050 format, outStrings, outLongs, outFloats);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001051
Evan Millarc64edde2009-04-18 12:26:32 -07001052}
1053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
1055 jobject binderObject)
1056{
1057 if (binderObject == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001058 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 return;
1060 }
1061
1062 sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
1063}
1064
1065void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
1066{
1067 if (pid > 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -07001068 ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 kill(pid, sig);
1070 }
1071}
1072
Dianne Hackborn906497c2010-05-10 15:57:38 -07001073void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
1074{
1075 if (pid > 0) {
1076 kill(pid, sig);
1077 }
1078}
1079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
1081{
1082 struct timespec ts;
1083
1084 int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 if (res != 0) {
1087 return (jlong) 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -07001088 }
1089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
1091 return (jlong) nanoseconds_to_milliseconds(when);
1092}
1093
1094static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
1095{
Daniel Colascione6c518102017-07-27 03:33:34 -07001096 UniqueFile file = OpenSmapsOrRollup(pid);
1097 if (file == nullptr) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 return (jlong) -1;
1099 }
1100
1101 // Tally up all of the Pss from the various maps
1102 char line[256];
1103 jlong pss = 0;
Daniel Colascione6c518102017-07-27 03:33:34 -07001104 while (fgets(line, sizeof(line), file.get())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 jlong v;
Mark Salyzync6a41012014-04-24 13:05:18 -07001106 if (sscanf(line, "Pss: %" SCNd64 " kB", &v) == 1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 pss += v;
1108 }
1109 }
1110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 // Return the Pss value in bytes, not kilobytes
1112 return pss * 1024;
1113}
1114
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001115jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
1116 jobjectArray commandNames)
1117{
1118 if (commandNames == NULL) {
1119 jniThrowNullPointerException(env, NULL);
1120 return NULL;
1121 }
1122
1123 Vector<String8> commands;
1124
1125 jsize count = env->GetArrayLength(commandNames);
1126
1127 for (int i=0; i<count; i++) {
1128 jobject obj = env->GetObjectArrayElement(commandNames, i);
1129 if (obj != NULL) {
1130 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
1131 if (str8 == NULL) {
1132 jniThrowNullPointerException(env, "Element in commandNames");
1133 return NULL;
1134 }
1135 commands.add(String8(str8));
1136 env->ReleaseStringUTFChars((jstring)obj, str8);
1137 } else {
1138 jniThrowNullPointerException(env, "Element in commandNames");
1139 return NULL;
1140 }
1141 }
1142
1143 Vector<jint> pids;
1144
1145 DIR *proc = opendir("/proc");
1146 if (proc == NULL) {
1147 fprintf(stderr, "/proc: %s\n", strerror(errno));
1148 return NULL;
1149 }
1150
1151 struct dirent *d;
1152 while ((d = readdir(proc))) {
1153 int pid = atoi(d->d_name);
1154 if (pid <= 0) continue;
1155
1156 char path[PATH_MAX];
1157 char data[PATH_MAX];
1158 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
1159
Nick Kralevich422dd00f2017-10-19 17:51:50 -07001160 int fd = open(path, O_RDONLY | O_CLOEXEC);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001161 if (fd < 0) {
1162 continue;
1163 }
1164 const int len = read(fd, data, sizeof(data)-1);
1165 close(fd);
1166
1167 if (len < 0) {
1168 continue;
1169 }
1170 data[len] = 0;
1171
1172 for (int i=0; i<len; i++) {
1173 if (data[i] == ' ') {
1174 data[i] = 0;
1175 break;
1176 }
1177 }
1178
1179 for (size_t i=0; i<commands.size(); i++) {
1180 if (commands[i] == data) {
1181 pids.add(pid);
1182 break;
1183 }
1184 }
1185 }
1186
1187 closedir(proc);
1188
1189 jintArray pidArray = env->NewIntArray(pids.size());
1190 if (pidArray == NULL) {
1191 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1192 return NULL;
1193 }
1194
1195 if (pids.size() > 0) {
1196 env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
1197 }
1198
1199 return pidArray;
1200}
1201
Colin Cross0769e552014-06-03 13:25:35 -07001202jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
1203{
1204 return killProcessGroup(uid, pid, SIGKILL);
1205}
1206
1207void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
1208{
1209 return removeAllProcessGroups();
1210}
1211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212static const JNINativeMethod methods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 {"getUidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
1214 {"getGidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
1215 {"setThreadPriority", "(II)V", (void*)android_os_Process_setThreadPriority},
Glenn Kasten6793ac92011-07-13 12:44:12 -07001216 {"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler},
Christopher Tate160edb32010-06-30 17:46:30 -07001217 {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 {"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority},
1219 {"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority},
Srinath Sridharan1b15d132016-07-19 15:16:11 -07001220 {"getThreadScheduler", "(I)I", (void*)android_os_Process_getThreadScheduler},
San Mehate9d376b2009-04-21 14:06:36 -07001221 {"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup},
Joel Fernandes474d3112017-04-04 16:32:15 -07001222 {"setThreadGroupAndCpuset", "(II)V", (void*)android_os_Process_setThreadGroupAndCpuset},
Jeff Sharkey9e57c412013-01-17 14:12:41 -08001223 {"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup},
1224 {"getProcessGroup", "(I)I", (void*)android_os_Process_getProcessGroup},
Martijn Coenencd4bdf32016-03-03 17:30:52 +01001225 {"getExclusiveCores", "()[I", (void*)android_os_Process_getExclusiveCores},
Rom Lemarchand5534ba92013-07-12 16:15:36 -07001226 {"setSwappiness", "(IZ)Z", (void*)android_os_Process_setSwappiness},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 {"setArgV0", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
1228 {"setUid", "(I)I", (void*)android_os_Process_setUid},
1229 {"setGid", "(I)I", (void*)android_os_Process_setGid},
1230 {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
Dianne Hackborn906497c2010-05-10 15:57:38 -07001231 {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
Marco Nelissen0bca96b2009-07-17 12:59:25 -07001232 {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
Dianne Hackborn59325eb2012-05-09 18:45:20 -07001233 {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
1235 {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
1236 {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
Evan Millarc64edde2009-04-18 12:26:32 -07001237 {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
1239 {"getPss", "(I)J", (void*)android_os_Process_getPss},
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001240 {"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
Colin Cross0769e552014-06-03 13:25:35 -07001242 {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
1243 {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244};
1245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246int register_android_os_Process(JNIEnv* env)
1247{
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001248 return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249}