blob: f34b1389c35893955989143eba1cb051272d0930 [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"
33#include "JNIHelp.h"
34
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035#include <dirent.h>
36#include <fcntl.h>
37#include <grp.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070038#include <inttypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039#include <pwd.h>
40#include <signal.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070041#include <sys/errno.h>
42#include <sys/resource.h>
43#include <sys/stat.h>
44#include <sys/types.h>
Glenn Kasten6af763b2011-05-04 17:58:57 -070045#include <unistd.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
Christopher Tate160edb32010-06-30 17:46:30 -070047#define GUARD_THREAD_PRIORITY 0
San Mehata5109a82009-10-29 11:48:50 -070048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049using namespace android;
50
Andreas Gampe0f0b4912014-11-12 08:03:48 -080051static const bool kDebugPolicy = false;
52static const bool kDebugProc = false;
53
Christopher Tate160edb32010-06-30 17:46:30 -070054#if GUARD_THREAD_PRIORITY
55Mutex gKeyCreateMutex;
56static pthread_key_t gBgKey = -1;
57#endif
58
Glenn Kastenf1b56442012-03-15 16:33:43 -070059// For both of these, err should be in the errno range (positive), not a status_t (negative)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070060static void signalExceptionForError(JNIEnv* env, int err, int tid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 switch (err) {
62 case EINVAL:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070063 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
64 "Invalid argument: %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 break;
66 case ESRCH:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070067 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
68 "Given thread %d does not exist", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 break;
70 case EPERM:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070071 jniThrowExceptionFmt(env, "java/lang/SecurityException",
72 "No permission to modify given thread %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 break;
74 default:
75 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
76 break;
77 }
78}
79
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070080static void signalExceptionForPriorityError(JNIEnv* env, int err, int tid) {
San Mehate9d376b2009-04-21 14:06:36 -070081 switch (err) {
San Mehate9d376b2009-04-21 14:06:36 -070082 case EACCES:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070083 jniThrowExceptionFmt(env, "java/lang/SecurityException",
84 "No permission to set the priority of %d", tid);
San Mehate9d376b2009-04-21 14:06:36 -070085 break;
86 default:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070087 signalExceptionForError(env, err, tid);
88 break;
89 }
90
91}
92
93static void signalExceptionForGroupError(JNIEnv* env, int err, int tid) {
94 switch (err) {
95 case EACCES:
96 jniThrowExceptionFmt(env, "java/lang/SecurityException",
97 "No permission to set the group of %d", tid);
98 break;
99 default:
100 signalExceptionForError(env, err, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700101 break;
102 }
103}
104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
106{
107 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700108 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 return -1;
110 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 const jchar* str16 = env->GetStringCritical(name, 0);
113 String8 name8;
114 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800115 name8 = String8(reinterpret_cast<const char16_t*>(str16),
116 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 env->ReleaseStringCritical(name, str16);
118 }
119
120 const size_t N = name8.size();
121 if (N > 0) {
122 const char* str = name8.string();
123 for (size_t i=0; i<N; i++) {
124 if (str[i] < '0' || str[i] > '9') {
125 struct passwd* pwd = getpwnam(str);
126 if (pwd == NULL) {
127 return -1;
128 }
129 return pwd->pw_uid;
130 }
131 }
132 return atoi(str);
133 }
134 return -1;
135}
136
137jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
138{
139 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700140 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 return -1;
142 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 const jchar* str16 = env->GetStringCritical(name, 0);
145 String8 name8;
146 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800147 name8 = String8(reinterpret_cast<const char16_t*>(str16),
148 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 env->ReleaseStringCritical(name, str16);
150 }
151
152 const size_t N = name8.size();
153 if (N > 0) {
154 const char* str = name8.string();
155 for (size_t i=0; i<N; i++) {
156 if (str[i] < '0' || str[i] > '9') {
157 struct group* grp = getgrnam(str);
158 if (grp == NULL) {
159 return -1;
160 }
161 return grp->gr_gid;
162 }
163 }
164 return atoi(str);
165 }
166 return -1;
167}
168
Glenn Kastenf1b56442012-03-15 16:33:43 -0700169void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int tid, jint grp)
San Mehate9d376b2009-04-21 14:06:36 -0700170{
Mark Salyzync6a41012014-04-24 13:05:18 -0700171 ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
Glenn Kastenf1b56442012-03-15 16:33:43 -0700172 SchedPolicy sp = (SchedPolicy) grp;
173 int res = set_sched_policy(tid, sp);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800174 if (res != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700175 signalExceptionForGroupError(env, -res, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700176 }
San Mehate9d376b2009-04-21 14:06:36 -0700177}
178
Joel Fernandes474d3112017-04-04 16:32:15 -0700179void android_os_Process_setThreadGroupAndCpuset(JNIEnv* env, jobject clazz, int tid, jint grp)
180{
181 ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
182 SchedPolicy sp = (SchedPolicy) grp;
183 int res = set_sched_policy(tid, sp);
184
185 if (res != NO_ERROR) {
186 signalExceptionForGroupError(env, -res, tid);
187 }
188
189 res = set_cpuset_policy(tid, sp);
190 if (res != NO_ERROR) {
191 signalExceptionForGroupError(env, -res, tid);
192 }
193}
194
Elliott Hughes69a017b2011-04-08 14:10:28 -0700195void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
San Mehat3e458242009-05-19 14:44:16 -0700196{
Mark Salyzync6a41012014-04-24 13:05:18 -0700197 ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp);
San Mehat3e458242009-05-19 14:44:16 -0700198 DIR *d;
San Mehat3e458242009-05-19 14:44:16 -0700199 char proc_path[255];
200 struct dirent *de;
201
Glenn Kastenf1b56442012-03-15 16:33:43 -0700202 if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700203 signalExceptionForGroupError(env, EINVAL, pid);
San Mehat3e458242009-05-19 14:44:16 -0700204 return;
205 }
206
Glenn Kastenf1b56442012-03-15 16:33:43 -0700207 bool isDefault = false;
208 if (grp < 0) {
209 grp = SP_FOREGROUND;
210 isDefault = true;
211 }
212 SchedPolicy sp = (SchedPolicy) grp;
213
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800214 if (kDebugPolicy) {
215 char cmdline[32];
216 int fd;
San Mehata5109a82009-10-29 11:48:50 -0700217
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800218 strcpy(cmdline, "unknown");
San Mehata5109a82009-10-29 11:48:50 -0700219
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800220 sprintf(proc_path, "/proc/%d/cmdline", pid);
221 fd = open(proc_path, O_RDONLY);
222 if (fd >= 0) {
223 int rc = read(fd, cmdline, sizeof(cmdline)-1);
224 cmdline[rc] = 0;
225 close(fd);
226 }
227
228 if (sp == SP_BACKGROUND) {
229 ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
230 } else {
231 ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
232 }
San Mehata5109a82009-10-29 11:48:50 -0700233 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700234
San Mehat3e458242009-05-19 14:44:16 -0700235 sprintf(proc_path, "/proc/%d/task", pid);
236 if (!(d = opendir(proc_path))) {
San Mehat1fd0ec72009-06-15 16:56:52 -0700237 // If the process exited on us, don't generate an exception
238 if (errno != ENOENT)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700239 signalExceptionForGroupError(env, errno, pid);
San Mehat3e458242009-05-19 14:44:16 -0700240 return;
241 }
242
243 while ((de = readdir(d))) {
San Mehat7e637892009-08-06 13:19:19 -0700244 int t_pid;
245 int t_pri;
246
San Mehat3e458242009-05-19 14:44:16 -0700247 if (de->d_name[0] == '.')
248 continue;
San Mehat7e637892009-08-06 13:19:19 -0700249 t_pid = atoi(de->d_name);
San Mehat1fd0ec72009-06-15 16:56:52 -0700250
San Mehat7e637892009-08-06 13:19:19 -0700251 if (!t_pid) {
Steve Block3762c312012-01-06 19:20:56 +0000252 ALOGE("Error getting pid for '%s'\n", de->d_name);
San Mehat7e637892009-08-06 13:19:19 -0700253 continue;
254 }
255
Glenn Kasten07b04652012-04-23 15:00:43 -0700256 t_pri = getpriority(PRIO_PROCESS, t_pid);
San Mehat7e637892009-08-06 13:19:19 -0700257
Glenn Kasten07b04652012-04-23 15:00:43 -0700258 if (t_pri <= ANDROID_PRIORITY_AUDIO) {
Tim Murray20375fe2016-12-20 11:47:24 -0800259 int scheduler = sched_getscheduler(t_pid) & ~SCHED_RESET_ON_FORK;
Glenn Kasten07b04652012-04-23 15:00:43 -0700260 if ((scheduler == SCHED_FIFO) || (scheduler == SCHED_RR)) {
Tim Murray9e41c742015-06-08 14:56:53 -0700261 // This task wants to stay in its current audio group so it can keep its budget
262 // don't update its cpuset or cgroup
Glenn Kasten07b04652012-04-23 15:00:43 -0700263 continue;
264 }
265 }
266
267 if (isDefault) {
Glenn Kastenf1b56442012-03-15 16:33:43 -0700268 if (t_pri >= ANDROID_PRIORITY_BACKGROUND) {
269 // This task wants to stay at background
Tim Murray9e41c742015-06-08 14:56:53 -0700270 // update its cpuset so it doesn't only run on bg core(s)
Isaac Chend34fac52017-02-16 11:51:08 +0800271 if (cpusets_enabled()) {
272 int err = set_cpuset_policy(t_pid, sp);
273 if (err != NO_ERROR) {
274 signalExceptionForGroupError(env, -err, t_pid);
275 break;
276 }
Tim Murray9e41c742015-06-08 14:56:53 -0700277 }
Glenn Kastenf1b56442012-03-15 16:33:43 -0700278 continue;
279 }
San Mehat7e637892009-08-06 13:19:19 -0700280 }
Tim Murray9e41c742015-06-08 14:56:53 -0700281 int err;
Isaac Chend34fac52017-02-16 11:51:08 +0800282
283 if (cpusets_enabled()) {
284 // set both cpuset and cgroup for general threads
285 err = set_cpuset_policy(t_pid, sp);
286 if (err != NO_ERROR) {
287 signalExceptionForGroupError(env, -err, t_pid);
288 break;
289 }
San Mehat242d65b2009-09-12 10:10:37 -0700290 }
Tim Murray9e41c742015-06-08 14:56:53 -0700291
292 err = set_sched_policy(t_pid, sp);
293 if (err != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700294 signalExceptionForGroupError(env, -err, t_pid);
Tim Murray9e41c742015-06-08 14:56:53 -0700295 break;
296 }
297
San Mehat3e458242009-05-19 14:44:16 -0700298 }
299 closedir(d);
300}
301
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800302jint android_os_Process_getProcessGroup(JNIEnv* env, jobject clazz, jint pid)
303{
304 SchedPolicy sp;
305 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700306 signalExceptionForGroupError(env, errno, pid);
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800307 }
308 return (int) sp;
309}
310
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100311/** Sample CPUset list format:
312 * 0-3,4,6-8
313 */
314static void parse_cpuset_cpus(char *cpus, cpu_set_t *cpu_set) {
315 unsigned int start, end, matched, i;
316 char *cpu_range = strtok(cpus, ",");
317 while (cpu_range != NULL) {
318 start = end = 0;
319 matched = sscanf(cpu_range, "%u-%u", &start, &end);
320 cpu_range = strtok(NULL, ",");
321 if (start >= CPU_SETSIZE) {
322 ALOGE("parse_cpuset_cpus: ignoring CPU number larger than %d.", CPU_SETSIZE);
323 continue;
324 } else if (end >= CPU_SETSIZE) {
325 ALOGE("parse_cpuset_cpus: ignoring CPU numbers larger than %d.", CPU_SETSIZE);
326 end = CPU_SETSIZE - 1;
327 }
328 if (matched == 1) {
329 CPU_SET(start, cpu_set);
330 } else if (matched == 2) {
331 for (i = start; i <= end; i++) {
332 CPU_SET(i, cpu_set);
333 }
334 } else {
335 ALOGE("Failed to match cpus");
336 }
337 }
338 return;
339}
340
341/**
342 * Stores the CPUs assigned to the cpuset corresponding to the
343 * SchedPolicy in the passed in cpu_set.
344 */
345static void get_cpuset_cores_for_policy(SchedPolicy policy, cpu_set_t *cpu_set)
346{
347 FILE *file;
348 const char *filename;
349
350 CPU_ZERO(cpu_set);
351
352 switch (policy) {
353 case SP_BACKGROUND:
354 filename = "/dev/cpuset/background/cpus";
355 break;
356 case SP_FOREGROUND:
357 case SP_AUDIO_APP:
358 case SP_AUDIO_SYS:
Glenn Kasten73a78002017-04-27 15:29:23 -0700359 case SP_RT_APP:
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100360 filename = "/dev/cpuset/foreground/cpus";
361 break;
362 case SP_TOP_APP:
363 filename = "/dev/cpuset/top-app/cpus";
364 break;
365 default:
366 filename = NULL;
367 }
368
369 if (!filename) return;
370
371 file = fopen(filename, "re");
372 if (file != NULL) {
373 // Parse cpus string
374 char *line = NULL;
375 size_t len = 0;
376 ssize_t num_read = getline(&line, &len, file);
377 fclose (file);
378 if (num_read > 0) {
379 parse_cpuset_cpus(line, cpu_set);
380 } else {
381 ALOGE("Failed to read %s", filename);
382 }
383 free(line);
384 }
385 return;
386}
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100387
388
389/**
390 * Determine CPU cores exclusively assigned to the
391 * cpuset corresponding to the SchedPolicy and store
392 * them in the passed in cpu_set_t
393 */
394void get_exclusive_cpuset_cores(SchedPolicy policy, cpu_set_t *cpu_set) {
Isaac Chend34fac52017-02-16 11:51:08 +0800395 if (cpusets_enabled()) {
396 int i;
397 cpu_set_t tmp_set;
398 get_cpuset_cores_for_policy(policy, cpu_set);
399 for (i = 0; i < SP_CNT; i++) {
400 if ((SchedPolicy) i == policy) continue;
401 get_cpuset_cores_for_policy((SchedPolicy)i, &tmp_set);
402 // First get cores exclusive to one set or the other
403 CPU_XOR(&tmp_set, cpu_set, &tmp_set);
404 // Then get the ones only in cpu_set
405 CPU_AND(cpu_set, cpu_set, &tmp_set);
406 }
407 } else {
408 CPU_ZERO(cpu_set);
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100409 }
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100410 return;
411}
412
413jintArray android_os_Process_getExclusiveCores(JNIEnv* env, jobject clazz) {
414 SchedPolicy sp;
415 cpu_set_t cpu_set;
416 jintArray cpus;
417 int pid = getpid();
418 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700419 signalExceptionForGroupError(env, errno, pid);
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100420 return NULL;
421 }
422 get_exclusive_cpuset_cores(sp, &cpu_set);
423 int num_cpus = CPU_COUNT(&cpu_set);
424 cpus = env->NewIntArray(num_cpus);
425 if (cpus == NULL) {
426 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
427 return NULL;
428 }
429
430 jint* cpu_elements = env->GetIntArrayElements(cpus, 0);
431 int count = 0;
432 for (int i = 0; i < CPU_SETSIZE && count < num_cpus; i++) {
433 if (CPU_ISSET(i, &cpu_set)) {
434 cpu_elements[count++] = i;
435 }
436 }
437
438 env->ReleaseIntArrayElements(cpus, cpu_elements, 0);
439 return cpus;
440}
441
Christopher Tate160edb32010-06-30 17:46:30 -0700442static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
443 // Establishes the calling thread as illegal to put into the background.
444 // Typically used only for the system process's main looper.
445#if GUARD_THREAD_PRIORITY
Elliott Hughes06451fe2014-08-18 10:26:52 -0700446 ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
Christopher Tate160edb32010-06-30 17:46:30 -0700447 {
448 Mutex::Autolock _l(gKeyCreateMutex);
449 if (gBgKey == -1) {
450 pthread_key_create(&gBgKey, NULL);
451 }
452 }
453
454 // inverted: not-okay, we set a sentinel value
455 pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
456#endif
457}
458
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700459jint android_os_Process_getThreadScheduler(JNIEnv* env, jclass clazz,
460 jint tid)
461{
462 int policy = 0;
463// linux has sched_getscheduler(), others don't.
464#if defined(__linux__)
465 errno = 0;
466 policy = sched_getscheduler(tid);
467 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700468 signalExceptionForPriorityError(env, errno, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700469 }
470#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700471 signalExceptionForPriorityError(env, ENOSYS, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700472#endif
473 return policy;
474}
475
Glenn Kasten6793ac92011-07-13 12:44:12 -0700476void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
477 jint tid, jint policy, jint pri)
478{
Yabin Cui65b4a682014-11-10 12:15:46 -0800479// linux has sched_setscheduler(), others don't.
480#if defined(__linux__)
Glenn Kasten6793ac92011-07-13 12:44:12 -0700481 struct sched_param param;
482 param.sched_priority = pri;
483 int rc = sched_setscheduler(tid, policy, &param);
484 if (rc) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700485 signalExceptionForPriorityError(env, errno, tid);
Glenn Kasten6793ac92011-07-13 12:44:12 -0700486 }
Glenn Kastencc767192012-01-17 08:38:51 -0800487#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700488 signalExceptionForPriorityError(env, ENOSYS, tid);
Glenn Kastencc767192012-01-17 08:38:51 -0800489#endif
Glenn Kasten6793ac92011-07-13 12:44:12 -0700490}
491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
493 jint pid, jint pri)
494{
Christopher Tate160edb32010-06-30 17:46:30 -0700495#if GUARD_THREAD_PRIORITY
496 // if we're putting the current thread into the background, check the TLS
497 // to make sure this thread isn't guarded. If it is, raise an exception.
498 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Elliott Hughes06451fe2014-08-18 10:26:52 -0700499 if (pid == gettid()) {
Christopher Tate160edb32010-06-30 17:46:30 -0700500 void* bgOk = pthread_getspecific(gBgKey);
501 if (bgOk == ((void*)0xbaad)) {
Steve Block3762c312012-01-06 19:20:56 +0000502 ALOGE("Thread marked fg-only put self in background!");
Christopher Tate160edb32010-06-30 17:46:30 -0700503 jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
504 return;
505 }
506 }
507 }
508#endif
509
Dianne Hackborn887f3552009-12-07 17:59:37 -0800510 int rc = androidSetThreadPriority(pid, pri);
511 if (rc != 0) {
512 if (rc == INVALID_OPERATION) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700513 signalExceptionForPriorityError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800514 } else {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700515 signalExceptionForGroupError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800516 }
San Mehat242d65b2009-09-12 10:10:37 -0700517 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700518
Mark Salyzync6a41012014-04-24 13:05:18 -0700519 //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 // pid, pri, getpriority(PRIO_PROCESS, pid));
521}
522
523void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
524 jint pri)
525{
Elliott Hughes06451fe2014-08-18 10:26:52 -0700526 android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527}
528
529jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
530 jint pid)
531{
532 errno = 0;
533 jint pri = getpriority(PRIO_PROCESS, pid);
534 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700535 signalExceptionForPriorityError(env, errno, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 }
Mark Salyzync6a41012014-04-24 13:05:18 -0700537 //ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 return pri;
539}
540
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700541jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
542 jint pid, jboolean is_increased)
543{
544 char text[64];
545
546 if (is_increased) {
547 strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
548 } else {
549 strcpy(text, "/sys/fs/cgroup/memory/tasks");
550 }
551
552 struct stat st;
553 if (stat(text, &st) || !S_ISREG(st.st_mode)) {
554 return false;
555 }
556
557 int fd = open(text, O_WRONLY);
558 if (fd >= 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -0700559 sprintf(text, "%" PRId32, pid);
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700560 write(fd, text, strlen(text));
561 close(fd);
562 }
563
564 return true;
565}
566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
568{
569 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700570 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 return;
572 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 const jchar* str = env->GetStringCritical(name, 0);
575 String8 name8;
576 if (str) {
Dan Albert66987492014-11-20 11:41:21 -0800577 name8 = String8(reinterpret_cast<const char16_t*>(str),
578 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 env->ReleaseStringCritical(name, str);
580 }
581
Dmitriy Filchenko342c7dc2016-07-12 15:40:54 -0700582 if (!name8.isEmpty()) {
Dmitriy Filchenkof5b6e552016-07-18 16:00:35 -0700583 AndroidRuntime::getRuntime()->setArgv0(name8.string(), true /* setProcName */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 }
585}
586
587jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
588{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 return setuid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590}
591
592jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
593{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 return setgid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595}
596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597static int pid_compare(const void* v1, const void* v2)
598{
Mark Salyzync6a41012014-04-24 13:05:18 -0700599 //ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 return *((const jint*)v1) - *((const jint*)v2);
601}
602
Elliott Hughesc367d482013-10-29 13:12:55 -0700603static jlong getFreeMemoryImpl(const char* const sums[], const size_t sumsLen[], size_t num)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604{
605 int fd = open("/proc/meminfo", O_RDONLY);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 if (fd < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000608 ALOGW("Unable to open /proc/meminfo");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 return -1;
610 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 char buffer[256];
613 const int len = read(fd, buffer, sizeof(buffer)-1);
614 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 if (len < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000617 ALOGW("Unable to read /proc/meminfo");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 return -1;
619 }
620 buffer[len] = 0;
621
Elliott Hughesc367d482013-10-29 13:12:55 -0700622 size_t numFound = 0;
Marco Nelissen0bca96b2009-07-17 12:59:25 -0700623 jlong mem = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 char* p = buffer;
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700626 while (*p && numFound < num) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 int i = 0;
628 while (sums[i]) {
629 if (strncmp(p, sums[i], sumsLen[i]) == 0) {
630 p += sumsLen[i];
631 while (*p == ' ') p++;
632 char* num = p;
633 while (*p >= '0' && *p <= '9') p++;
634 if (*p != 0) {
635 *p = 0;
636 p++;
637 if (*p == 0) p--;
638 }
Marco Nelissen0bca96b2009-07-17 12:59:25 -0700639 mem += atoll(num) * 1024;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 numFound++;
641 break;
642 }
643 i++;
644 }
645 p++;
646 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 return numFound > 0 ? mem : -1;
649}
650
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700651static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
652{
653 static const char* const sums[] = { "MemFree:", "Cached:", NULL };
Elliott Hughesc367d482013-10-29 13:12:55 -0700654 static const size_t sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 };
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700655 return getFreeMemoryImpl(sums, sumsLen, 2);
656}
657
658static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
659{
660 static const char* const sums[] = { "MemTotal:", NULL };
Elliott Hughesc367d482013-10-29 13:12:55 -0700661 static const size_t sumsLen[] = { strlen("MemTotal:"), 0 };
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700662 return getFreeMemoryImpl(sums, sumsLen, 1);
663}
664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
666 jobjectArray reqFields, jlongArray outFields)
667{
Steve Block6215d3f2012-01-04 20:05:49 +0000668 //ALOGI("getMemInfo: %p %p", reqFields, outFields);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700671 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 return;
673 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 const char* file8 = env->GetStringUTFChars(fileStr, NULL);
676 if (file8 == NULL) {
677 return;
678 }
679 String8 file(file8);
680 env->ReleaseStringUTFChars(fileStr, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 jsize count = env->GetArrayLength(reqFields);
683 if (count > env->GetArrayLength(outFields)) {
684 jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
685 return;
686 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 Vector<String8> fields;
689 int i;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 for (i=0; i<count; i++) {
692 jobject obj = env->GetObjectArrayElement(reqFields, i);
693 if (obj != NULL) {
694 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
Steve Block6215d3f2012-01-04 20:05:49 +0000695 //ALOGI("String at %d: %p = %s", i, obj, str8);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 if (str8 == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700697 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 return;
699 }
700 fields.add(String8(str8));
701 env->ReleaseStringUTFChars((jstring)obj, str8);
702 } else {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700703 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 return;
705 }
706 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
709 if (sizesArray == NULL) {
710 return;
711 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700712
Mark Salyzync6a41012014-04-24 13:05:18 -0700713 //ALOGI("Clearing %" PRId32 " sizes", count);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 for (i=0; i<count; i++) {
715 sizesArray[i] = 0;
716 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 int fd = open(file.string(), O_RDONLY);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 if (fd >= 0) {
721 const size_t BUFFER_SIZE = 2048;
722 char* buffer = (char*)malloc(BUFFER_SIZE);
723 int len = read(fd, buffer, BUFFER_SIZE-1);
724 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 if (len < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000727 ALOGW("Unable to read %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 len = 0;
729 }
730 buffer[len] = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 int foundCount = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 char* p = buffer;
735 while (*p && foundCount < count) {
736 bool skipToEol = true;
Steve Block6215d3f2012-01-04 20:05:49 +0000737 //ALOGI("Parsing at: %s", p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 for (i=0; i<count; i++) {
739 const String8& field = fields[i];
740 if (strncmp(p, field.string(), field.length()) == 0) {
741 p += field.length();
Amith Yamasaniadd868c2009-06-25 11:57:40 -0700742 while (*p == ' ' || *p == '\t') p++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 char* num = p;
744 while (*p >= '0' && *p <= '9') p++;
745 skipToEol = *p != '\n';
746 if (*p != 0) {
747 *p = 0;
748 p++;
749 }
750 char* end;
751 sizesArray[i] = strtoll(num, &end, 10);
Mark Salyzync6a41012014-04-24 13:05:18 -0700752 //ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 foundCount++;
754 break;
755 }
756 }
757 if (skipToEol) {
758 while (*p && *p != '\n') {
759 p++;
760 }
761 if (*p == '\n') {
762 p++;
763 }
764 }
765 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 free(buffer);
768 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000769 ALOGW("Unable to open %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700771
Steve Block6215d3f2012-01-04 20:05:49 +0000772 //ALOGI("Done!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 env->ReleaseLongArrayElements(outFields, sizesArray, 0);
774}
775
776jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
777 jstring file, jintArray lastArray)
778{
779 if (file == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700780 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 return NULL;
782 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 const char* file8 = env->GetStringUTFChars(file, NULL);
785 if (file8 == NULL) {
786 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
787 return NULL;
788 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 DIR* dirp = opendir(file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 if(dirp == NULL) {
795 return NULL;
796 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 jsize curCount = 0;
799 jint* curData = NULL;
800 if (lastArray != NULL) {
801 curCount = env->GetArrayLength(lastArray);
802 curData = env->GetIntArrayElements(lastArray, 0);
803 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 jint curPos = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 struct dirent* entry;
808 while ((entry=readdir(dirp)) != NULL) {
809 const char* p = entry->d_name;
810 while (*p) {
811 if (*p < '0' || *p > '9') break;
812 p++;
813 }
814 if (*p != 0) continue;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 char* end;
817 int pid = strtol(entry->d_name, &end, 10);
Steve Block6215d3f2012-01-04 20:05:49 +0000818 //ALOGI("File %s pid=%d\n", entry->d_name, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 if (curPos >= curCount) {
820 jsize newCount = (curCount == 0) ? 10 : (curCount*2);
821 jintArray newArray = env->NewIntArray(newCount);
822 if (newArray == NULL) {
823 closedir(dirp);
824 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
825 return NULL;
826 }
827 jint* newData = env->GetIntArrayElements(newArray, 0);
828 if (curData != NULL) {
829 memcpy(newData, curData, sizeof(jint)*curCount);
830 env->ReleaseIntArrayElements(lastArray, curData, 0);
831 }
832 lastArray = newArray;
833 curCount = newCount;
834 curData = newData;
835 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 curData[curPos] = pid;
838 curPos++;
839 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 closedir(dirp);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 if (curData != NULL && curPos > 0) {
844 qsort(curData, curPos, sizeof(jint), pid_compare);
845 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 while (curPos < curCount) {
848 curData[curPos] = -1;
849 curPos++;
850 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 if (curData != NULL) {
853 env->ReleaseIntArrayElements(lastArray, curData, 0);
854 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 return lastArray;
857}
858
859enum {
860 PROC_TERM_MASK = 0xff,
861 PROC_ZERO_TERM = 0,
862 PROC_SPACE_TERM = ' ',
863 PROC_COMBINE = 0x100,
864 PROC_PARENS = 0x200,
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700865 PROC_QUOTES = 0x400,
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700866 PROC_CHAR = 0x800,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 PROC_OUT_STRING = 0x1000,
868 PROC_OUT_LONG = 0x2000,
869 PROC_OUT_FLOAT = 0x4000,
870};
871
Evan Millarc64edde2009-04-18 12:26:32 -0700872jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700873 char* buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700874 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875{
Elliott Hughes69a017b2011-04-08 14:10:28 -0700876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 const jsize NF = env->GetArrayLength(format);
878 const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
879 const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
880 const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 jint* formatData = env->GetIntArrayElements(format, 0);
883 jlong* longsData = outLongs ?
884 env->GetLongArrayElements(outLongs, 0) : NULL;
885 jfloat* floatsData = outFloats ?
886 env->GetFloatArrayElements(outFloats, 0) : NULL;
887 if (formatData == NULL || (NL > 0 && longsData == NULL)
888 || (NR > 0 && floatsData == NULL)) {
889 if (formatData != NULL) {
890 env->ReleaseIntArrayElements(format, formatData, 0);
891 }
892 if (longsData != NULL) {
893 env->ReleaseLongArrayElements(outLongs, longsData, 0);
894 }
895 if (floatsData != NULL) {
896 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
897 }
898 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
899 return JNI_FALSE;
900 }
901
Evan Millarc64edde2009-04-18 12:26:32 -0700902 jsize i = startIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 jsize di = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 jboolean res = JNI_TRUE;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 for (jsize fi=0; fi<NF; fi++) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700908 jint mode = formatData[fi];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 if ((mode&PROC_PARENS) != 0) {
910 i++;
Bernhard Rosenkränzer3b1e22e2014-11-17 22:30:56 +0100911 } else if ((mode&PROC_QUOTES) != 0) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700912 if (buffer[i] == '"') {
913 i++;
914 } else {
915 mode &= ~PROC_QUOTES;
916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
918 const char term = (char)(mode&PROC_TERM_MASK);
919 const jsize start = i;
Evan Millarc64edde2009-04-18 12:26:32 -0700920 if (i >= endIndex) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800921 if (kDebugProc) {
922 ALOGW("Ran off end of data @%d", i);
923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 res = JNI_FALSE;
925 break;
926 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 jsize end = -1;
929 if ((mode&PROC_PARENS) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700930 while (i < endIndex && buffer[i] != ')') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 i++;
932 }
933 end = i;
934 i++;
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700935 } else if ((mode&PROC_QUOTES) != 0) {
936 while (buffer[i] != '"' && i < endIndex) {
937 i++;
938 }
939 end = i;
940 i++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700942 while (i < endIndex && buffer[i] != term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 i++;
944 }
945 if (end < 0) {
946 end = i;
947 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700948
Evan Millarc64edde2009-04-18 12:26:32 -0700949 if (i < endIndex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 i++;
951 if ((mode&PROC_COMBINE) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700952 while (i < endIndex && buffer[i] == term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 i++;
954 }
955 }
956 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700957
Mark Salyzync6a41012014-04-24 13:05:18 -0700958 //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
961 char c = buffer[end];
962 buffer[end] = 0;
963 if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
964 char* end;
965 floatsData[di] = strtof(buffer+start, &end);
966 }
967 if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700968 if ((mode&PROC_CHAR) != 0) {
969 // Caller wants single first character returned as one long.
970 longsData[di] = buffer[start];
971 } else {
972 char* end;
973 longsData[di] = strtoll(buffer+start, &end, 10);
974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
977 jstring str = env->NewStringUTF(buffer+start);
978 env->SetObjectArrayElement(outStrings, di, str);
979 }
980 buffer[end] = c;
981 di++;
982 }
983 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 env->ReleaseIntArrayElements(format, formatData, 0);
986 if (longsData != NULL) {
987 env->ReleaseLongArrayElements(outLongs, longsData, 0);
988 }
989 if (floatsData != NULL) {
990 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
991 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 return res;
994}
995
Evan Millarc64edde2009-04-18 12:26:32 -0700996jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700997 jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700998 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
999{
1000 jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
1001
Elliott Hughes69a017b2011-04-08 14:10:28 -07001002 jboolean result = android_os_Process_parseProcLineArray(env, clazz,
1003 (char*) bufferArray, startIndex, endIndex, format, outStrings,
Evan Millarc64edde2009-04-18 12:26:32 -07001004 outLongs, outFloats);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001005
Evan Millarc64edde2009-04-18 12:26:32 -07001006 env->ReleaseByteArrayElements(buffer, bufferArray, 0);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001007
Evan Millarc64edde2009-04-18 12:26:32 -07001008 return result;
1009}
1010
1011jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
1012 jstring file, jintArray format, jobjectArray outStrings,
1013 jlongArray outLongs, jfloatArray outFloats)
1014{
1015 if (file == NULL || format == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001016 jniThrowNullPointerException(env, NULL);
Evan Millarc64edde2009-04-18 12:26:32 -07001017 return JNI_FALSE;
1018 }
1019
1020 const char* file8 = env->GetStringUTFChars(file, NULL);
1021 if (file8 == NULL) {
1022 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1023 return JNI_FALSE;
1024 }
1025 int fd = open(file8, O_RDONLY);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001026
Evan Millarc64edde2009-04-18 12:26:32 -07001027 if (fd < 0) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001028 if (kDebugProc) {
1029 ALOGW("Unable to open process file: %s\n", file8);
1030 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001031 env->ReleaseStringUTFChars(file, file8);
Evan Millarc64edde2009-04-18 12:26:32 -07001032 return JNI_FALSE;
1033 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001034 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001035
Evan Millarc64edde2009-04-18 12:26:32 -07001036 char buffer[256];
1037 const int len = read(fd, buffer, sizeof(buffer)-1);
1038 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001039
Evan Millarc64edde2009-04-18 12:26:32 -07001040 if (len < 0) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001041 if (kDebugProc) {
1042 ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
1043 }
Evan Millarc64edde2009-04-18 12:26:32 -07001044 return JNI_FALSE;
1045 }
1046 buffer[len] = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -07001047
1048 return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
Evan Millarc64edde2009-04-18 12:26:32 -07001049 format, outStrings, outLongs, outFloats);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001050
Evan Millarc64edde2009-04-18 12:26:32 -07001051}
1052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
1054 jobject binderObject)
1055{
1056 if (binderObject == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001057 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 return;
1059 }
1060
1061 sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
1062}
1063
1064void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
1065{
1066 if (pid > 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -07001067 ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 kill(pid, sig);
1069 }
1070}
1071
Dianne Hackborn906497c2010-05-10 15:57:38 -07001072void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
1073{
1074 if (pid > 0) {
1075 kill(pid, sig);
1076 }
1077}
1078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
1080{
1081 struct timespec ts;
1082
1083 int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 if (res != 0) {
1086 return (jlong) 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -07001087 }
1088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
1090 return (jlong) nanoseconds_to_milliseconds(when);
1091}
1092
1093static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
1094{
1095 char filename[64];
1096
Mark Salyzync6a41012014-04-24 13:05:18 -07001097 snprintf(filename, sizeof(filename), "/proc/%" PRId32 "/smaps", pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098
1099 FILE * file = fopen(filename, "r");
1100 if (!file) {
1101 return (jlong) -1;
1102 }
1103
1104 // Tally up all of the Pss from the various maps
1105 char line[256];
1106 jlong pss = 0;
1107 while (fgets(line, sizeof(line), file)) {
1108 jlong v;
Mark Salyzync6a41012014-04-24 13:05:18 -07001109 if (sscanf(line, "Pss: %" SCNd64 " kB", &v) == 1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 pss += v;
1111 }
1112 }
1113
1114 fclose(file);
1115
1116 // Return the Pss value in bytes, not kilobytes
1117 return pss * 1024;
1118}
1119
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001120jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
1121 jobjectArray commandNames)
1122{
1123 if (commandNames == NULL) {
1124 jniThrowNullPointerException(env, NULL);
1125 return NULL;
1126 }
1127
1128 Vector<String8> commands;
1129
1130 jsize count = env->GetArrayLength(commandNames);
1131
1132 for (int i=0; i<count; i++) {
1133 jobject obj = env->GetObjectArrayElement(commandNames, i);
1134 if (obj != NULL) {
1135 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
1136 if (str8 == NULL) {
1137 jniThrowNullPointerException(env, "Element in commandNames");
1138 return NULL;
1139 }
1140 commands.add(String8(str8));
1141 env->ReleaseStringUTFChars((jstring)obj, str8);
1142 } else {
1143 jniThrowNullPointerException(env, "Element in commandNames");
1144 return NULL;
1145 }
1146 }
1147
1148 Vector<jint> pids;
1149
1150 DIR *proc = opendir("/proc");
1151 if (proc == NULL) {
1152 fprintf(stderr, "/proc: %s\n", strerror(errno));
1153 return NULL;
1154 }
1155
1156 struct dirent *d;
1157 while ((d = readdir(proc))) {
1158 int pid = atoi(d->d_name);
1159 if (pid <= 0) continue;
1160
1161 char path[PATH_MAX];
1162 char data[PATH_MAX];
1163 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
1164
1165 int fd = open(path, O_RDONLY);
1166 if (fd < 0) {
1167 continue;
1168 }
1169 const int len = read(fd, data, sizeof(data)-1);
1170 close(fd);
1171
1172 if (len < 0) {
1173 continue;
1174 }
1175 data[len] = 0;
1176
1177 for (int i=0; i<len; i++) {
1178 if (data[i] == ' ') {
1179 data[i] = 0;
1180 break;
1181 }
1182 }
1183
1184 for (size_t i=0; i<commands.size(); i++) {
1185 if (commands[i] == data) {
1186 pids.add(pid);
1187 break;
1188 }
1189 }
1190 }
1191
1192 closedir(proc);
1193
1194 jintArray pidArray = env->NewIntArray(pids.size());
1195 if (pidArray == NULL) {
1196 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1197 return NULL;
1198 }
1199
1200 if (pids.size() > 0) {
1201 env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
1202 }
1203
1204 return pidArray;
1205}
1206
Colin Cross0769e552014-06-03 13:25:35 -07001207jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
1208{
1209 return killProcessGroup(uid, pid, SIGKILL);
1210}
1211
1212void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
1213{
1214 return removeAllProcessGroups();
1215}
1216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217static const JNINativeMethod methods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 {"getUidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
1219 {"getGidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
1220 {"setThreadPriority", "(II)V", (void*)android_os_Process_setThreadPriority},
Glenn Kasten6793ac92011-07-13 12:44:12 -07001221 {"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler},
Christopher Tate160edb32010-06-30 17:46:30 -07001222 {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 {"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority},
1224 {"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority},
Srinath Sridharan1b15d132016-07-19 15:16:11 -07001225 {"getThreadScheduler", "(I)I", (void*)android_os_Process_getThreadScheduler},
San Mehate9d376b2009-04-21 14:06:36 -07001226 {"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup},
Joel Fernandes474d3112017-04-04 16:32:15 -07001227 {"setThreadGroupAndCpuset", "(II)V", (void*)android_os_Process_setThreadGroupAndCpuset},
Jeff Sharkey9e57c412013-01-17 14:12:41 -08001228 {"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup},
1229 {"getProcessGroup", "(I)I", (void*)android_os_Process_getProcessGroup},
Martijn Coenencd4bdf32016-03-03 17:30:52 +01001230 {"getExclusiveCores", "()[I", (void*)android_os_Process_getExclusiveCores},
Rom Lemarchand5534ba92013-07-12 16:15:36 -07001231 {"setSwappiness", "(IZ)Z", (void*)android_os_Process_setSwappiness},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 {"setArgV0", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
1233 {"setUid", "(I)I", (void*)android_os_Process_setUid},
1234 {"setGid", "(I)I", (void*)android_os_Process_setGid},
1235 {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
Dianne Hackborn906497c2010-05-10 15:57:38 -07001236 {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
Marco Nelissen0bca96b2009-07-17 12:59:25 -07001237 {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
Dianne Hackborn59325eb2012-05-09 18:45:20 -07001238 {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
1240 {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
1241 {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
Evan Millarc64edde2009-04-18 12:26:32 -07001242 {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
1244 {"getPss", "(I)J", (void*)android_os_Process_getPss},
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001245 {"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
Colin Cross0769e552014-06-03 13:25:35 -07001247 {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
1248 {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249};
1250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251int register_android_os_Process(JNIEnv* env)
1252{
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001253 return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254}