blob: 2d7069c50255ebd69a4ee6b6d7a1902f789178be [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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025#include <utils/String8.h>
26#include <utils/Vector.h>
Sandeep Patilfcd4a4a2019-01-12 22:42:05 -080027#include <meminfo/procmeminfo.h>
Sandeep Patilbe825412018-12-11 10:09:46 -080028#include <meminfo/sysmeminfo.h>
Colin Cross0769e552014-06-03 13:25:35 -070029#include <processgroup/processgroup.h>
Suren Baghdasaryane4433262019-01-04 12:16:57 -080030#include <processgroup/sched_policy.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Sandeep Patilbe825412018-12-11 10:09:46 -080032#include <string>
33#include <vector>
34
Andreas Gampeed6b9df2014-11-20 22:02:20 -080035#include "core_jni_helpers.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036
37#include "android_util_Binder.h"
Steven Moreland2279b252017-07-19 09:50:45 -070038#include <nativehelper/JNIHelp.h>
Daniel Colascione6c518102017-07-27 03:33:34 -070039#include "android_os_Debug.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041#include <dirent.h>
42#include <fcntl.h>
43#include <grp.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070044#include <inttypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045#include <pwd.h>
46#include <signal.h>
Sandeep Patilbe825412018-12-11 10:09:46 -080047#include <string.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070048#include <sys/errno.h>
49#include <sys/resource.h>
50#include <sys/stat.h>
Sandeep Patilbe825412018-12-11 10:09:46 -080051#include <sys/sysinfo.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070052#include <sys/types.h>
Glenn Kasten6af763b2011-05-04 17:58:57 -070053#include <unistd.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054
Christopher Tate160edb32010-06-30 17:46:30 -070055#define GUARD_THREAD_PRIORITY 0
San Mehata5109a82009-10-29 11:48:50 -070056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057using namespace android;
58
Andreas Gampe0f0b4912014-11-12 08:03:48 -080059static const bool kDebugPolicy = false;
60static const bool kDebugProc = false;
Misha Wagnercc065fb2018-10-15 10:45:44 +010061// When reading `proc` files, how many bytes to read at a time
62static const int kReadSize = 4096;
Andreas Gampe0f0b4912014-11-12 08:03:48 -080063
Christopher Tate160edb32010-06-30 17:46:30 -070064#if GUARD_THREAD_PRIORITY
65Mutex gKeyCreateMutex;
66static pthread_key_t gBgKey = -1;
67#endif
68
Glenn Kastenf1b56442012-03-15 16:33:43 -070069// For both of these, err should be in the errno range (positive), not a status_t (negative)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070070static void signalExceptionForError(JNIEnv* env, int err, int tid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 switch (err) {
72 case EINVAL:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070073 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
74 "Invalid argument: %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 break;
76 case ESRCH:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070077 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
78 "Given thread %d does not exist", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 break;
80 case EPERM:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070081 jniThrowExceptionFmt(env, "java/lang/SecurityException",
82 "No permission to modify given thread %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 break;
84 default:
85 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
86 break;
87 }
88}
89
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070090static void signalExceptionForPriorityError(JNIEnv* env, int err, int tid) {
San Mehate9d376b2009-04-21 14:06:36 -070091 switch (err) {
San Mehate9d376b2009-04-21 14:06:36 -070092 case EACCES:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070093 jniThrowExceptionFmt(env, "java/lang/SecurityException",
94 "No permission to set the priority of %d", tid);
San Mehate9d376b2009-04-21 14:06:36 -070095 break;
96 default:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070097 signalExceptionForError(env, err, tid);
98 break;
99 }
100
101}
102
103static void signalExceptionForGroupError(JNIEnv* env, int err, int tid) {
104 switch (err) {
105 case EACCES:
106 jniThrowExceptionFmt(env, "java/lang/SecurityException",
107 "No permission to set the group of %d", tid);
108 break;
109 default:
110 signalExceptionForError(env, err, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700111 break;
112 }
113}
114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
116{
117 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700118 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 return -1;
120 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 const jchar* str16 = env->GetStringCritical(name, 0);
123 String8 name8;
124 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800125 name8 = String8(reinterpret_cast<const char16_t*>(str16),
126 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 env->ReleaseStringCritical(name, str16);
128 }
129
130 const size_t N = name8.size();
131 if (N > 0) {
132 const char* str = name8.string();
133 for (size_t i=0; i<N; i++) {
134 if (str[i] < '0' || str[i] > '9') {
135 struct passwd* pwd = getpwnam(str);
136 if (pwd == NULL) {
137 return -1;
138 }
139 return pwd->pw_uid;
140 }
141 }
142 return atoi(str);
143 }
144 return -1;
145}
146
147jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
148{
149 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700150 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 return -1;
152 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 const jchar* str16 = env->GetStringCritical(name, 0);
155 String8 name8;
156 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800157 name8 = String8(reinterpret_cast<const char16_t*>(str16),
158 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 env->ReleaseStringCritical(name, str16);
160 }
161
162 const size_t N = name8.size();
163 if (N > 0) {
164 const char* str = name8.string();
165 for (size_t i=0; i<N; i++) {
166 if (str[i] < '0' || str[i] > '9') {
167 struct group* grp = getgrnam(str);
168 if (grp == NULL) {
169 return -1;
170 }
171 return grp->gr_gid;
172 }
173 }
174 return atoi(str);
175 }
176 return -1;
177}
178
Glenn Kastenf1b56442012-03-15 16:33:43 -0700179void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int tid, jint grp)
San Mehate9d376b2009-04-21 14:06:36 -0700180{
Mark Salyzync6a41012014-04-24 13:05:18 -0700181 ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
Glenn Kastenf1b56442012-03-15 16:33:43 -0700182 SchedPolicy sp = (SchedPolicy) grp;
183 int res = set_sched_policy(tid, sp);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800184 if (res != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700185 signalExceptionForGroupError(env, -res, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700186 }
San Mehate9d376b2009-04-21 14:06:36 -0700187}
188
Joel Fernandes474d3112017-04-04 16:32:15 -0700189void android_os_Process_setThreadGroupAndCpuset(JNIEnv* env, jobject clazz, int tid, jint grp)
190{
191 ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
192 SchedPolicy sp = (SchedPolicy) grp;
193 int res = set_sched_policy(tid, sp);
194
195 if (res != NO_ERROR) {
196 signalExceptionForGroupError(env, -res, tid);
197 }
198
199 res = set_cpuset_policy(tid, sp);
200 if (res != NO_ERROR) {
201 signalExceptionForGroupError(env, -res, tid);
202 }
203}
204
Elliott Hughes69a017b2011-04-08 14:10:28 -0700205void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
San Mehat3e458242009-05-19 14:44:16 -0700206{
Mark Salyzync6a41012014-04-24 13:05:18 -0700207 ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp);
San Mehat3e458242009-05-19 14:44:16 -0700208 DIR *d;
San Mehat3e458242009-05-19 14:44:16 -0700209 char proc_path[255];
210 struct dirent *de;
211
Glenn Kastenf1b56442012-03-15 16:33:43 -0700212 if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700213 signalExceptionForGroupError(env, EINVAL, pid);
San Mehat3e458242009-05-19 14:44:16 -0700214 return;
215 }
216
Glenn Kastenf1b56442012-03-15 16:33:43 -0700217 bool isDefault = false;
218 if (grp < 0) {
219 grp = SP_FOREGROUND;
220 isDefault = true;
221 }
222 SchedPolicy sp = (SchedPolicy) grp;
223
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800224 if (kDebugPolicy) {
225 char cmdline[32];
226 int fd;
San Mehata5109a82009-10-29 11:48:50 -0700227
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800228 strcpy(cmdline, "unknown");
San Mehata5109a82009-10-29 11:48:50 -0700229
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800230 sprintf(proc_path, "/proc/%d/cmdline", pid);
Nick Kralevich422dd00f2017-10-19 17:51:50 -0700231 fd = open(proc_path, O_RDONLY | O_CLOEXEC);
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800232 if (fd >= 0) {
233 int rc = read(fd, cmdline, sizeof(cmdline)-1);
234 cmdline[rc] = 0;
235 close(fd);
236 }
237
238 if (sp == SP_BACKGROUND) {
239 ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
240 } else {
241 ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
242 }
San Mehata5109a82009-10-29 11:48:50 -0700243 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700244
San Mehat3e458242009-05-19 14:44:16 -0700245 sprintf(proc_path, "/proc/%d/task", pid);
246 if (!(d = opendir(proc_path))) {
San Mehat1fd0ec72009-06-15 16:56:52 -0700247 // If the process exited on us, don't generate an exception
248 if (errno != ENOENT)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700249 signalExceptionForGroupError(env, errno, pid);
San Mehat3e458242009-05-19 14:44:16 -0700250 return;
251 }
252
253 while ((de = readdir(d))) {
San Mehat7e637892009-08-06 13:19:19 -0700254 int t_pid;
255 int t_pri;
256
San Mehat3e458242009-05-19 14:44:16 -0700257 if (de->d_name[0] == '.')
258 continue;
San Mehat7e637892009-08-06 13:19:19 -0700259 t_pid = atoi(de->d_name);
San Mehat1fd0ec72009-06-15 16:56:52 -0700260
San Mehat7e637892009-08-06 13:19:19 -0700261 if (!t_pid) {
Steve Block3762c312012-01-06 19:20:56 +0000262 ALOGE("Error getting pid for '%s'\n", de->d_name);
San Mehat7e637892009-08-06 13:19:19 -0700263 continue;
264 }
265
Glenn Kasten07b04652012-04-23 15:00:43 -0700266 t_pri = getpriority(PRIO_PROCESS, t_pid);
San Mehat7e637892009-08-06 13:19:19 -0700267
Glenn Kasten07b04652012-04-23 15:00:43 -0700268 if (t_pri <= ANDROID_PRIORITY_AUDIO) {
Tim Murray20375fe2016-12-20 11:47:24 -0800269 int scheduler = sched_getscheduler(t_pid) & ~SCHED_RESET_ON_FORK;
Glenn Kasten07b04652012-04-23 15:00:43 -0700270 if ((scheduler == SCHED_FIFO) || (scheduler == SCHED_RR)) {
Tim Murray9e41c742015-06-08 14:56:53 -0700271 // This task wants to stay in its current audio group so it can keep its budget
272 // don't update its cpuset or cgroup
Glenn Kasten07b04652012-04-23 15:00:43 -0700273 continue;
274 }
275 }
276
277 if (isDefault) {
Glenn Kastenf1b56442012-03-15 16:33:43 -0700278 if (t_pri >= ANDROID_PRIORITY_BACKGROUND) {
279 // This task wants to stay at background
Tim Murray9e41c742015-06-08 14:56:53 -0700280 // update its cpuset so it doesn't only run on bg core(s)
Isaac Chend34fac52017-02-16 11:51:08 +0800281 if (cpusets_enabled()) {
282 int err = set_cpuset_policy(t_pid, sp);
283 if (err != NO_ERROR) {
284 signalExceptionForGroupError(env, -err, t_pid);
285 break;
286 }
Tim Murray9e41c742015-06-08 14:56:53 -0700287 }
Glenn Kastenf1b56442012-03-15 16:33:43 -0700288 continue;
289 }
San Mehat7e637892009-08-06 13:19:19 -0700290 }
Tim Murray9e41c742015-06-08 14:56:53 -0700291 int err;
Isaac Chend34fac52017-02-16 11:51:08 +0800292
293 if (cpusets_enabled()) {
294 // set both cpuset and cgroup for general threads
295 err = set_cpuset_policy(t_pid, sp);
296 if (err != NO_ERROR) {
297 signalExceptionForGroupError(env, -err, t_pid);
298 break;
299 }
San Mehat242d65b2009-09-12 10:10:37 -0700300 }
Tim Murray9e41c742015-06-08 14:56:53 -0700301
302 err = set_sched_policy(t_pid, sp);
303 if (err != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700304 signalExceptionForGroupError(env, -err, t_pid);
Tim Murray9e41c742015-06-08 14:56:53 -0700305 break;
306 }
307
San Mehat3e458242009-05-19 14:44:16 -0700308 }
309 closedir(d);
310}
311
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800312jint android_os_Process_getProcessGroup(JNIEnv* env, jobject clazz, jint pid)
313{
314 SchedPolicy sp;
315 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700316 signalExceptionForGroupError(env, errno, pid);
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800317 }
318 return (int) sp;
319}
320
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100321/** Sample CPUset list format:
322 * 0-3,4,6-8
323 */
324static void parse_cpuset_cpus(char *cpus, cpu_set_t *cpu_set) {
325 unsigned int start, end, matched, i;
326 char *cpu_range = strtok(cpus, ",");
327 while (cpu_range != NULL) {
328 start = end = 0;
329 matched = sscanf(cpu_range, "%u-%u", &start, &end);
330 cpu_range = strtok(NULL, ",");
331 if (start >= CPU_SETSIZE) {
332 ALOGE("parse_cpuset_cpus: ignoring CPU number larger than %d.", CPU_SETSIZE);
333 continue;
334 } else if (end >= CPU_SETSIZE) {
335 ALOGE("parse_cpuset_cpus: ignoring CPU numbers larger than %d.", CPU_SETSIZE);
336 end = CPU_SETSIZE - 1;
337 }
338 if (matched == 1) {
339 CPU_SET(start, cpu_set);
340 } else if (matched == 2) {
341 for (i = start; i <= end; i++) {
342 CPU_SET(i, cpu_set);
343 }
344 } else {
345 ALOGE("Failed to match cpus");
346 }
347 }
348 return;
349}
350
351/**
352 * Stores the CPUs assigned to the cpuset corresponding to the
353 * SchedPolicy in the passed in cpu_set.
354 */
355static void get_cpuset_cores_for_policy(SchedPolicy policy, cpu_set_t *cpu_set)
356{
357 FILE *file;
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -0800358 std::string filename;
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100359
360 CPU_ZERO(cpu_set);
361
362 switch (policy) {
363 case SP_BACKGROUND:
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -0800364 if (!CgroupGetAttributePath("LowCapacityCPUs", &filename)) {
365 return;
366 }
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100367 break;
368 case SP_FOREGROUND:
369 case SP_AUDIO_APP:
370 case SP_AUDIO_SYS:
Glenn Kasten73a78002017-04-27 15:29:23 -0700371 case SP_RT_APP:
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -0800372 if (!CgroupGetAttributePath("HighCapacityCPUs", &filename)) {
373 return;
374 }
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100375 break;
376 case SP_TOP_APP:
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -0800377 if (!CgroupGetAttributePath("MaxCapacityCPUs", &filename)) {
378 return;
379 }
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100380 break;
381 default:
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -0800382 return;
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100383 }
384
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -0800385 file = fopen(filename.c_str(), "re");
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100386 if (file != NULL) {
387 // Parse cpus string
388 char *line = NULL;
389 size_t len = 0;
390 ssize_t num_read = getline(&line, &len, file);
391 fclose (file);
392 if (num_read > 0) {
393 parse_cpuset_cpus(line, cpu_set);
394 } else {
Suren Baghdasaryan3fc4af62018-12-14 10:32:22 -0800395 ALOGE("Failed to read %s", filename.c_str());
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100396 }
397 free(line);
398 }
399 return;
400}
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100401
402
403/**
404 * Determine CPU cores exclusively assigned to the
405 * cpuset corresponding to the SchedPolicy and store
406 * them in the passed in cpu_set_t
407 */
408void get_exclusive_cpuset_cores(SchedPolicy policy, cpu_set_t *cpu_set) {
Isaac Chend34fac52017-02-16 11:51:08 +0800409 if (cpusets_enabled()) {
410 int i;
411 cpu_set_t tmp_set;
412 get_cpuset_cores_for_policy(policy, cpu_set);
413 for (i = 0; i < SP_CNT; i++) {
414 if ((SchedPolicy) i == policy) continue;
415 get_cpuset_cores_for_policy((SchedPolicy)i, &tmp_set);
416 // First get cores exclusive to one set or the other
417 CPU_XOR(&tmp_set, cpu_set, &tmp_set);
418 // Then get the ones only in cpu_set
419 CPU_AND(cpu_set, cpu_set, &tmp_set);
420 }
421 } else {
422 CPU_ZERO(cpu_set);
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100423 }
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100424 return;
425}
426
427jintArray android_os_Process_getExclusiveCores(JNIEnv* env, jobject clazz) {
428 SchedPolicy sp;
429 cpu_set_t cpu_set;
430 jintArray cpus;
431 int pid = getpid();
432 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700433 signalExceptionForGroupError(env, errno, pid);
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100434 return NULL;
435 }
436 get_exclusive_cpuset_cores(sp, &cpu_set);
437 int num_cpus = CPU_COUNT(&cpu_set);
438 cpus = env->NewIntArray(num_cpus);
439 if (cpus == NULL) {
440 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
441 return NULL;
442 }
443
444 jint* cpu_elements = env->GetIntArrayElements(cpus, 0);
445 int count = 0;
446 for (int i = 0; i < CPU_SETSIZE && count < num_cpus; i++) {
447 if (CPU_ISSET(i, &cpu_set)) {
448 cpu_elements[count++] = i;
449 }
450 }
451
452 env->ReleaseIntArrayElements(cpus, cpu_elements, 0);
453 return cpus;
454}
455
Christopher Tate160edb32010-06-30 17:46:30 -0700456static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
457 // Establishes the calling thread as illegal to put into the background.
458 // Typically used only for the system process's main looper.
459#if GUARD_THREAD_PRIORITY
Elliott Hughes06451fe2014-08-18 10:26:52 -0700460 ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
Christopher Tate160edb32010-06-30 17:46:30 -0700461 {
462 Mutex::Autolock _l(gKeyCreateMutex);
463 if (gBgKey == -1) {
464 pthread_key_create(&gBgKey, NULL);
465 }
466 }
467
468 // inverted: not-okay, we set a sentinel value
469 pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
470#endif
471}
472
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700473jint android_os_Process_getThreadScheduler(JNIEnv* env, jclass clazz,
474 jint tid)
475{
476 int policy = 0;
477// linux has sched_getscheduler(), others don't.
478#if defined(__linux__)
479 errno = 0;
480 policy = sched_getscheduler(tid);
481 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700482 signalExceptionForPriorityError(env, errno, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700483 }
484#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700485 signalExceptionForPriorityError(env, ENOSYS, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700486#endif
487 return policy;
488}
489
Glenn Kasten6793ac92011-07-13 12:44:12 -0700490void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
491 jint tid, jint policy, jint pri)
492{
Yabin Cui65b4a682014-11-10 12:15:46 -0800493// linux has sched_setscheduler(), others don't.
494#if defined(__linux__)
Glenn Kasten6793ac92011-07-13 12:44:12 -0700495 struct sched_param param;
496 param.sched_priority = pri;
497 int rc = sched_setscheduler(tid, policy, &param);
498 if (rc) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700499 signalExceptionForPriorityError(env, errno, tid);
Glenn Kasten6793ac92011-07-13 12:44:12 -0700500 }
Glenn Kastencc767192012-01-17 08:38:51 -0800501#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700502 signalExceptionForPriorityError(env, ENOSYS, tid);
Glenn Kastencc767192012-01-17 08:38:51 -0800503#endif
Glenn Kasten6793ac92011-07-13 12:44:12 -0700504}
505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
507 jint pid, jint pri)
508{
Christopher Tate160edb32010-06-30 17:46:30 -0700509#if GUARD_THREAD_PRIORITY
510 // if we're putting the current thread into the background, check the TLS
511 // to make sure this thread isn't guarded. If it is, raise an exception.
512 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Elliott Hughes06451fe2014-08-18 10:26:52 -0700513 if (pid == gettid()) {
Christopher Tate160edb32010-06-30 17:46:30 -0700514 void* bgOk = pthread_getspecific(gBgKey);
515 if (bgOk == ((void*)0xbaad)) {
Steve Block3762c312012-01-06 19:20:56 +0000516 ALOGE("Thread marked fg-only put self in background!");
Christopher Tate160edb32010-06-30 17:46:30 -0700517 jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
518 return;
519 }
520 }
521 }
522#endif
523
Dianne Hackborn887f3552009-12-07 17:59:37 -0800524 int rc = androidSetThreadPriority(pid, pri);
525 if (rc != 0) {
526 if (rc == INVALID_OPERATION) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700527 signalExceptionForPriorityError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800528 } else {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700529 signalExceptionForGroupError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800530 }
San Mehat242d65b2009-09-12 10:10:37 -0700531 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700532
Mark Salyzync6a41012014-04-24 13:05:18 -0700533 //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 // pid, pri, getpriority(PRIO_PROCESS, pid));
535}
536
537void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
538 jint pri)
539{
Elliott Hughes06451fe2014-08-18 10:26:52 -0700540 android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541}
542
543jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
544 jint pid)
545{
546 errno = 0;
547 jint pri = getpriority(PRIO_PROCESS, pid);
548 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700549 signalExceptionForPriorityError(env, errno, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 }
Mark Salyzync6a41012014-04-24 13:05:18 -0700551 //ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 return pri;
553}
554
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700555jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
556 jint pid, jboolean is_increased)
557{
558 char text[64];
559
560 if (is_increased) {
561 strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
562 } else {
563 strcpy(text, "/sys/fs/cgroup/memory/tasks");
564 }
565
566 struct stat st;
567 if (stat(text, &st) || !S_ISREG(st.st_mode)) {
568 return false;
569 }
570
Nick Kralevich422dd00f2017-10-19 17:51:50 -0700571 int fd = open(text, O_WRONLY | O_CLOEXEC);
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700572 if (fd >= 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -0700573 sprintf(text, "%" PRId32, pid);
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700574 write(fd, text, strlen(text));
575 close(fd);
576 }
577
578 return true;
579}
580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
582{
583 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700584 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 return;
586 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 const jchar* str = env->GetStringCritical(name, 0);
589 String8 name8;
590 if (str) {
Dan Albert66987492014-11-20 11:41:21 -0800591 name8 = String8(reinterpret_cast<const char16_t*>(str),
592 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 env->ReleaseStringCritical(name, str);
594 }
595
Dmitriy Filchenko342c7dc2016-07-12 15:40:54 -0700596 if (!name8.isEmpty()) {
Dmitriy Filchenkof5b6e552016-07-18 16:00:35 -0700597 AndroidRuntime::getRuntime()->setArgv0(name8.string(), true /* setProcName */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 }
599}
600
601jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
602{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 return setuid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604}
605
606jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
607{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 return setgid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609}
610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611static int pid_compare(const void* v1, const void* v2)
612{
Mark Salyzync6a41012014-04-24 13:05:18 -0700613 //ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 return *((const jint*)v1) - *((const jint*)v2);
615}
616
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700617static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
618{
Sandeep Patilbe825412018-12-11 10:09:46 -0800619 static const std::vector<std::string> memFreeTags = {
620 ::android::meminfo::SysMemInfo::kMemFree,
621 ::android::meminfo::SysMemInfo::kMemCached,
622 };
623 std::vector<uint64_t> mem(memFreeTags.size());
624 ::android::meminfo::SysMemInfo smi;
625
626 if (!smi.ReadMemInfo(memFreeTags, &mem)) {
627 jniThrowRuntimeException(env, "SysMemInfo read failed to get Free Memory");
628 return -1L;
629 }
630
631 jlong sum = 0;
632 std::for_each(mem.begin(), mem.end(), [&](uint64_t val) { sum += val; });
633 return sum * 1024;
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700634}
635
636static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
637{
Sandeep Patilbe825412018-12-11 10:09:46 -0800638 struct sysinfo si;
639 if (sysinfo(&si) == -1) {
640 ALOGE("sysinfo failed: %s", strerror(errno));
641 return -1;
642 }
643
644 return si.totalram;
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700645}
646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
648 jobjectArray reqFields, jlongArray outFields)
649{
Steve Block6215d3f2012-01-04 20:05:49 +0000650 //ALOGI("getMemInfo: %p %p", reqFields, outFields);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700653 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 return;
655 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 const char* file8 = env->GetStringUTFChars(fileStr, NULL);
658 if (file8 == NULL) {
659 return;
660 }
661 String8 file(file8);
662 env->ReleaseStringUTFChars(fileStr, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 jsize count = env->GetArrayLength(reqFields);
665 if (count > env->GetArrayLength(outFields)) {
666 jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
667 return;
668 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 Vector<String8> fields;
671 int i;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 for (i=0; i<count; i++) {
674 jobject obj = env->GetObjectArrayElement(reqFields, i);
675 if (obj != NULL) {
676 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
Steve Block6215d3f2012-01-04 20:05:49 +0000677 //ALOGI("String at %d: %p = %s", i, obj, str8);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 if (str8 == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700679 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 return;
681 }
682 fields.add(String8(str8));
683 env->ReleaseStringUTFChars((jstring)obj, str8);
684 } else {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700685 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 return;
687 }
688 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
691 if (sizesArray == NULL) {
692 return;
693 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700694
Mark Salyzync6a41012014-04-24 13:05:18 -0700695 //ALOGI("Clearing %" PRId32 " sizes", count);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 for (i=0; i<count; i++) {
697 sizesArray[i] = 0;
698 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700699
Nick Kralevich422dd00f2017-10-19 17:51:50 -0700700 int fd = open(file.string(), O_RDONLY | O_CLOEXEC);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 if (fd >= 0) {
Dianne Hackborne17b4452018-01-10 13:15:40 -0800703 const size_t BUFFER_SIZE = 4096;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 char* buffer = (char*)malloc(BUFFER_SIZE);
705 int len = read(fd, buffer, BUFFER_SIZE-1);
706 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 if (len < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000709 ALOGW("Unable to read %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 len = 0;
711 }
712 buffer[len] = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 int foundCount = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 char* p = buffer;
717 while (*p && foundCount < count) {
718 bool skipToEol = true;
Steve Block6215d3f2012-01-04 20:05:49 +0000719 //ALOGI("Parsing at: %s", p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 for (i=0; i<count; i++) {
721 const String8& field = fields[i];
722 if (strncmp(p, field.string(), field.length()) == 0) {
723 p += field.length();
Amith Yamasaniadd868c2009-06-25 11:57:40 -0700724 while (*p == ' ' || *p == '\t') p++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 char* num = p;
726 while (*p >= '0' && *p <= '9') p++;
727 skipToEol = *p != '\n';
728 if (*p != 0) {
729 *p = 0;
730 p++;
731 }
732 char* end;
733 sizesArray[i] = strtoll(num, &end, 10);
Mark Salyzync6a41012014-04-24 13:05:18 -0700734 //ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 foundCount++;
736 break;
737 }
738 }
739 if (skipToEol) {
740 while (*p && *p != '\n') {
741 p++;
742 }
743 if (*p == '\n') {
744 p++;
745 }
746 }
747 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 free(buffer);
750 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000751 ALOGW("Unable to open %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700753
Steve Block6215d3f2012-01-04 20:05:49 +0000754 //ALOGI("Done!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 env->ReleaseLongArrayElements(outFields, sizesArray, 0);
756}
757
758jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
759 jstring file, jintArray lastArray)
760{
761 if (file == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700762 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 return NULL;
764 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 const char* file8 = env->GetStringUTFChars(file, NULL);
767 if (file8 == NULL) {
768 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
769 return NULL;
770 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 DIR* dirp = opendir(file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 if(dirp == NULL) {
777 return NULL;
778 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 jsize curCount = 0;
781 jint* curData = NULL;
782 if (lastArray != NULL) {
783 curCount = env->GetArrayLength(lastArray);
784 curData = env->GetIntArrayElements(lastArray, 0);
785 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 jint curPos = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 struct dirent* entry;
790 while ((entry=readdir(dirp)) != NULL) {
791 const char* p = entry->d_name;
792 while (*p) {
793 if (*p < '0' || *p > '9') break;
794 p++;
795 }
796 if (*p != 0) continue;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 char* end;
799 int pid = strtol(entry->d_name, &end, 10);
Steve Block6215d3f2012-01-04 20:05:49 +0000800 //ALOGI("File %s pid=%d\n", entry->d_name, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 if (curPos >= curCount) {
802 jsize newCount = (curCount == 0) ? 10 : (curCount*2);
803 jintArray newArray = env->NewIntArray(newCount);
804 if (newArray == NULL) {
805 closedir(dirp);
806 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
807 return NULL;
808 }
809 jint* newData = env->GetIntArrayElements(newArray, 0);
810 if (curData != NULL) {
811 memcpy(newData, curData, sizeof(jint)*curCount);
812 env->ReleaseIntArrayElements(lastArray, curData, 0);
813 }
814 lastArray = newArray;
815 curCount = newCount;
816 curData = newData;
817 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 curData[curPos] = pid;
820 curPos++;
821 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 closedir(dirp);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 if (curData != NULL && curPos > 0) {
826 qsort(curData, curPos, sizeof(jint), pid_compare);
827 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 while (curPos < curCount) {
830 curData[curPos] = -1;
831 curPos++;
832 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 if (curData != NULL) {
835 env->ReleaseIntArrayElements(lastArray, curData, 0);
836 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 return lastArray;
839}
840
841enum {
842 PROC_TERM_MASK = 0xff,
843 PROC_ZERO_TERM = 0,
844 PROC_SPACE_TERM = ' ',
845 PROC_COMBINE = 0x100,
846 PROC_PARENS = 0x200,
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700847 PROC_QUOTES = 0x400,
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700848 PROC_CHAR = 0x800,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 PROC_OUT_STRING = 0x1000,
850 PROC_OUT_LONG = 0x2000,
851 PROC_OUT_FLOAT = 0x4000,
852};
853
Evan Millarc64edde2009-04-18 12:26:32 -0700854jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700855 char* buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700856 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857{
Elliott Hughes69a017b2011-04-08 14:10:28 -0700858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 const jsize NF = env->GetArrayLength(format);
860 const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
861 const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
862 const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 jint* formatData = env->GetIntArrayElements(format, 0);
865 jlong* longsData = outLongs ?
866 env->GetLongArrayElements(outLongs, 0) : NULL;
867 jfloat* floatsData = outFloats ?
868 env->GetFloatArrayElements(outFloats, 0) : NULL;
869 if (formatData == NULL || (NL > 0 && longsData == NULL)
870 || (NR > 0 && floatsData == NULL)) {
871 if (formatData != NULL) {
872 env->ReleaseIntArrayElements(format, formatData, 0);
873 }
874 if (longsData != NULL) {
875 env->ReleaseLongArrayElements(outLongs, longsData, 0);
876 }
877 if (floatsData != NULL) {
878 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
879 }
880 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
881 return JNI_FALSE;
882 }
883
Evan Millarc64edde2009-04-18 12:26:32 -0700884 jsize i = startIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 jsize di = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 jboolean res = JNI_TRUE;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 for (jsize fi=0; fi<NF; fi++) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700890 jint mode = formatData[fi];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 if ((mode&PROC_PARENS) != 0) {
892 i++;
Bernhard Rosenkränzer3b1e22e2014-11-17 22:30:56 +0100893 } else if ((mode&PROC_QUOTES) != 0) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700894 if (buffer[i] == '"') {
895 i++;
896 } else {
897 mode &= ~PROC_QUOTES;
898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
900 const char term = (char)(mode&PROC_TERM_MASK);
901 const jsize start = i;
Evan Millarc64edde2009-04-18 12:26:32 -0700902 if (i >= endIndex) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800903 if (kDebugProc) {
904 ALOGW("Ran off end of data @%d", i);
905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 res = JNI_FALSE;
907 break;
908 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 jsize end = -1;
911 if ((mode&PROC_PARENS) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700912 while (i < endIndex && buffer[i] != ')') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 i++;
914 }
915 end = i;
916 i++;
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700917 } else if ((mode&PROC_QUOTES) != 0) {
918 while (buffer[i] != '"' && i < endIndex) {
919 i++;
920 }
921 end = i;
922 i++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700924 while (i < endIndex && buffer[i] != term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 i++;
926 }
927 if (end < 0) {
928 end = i;
929 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700930
Evan Millarc64edde2009-04-18 12:26:32 -0700931 if (i < endIndex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 i++;
933 if ((mode&PROC_COMBINE) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700934 while (i < endIndex && buffer[i] == term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 i++;
936 }
937 }
938 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700939
Mark Salyzync6a41012014-04-24 13:05:18 -0700940 //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
943 char c = buffer[end];
944 buffer[end] = 0;
945 if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
946 char* end;
947 floatsData[di] = strtof(buffer+start, &end);
948 }
949 if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700950 if ((mode&PROC_CHAR) != 0) {
951 // Caller wants single first character returned as one long.
952 longsData[di] = buffer[start];
953 } else {
954 char* end;
955 longsData[di] = strtoll(buffer+start, &end, 10);
956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
958 if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
959 jstring str = env->NewStringUTF(buffer+start);
960 env->SetObjectArrayElement(outStrings, di, str);
961 }
962 buffer[end] = c;
963 di++;
964 }
965 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 env->ReleaseIntArrayElements(format, formatData, 0);
968 if (longsData != NULL) {
969 env->ReleaseLongArrayElements(outLongs, longsData, 0);
970 }
971 if (floatsData != NULL) {
972 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
973 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 return res;
976}
977
Evan Millarc64edde2009-04-18 12:26:32 -0700978jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700979 jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700980 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
981{
982 jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
983
Elliott Hughes69a017b2011-04-08 14:10:28 -0700984 jboolean result = android_os_Process_parseProcLineArray(env, clazz,
985 (char*) bufferArray, startIndex, endIndex, format, outStrings,
Evan Millarc64edde2009-04-18 12:26:32 -0700986 outLongs, outFloats);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700987
Evan Millarc64edde2009-04-18 12:26:32 -0700988 env->ReleaseByteArrayElements(buffer, bufferArray, 0);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700989
Evan Millarc64edde2009-04-18 12:26:32 -0700990 return result;
991}
992
993jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
994 jstring file, jintArray format, jobjectArray outStrings,
995 jlongArray outLongs, jfloatArray outFloats)
996{
997 if (file == NULL || format == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700998 jniThrowNullPointerException(env, NULL);
Evan Millarc64edde2009-04-18 12:26:32 -0700999 return JNI_FALSE;
1000 }
1001
1002 const char* file8 = env->GetStringUTFChars(file, NULL);
1003 if (file8 == NULL) {
1004 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1005 return JNI_FALSE;
1006 }
Nick Kralevich422dd00f2017-10-19 17:51:50 -07001007 int fd = open(file8, O_RDONLY | O_CLOEXEC);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001008
Evan Millarc64edde2009-04-18 12:26:32 -07001009 if (fd < 0) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001010 if (kDebugProc) {
1011 ALOGW("Unable to open process file: %s\n", file8);
1012 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001013 env->ReleaseStringUTFChars(file, file8);
Evan Millarc64edde2009-04-18 12:26:32 -07001014 return JNI_FALSE;
1015 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001016 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001017
Misha Wagnercc065fb2018-10-15 10:45:44 +01001018 std::vector<char> fileBuffer(kReadSize);
1019 int numBytesRead = 0;
1020 while (true) {
1021 // Resize buffer to make space for contents. This might be more than we need, but once we've
1022 // read we resize back down
1023 fileBuffer.resize(numBytesRead + kReadSize, 0);
1024 // Read in contents
1025 int len = TEMP_FAILURE_RETRY(read(fd, fileBuffer.data() + numBytesRead, kReadSize));
1026 numBytesRead += len;
1027 if (len < 0) {
1028 // If `len` is negative, an error occurred on read
1029 if (kDebugProc) {
1030 ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
1031 }
1032 close(fd);
1033 return JNI_FALSE;
1034 } else if (len == 0) {
1035 // If nothing read, we're done
1036 break;
1037 }
1038 }
1039 // Resize back down to the amount we read
1040 fileBuffer.resize(numBytesRead);
1041 // Terminate buffer with null byte
1042 fileBuffer.push_back('\0');
Evan Millarc64edde2009-04-18 12:26:32 -07001043 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001044
Misha Wagnercc065fb2018-10-15 10:45:44 +01001045 return android_os_Process_parseProcLineArray(env, clazz, fileBuffer.data(), 0, numBytesRead,
Evan Millarc64edde2009-04-18 12:26:32 -07001046 format, outStrings, outLongs, outFloats);
Evan Millarc64edde2009-04-18 12:26:32 -07001047}
1048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
1050 jobject binderObject)
1051{
1052 if (binderObject == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001053 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 return;
1055 }
1056
1057 sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
1058}
1059
1060void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
1061{
1062 if (pid > 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -07001063 ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 kill(pid, sig);
1065 }
1066}
1067
Dianne Hackborn906497c2010-05-10 15:57:38 -07001068void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
1069{
1070 if (pid > 0) {
1071 kill(pid, sig);
1072 }
1073}
1074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
1076{
1077 struct timespec ts;
1078
1079 int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 if (res != 0) {
1082 return (jlong) 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -07001083 }
1084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
1086 return (jlong) nanoseconds_to_milliseconds(when);
1087}
1088
1089static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
1090{
Sandeep Patilfcd4a4a2019-01-12 22:42:05 -08001091 ::android::meminfo::ProcMemInfo proc_mem(pid);
1092 uint64_t pss;
1093 if (!proc_mem.SmapsOrRollupPss(&pss)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 return (jlong) -1;
1095 }
1096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 // Return the Pss value in bytes, not kilobytes
1098 return pss * 1024;
1099}
1100
Tim Murrayfb076782018-11-27 12:22:22 -08001101static jlongArray android_os_Process_getRss(JNIEnv* env, jobject clazz, jint pid)
1102{
1103 // total, file, anon, swap
1104 jlong rss[4] = {0, 0, 0, 0};
1105 std::string status_path =
1106 android::base::StringPrintf("/proc/%d/status", pid);
1107 UniqueFile file = MakeUniqueFile(status_path.c_str(), "re");
1108
1109 char line[256];
Tim Murray8d652172018-12-12 16:26:47 -08001110 while (file != nullptr && fgets(line, sizeof(line), file.get())) {
Tim Murrayfb076782018-11-27 12:22:22 -08001111 jlong v;
1112 if ( sscanf(line, "VmRSS: %" SCNd64 " kB", &v) == 1) {
1113 rss[0] = v;
1114 } else if ( sscanf(line, "RssFile: %" SCNd64 " kB", &v) == 1) {
1115 rss[1] = v;
1116 } else if ( sscanf(line, "RssAnon: %" SCNd64 " kB", &v) == 1) {
1117 rss[2] = v;
1118 } else if ( sscanf(line, "VmSwap: %" SCNd64 " kB", &v) == 1) {
1119 rss[3] = v;
1120 }
1121 }
1122
1123 jlongArray rssArray = env->NewLongArray(4);
1124 if (rssArray == NULL) {
1125 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1126 return NULL;
1127 }
1128
1129 env->SetLongArrayRegion(rssArray, 0, 4, rss);
1130
1131 return rssArray;
1132}
1133
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001134jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
1135 jobjectArray commandNames)
1136{
1137 if (commandNames == NULL) {
1138 jniThrowNullPointerException(env, NULL);
1139 return NULL;
1140 }
1141
1142 Vector<String8> commands;
1143
1144 jsize count = env->GetArrayLength(commandNames);
1145
1146 for (int i=0; i<count; i++) {
1147 jobject obj = env->GetObjectArrayElement(commandNames, i);
1148 if (obj != NULL) {
1149 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
1150 if (str8 == NULL) {
1151 jniThrowNullPointerException(env, "Element in commandNames");
1152 return NULL;
1153 }
1154 commands.add(String8(str8));
1155 env->ReleaseStringUTFChars((jstring)obj, str8);
1156 } else {
1157 jniThrowNullPointerException(env, "Element in commandNames");
1158 return NULL;
1159 }
1160 }
1161
1162 Vector<jint> pids;
1163
1164 DIR *proc = opendir("/proc");
1165 if (proc == NULL) {
1166 fprintf(stderr, "/proc: %s\n", strerror(errno));
1167 return NULL;
1168 }
1169
1170 struct dirent *d;
1171 while ((d = readdir(proc))) {
1172 int pid = atoi(d->d_name);
1173 if (pid <= 0) continue;
1174
1175 char path[PATH_MAX];
1176 char data[PATH_MAX];
1177 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
1178
Nick Kralevich422dd00f2017-10-19 17:51:50 -07001179 int fd = open(path, O_RDONLY | O_CLOEXEC);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001180 if (fd < 0) {
1181 continue;
1182 }
1183 const int len = read(fd, data, sizeof(data)-1);
1184 close(fd);
1185
1186 if (len < 0) {
1187 continue;
1188 }
1189 data[len] = 0;
1190
1191 for (int i=0; i<len; i++) {
1192 if (data[i] == ' ') {
1193 data[i] = 0;
1194 break;
1195 }
1196 }
1197
1198 for (size_t i=0; i<commands.size(); i++) {
1199 if (commands[i] == data) {
1200 pids.add(pid);
1201 break;
1202 }
1203 }
1204 }
1205
1206 closedir(proc);
1207
1208 jintArray pidArray = env->NewIntArray(pids.size());
1209 if (pidArray == NULL) {
1210 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1211 return NULL;
1212 }
1213
1214 if (pids.size() > 0) {
1215 env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
1216 }
1217
1218 return pidArray;
1219}
1220
Colin Cross0769e552014-06-03 13:25:35 -07001221jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
1222{
1223 return killProcessGroup(uid, pid, SIGKILL);
1224}
1225
1226void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
1227{
1228 return removeAllProcessGroups();
1229}
1230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231static const JNINativeMethod methods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 {"getUidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
1233 {"getGidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
1234 {"setThreadPriority", "(II)V", (void*)android_os_Process_setThreadPriority},
Glenn Kasten6793ac92011-07-13 12:44:12 -07001235 {"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler},
Christopher Tate160edb32010-06-30 17:46:30 -07001236 {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 {"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority},
1238 {"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority},
Srinath Sridharan1b15d132016-07-19 15:16:11 -07001239 {"getThreadScheduler", "(I)I", (void*)android_os_Process_getThreadScheduler},
San Mehate9d376b2009-04-21 14:06:36 -07001240 {"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup},
Joel Fernandes474d3112017-04-04 16:32:15 -07001241 {"setThreadGroupAndCpuset", "(II)V", (void*)android_os_Process_setThreadGroupAndCpuset},
Jeff Sharkey9e57c412013-01-17 14:12:41 -08001242 {"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup},
1243 {"getProcessGroup", "(I)I", (void*)android_os_Process_getProcessGroup},
Martijn Coenencd4bdf32016-03-03 17:30:52 +01001244 {"getExclusiveCores", "()[I", (void*)android_os_Process_getExclusiveCores},
Rom Lemarchand5534ba92013-07-12 16:15:36 -07001245 {"setSwappiness", "(IZ)Z", (void*)android_os_Process_setSwappiness},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 {"setArgV0", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
1247 {"setUid", "(I)I", (void*)android_os_Process_setUid},
1248 {"setGid", "(I)I", (void*)android_os_Process_setGid},
1249 {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
Dianne Hackborn906497c2010-05-10 15:57:38 -07001250 {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
Marco Nelissen0bca96b2009-07-17 12:59:25 -07001251 {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
Dianne Hackborn59325eb2012-05-09 18:45:20 -07001252 {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
1254 {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
1255 {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
Evan Millarc64edde2009-04-18 12:26:32 -07001256 {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
1258 {"getPss", "(I)J", (void*)android_os_Process_getPss},
Tim Murrayfb076782018-11-27 12:22:22 -08001259 {"getRss", "(I)[J", (void*)android_os_Process_getRss},
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001260 {"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
Colin Cross0769e552014-06-03 13:25:35 -07001262 {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
1263 {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264};
1265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266int register_android_os_Process(JNIEnv* env)
1267{
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001268 return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269}