blob: ffa710752956f0f569279624024239f9aaa0d067 [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>
Narayan Kamatha23fcd72014-03-28 13:39:21 +000025#include <cutils/process_name.h>
Glenn Kastenf1b56442012-03-15 16:33:43 -070026#include <cutils/sched_policy.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#include <utils/String8.h>
28#include <utils/Vector.h>
Colin Cross0769e552014-06-03 13:25:35 -070029#include <processgroup/processgroup.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030
Andreas Gampeed6b9df2014-11-20 22:02:20 -080031#include "core_jni_helpers.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032
33#include "android_util_Binder.h"
34#include "JNIHelp.h"
35
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036#include <dirent.h>
37#include <fcntl.h>
38#include <grp.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070039#include <inttypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040#include <pwd.h>
41#include <signal.h>
Mark Salyzync6a41012014-04-24 13:05:18 -070042#include <sys/errno.h>
43#include <sys/resource.h>
44#include <sys/stat.h>
45#include <sys/types.h>
Glenn Kasten6af763b2011-05-04 17:58:57 -070046#include <unistd.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
Christopher Tate160edb32010-06-30 17:46:30 -070048#define GUARD_THREAD_PRIORITY 0
San Mehata5109a82009-10-29 11:48:50 -070049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050using namespace android;
51
Andreas Gampe0f0b4912014-11-12 08:03:48 -080052static const bool kDebugPolicy = false;
53static const bool kDebugProc = false;
54
Christopher Tate160edb32010-06-30 17:46:30 -070055#if GUARD_THREAD_PRIORITY
56Mutex gKeyCreateMutex;
57static pthread_key_t gBgKey = -1;
58#endif
59
Glenn Kastenf1b56442012-03-15 16:33:43 -070060// For both of these, err should be in the errno range (positive), not a status_t (negative)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070061static void signalExceptionForError(JNIEnv* env, int err, int tid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 switch (err) {
63 case EINVAL:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070064 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
65 "Invalid argument: %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 break;
67 case ESRCH:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070068 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
69 "Given thread %d does not exist", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 break;
71 case EPERM:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070072 jniThrowExceptionFmt(env, "java/lang/SecurityException",
73 "No permission to modify given thread %d", tid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 break;
75 default:
76 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
77 break;
78 }
79}
80
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070081static void signalExceptionForPriorityError(JNIEnv* env, int err, int tid) {
San Mehate9d376b2009-04-21 14:06:36 -070082 switch (err) {
San Mehate9d376b2009-04-21 14:06:36 -070083 case EACCES:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070084 jniThrowExceptionFmt(env, "java/lang/SecurityException",
85 "No permission to set the priority of %d", tid);
San Mehate9d376b2009-04-21 14:06:36 -070086 break;
87 default:
Ruben Brunk4c0c4df2016-08-09 12:46:13 -070088 signalExceptionForError(env, err, tid);
89 break;
90 }
91
92}
93
94static void signalExceptionForGroupError(JNIEnv* env, int err, int tid) {
95 switch (err) {
96 case EACCES:
97 jniThrowExceptionFmt(env, "java/lang/SecurityException",
98 "No permission to set the group of %d", tid);
99 break;
100 default:
101 signalExceptionForError(env, err, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700102 break;
103 }
104}
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
107{
108 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700109 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 return -1;
111 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 const jchar* str16 = env->GetStringCritical(name, 0);
114 String8 name8;
115 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800116 name8 = String8(reinterpret_cast<const char16_t*>(str16),
117 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 env->ReleaseStringCritical(name, str16);
119 }
120
121 const size_t N = name8.size();
122 if (N > 0) {
123 const char* str = name8.string();
124 for (size_t i=0; i<N; i++) {
125 if (str[i] < '0' || str[i] > '9') {
126 struct passwd* pwd = getpwnam(str);
127 if (pwd == NULL) {
128 return -1;
129 }
130 return pwd->pw_uid;
131 }
132 }
133 return atoi(str);
134 }
135 return -1;
136}
137
138jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
139{
140 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700141 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 return -1;
143 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 const jchar* str16 = env->GetStringCritical(name, 0);
146 String8 name8;
147 if (str16) {
Dan Albert66987492014-11-20 11:41:21 -0800148 name8 = String8(reinterpret_cast<const char16_t*>(str16),
149 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 env->ReleaseStringCritical(name, str16);
151 }
152
153 const size_t N = name8.size();
154 if (N > 0) {
155 const char* str = name8.string();
156 for (size_t i=0; i<N; i++) {
157 if (str[i] < '0' || str[i] > '9') {
158 struct group* grp = getgrnam(str);
159 if (grp == NULL) {
160 return -1;
161 }
162 return grp->gr_gid;
163 }
164 }
165 return atoi(str);
166 }
167 return -1;
168}
169
Glenn Kastenf1b56442012-03-15 16:33:43 -0700170void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int tid, jint grp)
San Mehate9d376b2009-04-21 14:06:36 -0700171{
Mark Salyzync6a41012014-04-24 13:05:18 -0700172 ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
Glenn Kastenf1b56442012-03-15 16:33:43 -0700173 SchedPolicy sp = (SchedPolicy) grp;
174 int res = set_sched_policy(tid, sp);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800175 if (res != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700176 signalExceptionForGroupError(env, -res, tid);
San Mehate9d376b2009-04-21 14:06:36 -0700177 }
San Mehate9d376b2009-04-21 14:06:36 -0700178}
179
Elliott Hughes69a017b2011-04-08 14:10:28 -0700180void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
San Mehat3e458242009-05-19 14:44:16 -0700181{
Mark Salyzync6a41012014-04-24 13:05:18 -0700182 ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp);
San Mehat3e458242009-05-19 14:44:16 -0700183 DIR *d;
San Mehat3e458242009-05-19 14:44:16 -0700184 char proc_path[255];
185 struct dirent *de;
186
Glenn Kastenf1b56442012-03-15 16:33:43 -0700187 if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700188 signalExceptionForGroupError(env, EINVAL, pid);
San Mehat3e458242009-05-19 14:44:16 -0700189 return;
190 }
191
Glenn Kastenf1b56442012-03-15 16:33:43 -0700192 bool isDefault = false;
193 if (grp < 0) {
194 grp = SP_FOREGROUND;
195 isDefault = true;
196 }
197 SchedPolicy sp = (SchedPolicy) grp;
198
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800199 if (kDebugPolicy) {
200 char cmdline[32];
201 int fd;
San Mehata5109a82009-10-29 11:48:50 -0700202
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800203 strcpy(cmdline, "unknown");
San Mehata5109a82009-10-29 11:48:50 -0700204
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800205 sprintf(proc_path, "/proc/%d/cmdline", pid);
206 fd = open(proc_path, O_RDONLY);
207 if (fd >= 0) {
208 int rc = read(fd, cmdline, sizeof(cmdline)-1);
209 cmdline[rc] = 0;
210 close(fd);
211 }
212
213 if (sp == SP_BACKGROUND) {
214 ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
215 } else {
216 ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
217 }
San Mehata5109a82009-10-29 11:48:50 -0700218 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700219
San Mehat3e458242009-05-19 14:44:16 -0700220 sprintf(proc_path, "/proc/%d/task", pid);
221 if (!(d = opendir(proc_path))) {
San Mehat1fd0ec72009-06-15 16:56:52 -0700222 // If the process exited on us, don't generate an exception
223 if (errno != ENOENT)
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700224 signalExceptionForGroupError(env, errno, pid);
San Mehat3e458242009-05-19 14:44:16 -0700225 return;
226 }
227
228 while ((de = readdir(d))) {
San Mehat7e637892009-08-06 13:19:19 -0700229 int t_pid;
230 int t_pri;
231
San Mehat3e458242009-05-19 14:44:16 -0700232 if (de->d_name[0] == '.')
233 continue;
San Mehat7e637892009-08-06 13:19:19 -0700234 t_pid = atoi(de->d_name);
San Mehat1fd0ec72009-06-15 16:56:52 -0700235
San Mehat7e637892009-08-06 13:19:19 -0700236 if (!t_pid) {
Steve Block3762c312012-01-06 19:20:56 +0000237 ALOGE("Error getting pid for '%s'\n", de->d_name);
San Mehat7e637892009-08-06 13:19:19 -0700238 continue;
239 }
240
Glenn Kasten07b04652012-04-23 15:00:43 -0700241 t_pri = getpriority(PRIO_PROCESS, t_pid);
San Mehat7e637892009-08-06 13:19:19 -0700242
Glenn Kasten07b04652012-04-23 15:00:43 -0700243 if (t_pri <= ANDROID_PRIORITY_AUDIO) {
244 int scheduler = sched_getscheduler(t_pid);
245 if ((scheduler == SCHED_FIFO) || (scheduler == SCHED_RR)) {
Tim Murray9e41c742015-06-08 14:56:53 -0700246 // This task wants to stay in its current audio group so it can keep its budget
247 // don't update its cpuset or cgroup
Glenn Kasten07b04652012-04-23 15:00:43 -0700248 continue;
249 }
250 }
251
252 if (isDefault) {
Glenn Kastenf1b56442012-03-15 16:33:43 -0700253 if (t_pri >= ANDROID_PRIORITY_BACKGROUND) {
254 // This task wants to stay at background
Tim Murray9e41c742015-06-08 14:56:53 -0700255 // update its cpuset so it doesn't only run on bg core(s)
256#ifdef ENABLE_CPUSETS
257 int err = set_cpuset_policy(t_pid, sp);
258 if (err != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700259 signalExceptionForGroupError(env, -err, t_pid);
Tim Murray9e41c742015-06-08 14:56:53 -0700260 break;
261 }
262#endif
Glenn Kastenf1b56442012-03-15 16:33:43 -0700263 continue;
264 }
San Mehat7e637892009-08-06 13:19:19 -0700265 }
Tim Murray9e41c742015-06-08 14:56:53 -0700266 int err;
267#ifdef ENABLE_CPUSETS
268 // set both cpuset and cgroup for general threads
269 err = set_cpuset_policy(t_pid, sp);
Glenn Kastenf1b56442012-03-15 16:33:43 -0700270 if (err != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700271 signalExceptionForGroupError(env, -err, t_pid);
San Mehat0a42b812009-12-03 12:21:28 -0800272 break;
San Mehat242d65b2009-09-12 10:10:37 -0700273 }
Tim Murray9e41c742015-06-08 14:56:53 -0700274#endif
275
276 err = set_sched_policy(t_pid, sp);
277 if (err != NO_ERROR) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700278 signalExceptionForGroupError(env, -err, t_pid);
Tim Murray9e41c742015-06-08 14:56:53 -0700279 break;
280 }
281
San Mehat3e458242009-05-19 14:44:16 -0700282 }
283 closedir(d);
284}
285
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800286jint android_os_Process_getProcessGroup(JNIEnv* env, jobject clazz, jint pid)
287{
288 SchedPolicy sp;
289 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700290 signalExceptionForGroupError(env, errno, pid);
Jeff Sharkey9e57c412013-01-17 14:12:41 -0800291 }
292 return (int) sp;
293}
294
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100295#ifdef ENABLE_CPUSETS
296/** Sample CPUset list format:
297 * 0-3,4,6-8
298 */
299static void parse_cpuset_cpus(char *cpus, cpu_set_t *cpu_set) {
300 unsigned int start, end, matched, i;
301 char *cpu_range = strtok(cpus, ",");
302 while (cpu_range != NULL) {
303 start = end = 0;
304 matched = sscanf(cpu_range, "%u-%u", &start, &end);
305 cpu_range = strtok(NULL, ",");
306 if (start >= CPU_SETSIZE) {
307 ALOGE("parse_cpuset_cpus: ignoring CPU number larger than %d.", CPU_SETSIZE);
308 continue;
309 } else if (end >= CPU_SETSIZE) {
310 ALOGE("parse_cpuset_cpus: ignoring CPU numbers larger than %d.", CPU_SETSIZE);
311 end = CPU_SETSIZE - 1;
312 }
313 if (matched == 1) {
314 CPU_SET(start, cpu_set);
315 } else if (matched == 2) {
316 for (i = start; i <= end; i++) {
317 CPU_SET(i, cpu_set);
318 }
319 } else {
320 ALOGE("Failed to match cpus");
321 }
322 }
323 return;
324}
325
326/**
327 * Stores the CPUs assigned to the cpuset corresponding to the
328 * SchedPolicy in the passed in cpu_set.
329 */
330static void get_cpuset_cores_for_policy(SchedPolicy policy, cpu_set_t *cpu_set)
331{
332 FILE *file;
333 const char *filename;
334
335 CPU_ZERO(cpu_set);
336
337 switch (policy) {
338 case SP_BACKGROUND:
339 filename = "/dev/cpuset/background/cpus";
340 break;
341 case SP_FOREGROUND:
342 case SP_AUDIO_APP:
343 case SP_AUDIO_SYS:
344 filename = "/dev/cpuset/foreground/cpus";
345 break;
346 case SP_TOP_APP:
347 filename = "/dev/cpuset/top-app/cpus";
348 break;
349 default:
350 filename = NULL;
351 }
352
353 if (!filename) return;
354
355 file = fopen(filename, "re");
356 if (file != NULL) {
357 // Parse cpus string
358 char *line = NULL;
359 size_t len = 0;
360 ssize_t num_read = getline(&line, &len, file);
361 fclose (file);
362 if (num_read > 0) {
363 parse_cpuset_cpus(line, cpu_set);
364 } else {
365 ALOGE("Failed to read %s", filename);
366 }
367 free(line);
368 }
369 return;
370}
371#endif
372
373
374/**
375 * Determine CPU cores exclusively assigned to the
376 * cpuset corresponding to the SchedPolicy and store
377 * them in the passed in cpu_set_t
378 */
379void get_exclusive_cpuset_cores(SchedPolicy policy, cpu_set_t *cpu_set) {
380#ifdef ENABLE_CPUSETS
381 int i;
382 cpu_set_t tmp_set;
383 get_cpuset_cores_for_policy(policy, cpu_set);
384 for (i = 0; i < SP_CNT; i++) {
385 if ((SchedPolicy) i == policy) continue;
386 get_cpuset_cores_for_policy((SchedPolicy)i, &tmp_set);
387 // First get cores exclusive to one set or the other
388 CPU_XOR(&tmp_set, cpu_set, &tmp_set);
389 // Then get the ones only in cpu_set
390 CPU_AND(cpu_set, cpu_set, &tmp_set);
391 }
392#else
393 (void) policy;
394 CPU_ZERO(cpu_set);
395#endif
396 return;
397}
398
399jintArray android_os_Process_getExclusiveCores(JNIEnv* env, jobject clazz) {
400 SchedPolicy sp;
401 cpu_set_t cpu_set;
402 jintArray cpus;
403 int pid = getpid();
404 if (get_sched_policy(pid, &sp) != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700405 signalExceptionForGroupError(env, errno, pid);
Martijn Coenencd4bdf32016-03-03 17:30:52 +0100406 return NULL;
407 }
408 get_exclusive_cpuset_cores(sp, &cpu_set);
409 int num_cpus = CPU_COUNT(&cpu_set);
410 cpus = env->NewIntArray(num_cpus);
411 if (cpus == NULL) {
412 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
413 return NULL;
414 }
415
416 jint* cpu_elements = env->GetIntArrayElements(cpus, 0);
417 int count = 0;
418 for (int i = 0; i < CPU_SETSIZE && count < num_cpus; i++) {
419 if (CPU_ISSET(i, &cpu_set)) {
420 cpu_elements[count++] = i;
421 }
422 }
423
424 env->ReleaseIntArrayElements(cpus, cpu_elements, 0);
425 return cpus;
426}
427
Christopher Tate160edb32010-06-30 17:46:30 -0700428static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
429 // Establishes the calling thread as illegal to put into the background.
430 // Typically used only for the system process's main looper.
431#if GUARD_THREAD_PRIORITY
Elliott Hughes06451fe2014-08-18 10:26:52 -0700432 ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
Christopher Tate160edb32010-06-30 17:46:30 -0700433 {
434 Mutex::Autolock _l(gKeyCreateMutex);
435 if (gBgKey == -1) {
436 pthread_key_create(&gBgKey, NULL);
437 }
438 }
439
440 // inverted: not-okay, we set a sentinel value
441 pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
442#endif
443}
444
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700445jint android_os_Process_getThreadScheduler(JNIEnv* env, jclass clazz,
446 jint tid)
447{
448 int policy = 0;
449// linux has sched_getscheduler(), others don't.
450#if defined(__linux__)
451 errno = 0;
452 policy = sched_getscheduler(tid);
453 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700454 signalExceptionForPriorityError(env, errno, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700455 }
456#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700457 signalExceptionForPriorityError(env, ENOSYS, tid);
Srinath Sridharan1b15d132016-07-19 15:16:11 -0700458#endif
459 return policy;
460}
461
Glenn Kasten6793ac92011-07-13 12:44:12 -0700462void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
463 jint tid, jint policy, jint pri)
464{
Yabin Cui65b4a682014-11-10 12:15:46 -0800465// linux has sched_setscheduler(), others don't.
466#if defined(__linux__)
Glenn Kasten6793ac92011-07-13 12:44:12 -0700467 struct sched_param param;
468 param.sched_priority = pri;
469 int rc = sched_setscheduler(tid, policy, &param);
470 if (rc) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700471 signalExceptionForPriorityError(env, errno, tid);
Glenn Kasten6793ac92011-07-13 12:44:12 -0700472 }
Glenn Kastencc767192012-01-17 08:38:51 -0800473#else
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700474 signalExceptionForPriorityError(env, ENOSYS, tid);
Glenn Kastencc767192012-01-17 08:38:51 -0800475#endif
Glenn Kasten6793ac92011-07-13 12:44:12 -0700476}
477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
479 jint pid, jint pri)
480{
Christopher Tate160edb32010-06-30 17:46:30 -0700481#if GUARD_THREAD_PRIORITY
482 // if we're putting the current thread into the background, check the TLS
483 // to make sure this thread isn't guarded. If it is, raise an exception.
484 if (pri >= ANDROID_PRIORITY_BACKGROUND) {
Elliott Hughes06451fe2014-08-18 10:26:52 -0700485 if (pid == gettid()) {
Christopher Tate160edb32010-06-30 17:46:30 -0700486 void* bgOk = pthread_getspecific(gBgKey);
487 if (bgOk == ((void*)0xbaad)) {
Steve Block3762c312012-01-06 19:20:56 +0000488 ALOGE("Thread marked fg-only put self in background!");
Christopher Tate160edb32010-06-30 17:46:30 -0700489 jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
490 return;
491 }
492 }
493 }
494#endif
495
Dianne Hackborn887f3552009-12-07 17:59:37 -0800496 int rc = androidSetThreadPriority(pid, pri);
497 if (rc != 0) {
498 if (rc == INVALID_OPERATION) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700499 signalExceptionForPriorityError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800500 } else {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700501 signalExceptionForGroupError(env, errno, pid);
Dianne Hackborn887f3552009-12-07 17:59:37 -0800502 }
San Mehat242d65b2009-09-12 10:10:37 -0700503 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700504
Mark Salyzync6a41012014-04-24 13:05:18 -0700505 //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 // pid, pri, getpriority(PRIO_PROCESS, pid));
507}
508
509void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
510 jint pri)
511{
Elliott Hughes06451fe2014-08-18 10:26:52 -0700512 android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513}
514
515jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
516 jint pid)
517{
518 errno = 0;
519 jint pri = getpriority(PRIO_PROCESS, pid);
520 if (errno != 0) {
Ruben Brunk4c0c4df2016-08-09 12:46:13 -0700521 signalExceptionForPriorityError(env, errno, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
Mark Salyzync6a41012014-04-24 13:05:18 -0700523 //ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 return pri;
525}
526
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700527jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
528 jint pid, jboolean is_increased)
529{
530 char text[64];
531
532 if (is_increased) {
533 strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
534 } else {
535 strcpy(text, "/sys/fs/cgroup/memory/tasks");
536 }
537
538 struct stat st;
539 if (stat(text, &st) || !S_ISREG(st.st_mode)) {
540 return false;
541 }
542
543 int fd = open(text, O_WRONLY);
544 if (fd >= 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -0700545 sprintf(text, "%" PRId32, pid);
Rom Lemarchand5534ba92013-07-12 16:15:36 -0700546 write(fd, text, strlen(text));
547 close(fd);
548 }
549
550 return true;
551}
552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
554{
555 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700556 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 return;
558 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 const jchar* str = env->GetStringCritical(name, 0);
561 String8 name8;
562 if (str) {
Dan Albert66987492014-11-20 11:41:21 -0800563 name8 = String8(reinterpret_cast<const char16_t*>(str),
564 env->GetStringLength(name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 env->ReleaseStringCritical(name, str);
566 }
567
Dmitriy Filchenko342c7dc2016-07-12 15:40:54 -0700568 if (!name8.isEmpty()) {
Dmitriy Filchenkof5b6e552016-07-18 16:00:35 -0700569 AndroidRuntime::getRuntime()->setArgv0(name8.string(), true /* setProcName */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
571}
572
573jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
574{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 return setuid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576}
577
578jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
579{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 return setgid(uid) == 0 ? 0 : errno;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581}
582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583static int pid_compare(const void* v1, const void* v2)
584{
Mark Salyzync6a41012014-04-24 13:05:18 -0700585 //ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 return *((const jint*)v1) - *((const jint*)v2);
587}
588
Elliott Hughesc367d482013-10-29 13:12:55 -0700589static jlong getFreeMemoryImpl(const char* const sums[], const size_t sumsLen[], size_t num)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590{
591 int fd = open("/proc/meminfo", O_RDONLY);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 if (fd < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000594 ALOGW("Unable to open /proc/meminfo");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 return -1;
596 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598 char buffer[256];
599 const int len = read(fd, buffer, sizeof(buffer)-1);
600 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 if (len < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000603 ALOGW("Unable to read /proc/meminfo");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 return -1;
605 }
606 buffer[len] = 0;
607
Elliott Hughesc367d482013-10-29 13:12:55 -0700608 size_t numFound = 0;
Marco Nelissen0bca96b2009-07-17 12:59:25 -0700609 jlong mem = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 char* p = buffer;
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700612 while (*p && numFound < num) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 int i = 0;
614 while (sums[i]) {
615 if (strncmp(p, sums[i], sumsLen[i]) == 0) {
616 p += sumsLen[i];
617 while (*p == ' ') p++;
618 char* num = p;
619 while (*p >= '0' && *p <= '9') p++;
620 if (*p != 0) {
621 *p = 0;
622 p++;
623 if (*p == 0) p--;
624 }
Marco Nelissen0bca96b2009-07-17 12:59:25 -0700625 mem += atoll(num) * 1024;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 numFound++;
627 break;
628 }
629 i++;
630 }
631 p++;
632 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 return numFound > 0 ? mem : -1;
635}
636
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700637static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
638{
639 static const char* const sums[] = { "MemFree:", "Cached:", NULL };
Elliott Hughesc367d482013-10-29 13:12:55 -0700640 static const size_t sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 };
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700641 return getFreeMemoryImpl(sums, sumsLen, 2);
642}
643
644static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
645{
646 static const char* const sums[] = { "MemTotal:", NULL };
Elliott Hughesc367d482013-10-29 13:12:55 -0700647 static const size_t sumsLen[] = { strlen("MemTotal:"), 0 };
Dianne Hackborn59325eb2012-05-09 18:45:20 -0700648 return getFreeMemoryImpl(sums, sumsLen, 1);
649}
650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
652 jobjectArray reqFields, jlongArray outFields)
653{
Steve Block6215d3f2012-01-04 20:05:49 +0000654 //ALOGI("getMemInfo: %p %p", reqFields, outFields);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700657 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 return;
659 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 const char* file8 = env->GetStringUTFChars(fileStr, NULL);
662 if (file8 == NULL) {
663 return;
664 }
665 String8 file(file8);
666 env->ReleaseStringUTFChars(fileStr, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 jsize count = env->GetArrayLength(reqFields);
669 if (count > env->GetArrayLength(outFields)) {
670 jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
671 return;
672 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 Vector<String8> fields;
675 int i;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 for (i=0; i<count; i++) {
678 jobject obj = env->GetObjectArrayElement(reqFields, i);
679 if (obj != NULL) {
680 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
Steve Block6215d3f2012-01-04 20:05:49 +0000681 //ALOGI("String at %d: %p = %s", i, obj, str8);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 if (str8 == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700683 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 return;
685 }
686 fields.add(String8(str8));
687 env->ReleaseStringUTFChars((jstring)obj, str8);
688 } else {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700689 jniThrowNullPointerException(env, "Element in reqFields");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 return;
691 }
692 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
695 if (sizesArray == NULL) {
696 return;
697 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700698
Mark Salyzync6a41012014-04-24 13:05:18 -0700699 //ALOGI("Clearing %" PRId32 " sizes", count);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 for (i=0; i<count; i++) {
701 sizesArray[i] = 0;
702 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 int fd = open(file.string(), O_RDONLY);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 if (fd >= 0) {
707 const size_t BUFFER_SIZE = 2048;
708 char* buffer = (char*)malloc(BUFFER_SIZE);
709 int len = read(fd, buffer, BUFFER_SIZE-1);
710 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 if (len < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000713 ALOGW("Unable to read %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 len = 0;
715 }
716 buffer[len] = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 int foundCount = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 char* p = buffer;
721 while (*p && foundCount < count) {
722 bool skipToEol = true;
Steve Block6215d3f2012-01-04 20:05:49 +0000723 //ALOGI("Parsing at: %s", p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 for (i=0; i<count; i++) {
725 const String8& field = fields[i];
726 if (strncmp(p, field.string(), field.length()) == 0) {
727 p += field.length();
Amith Yamasaniadd868c2009-06-25 11:57:40 -0700728 while (*p == ' ' || *p == '\t') p++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 char* num = p;
730 while (*p >= '0' && *p <= '9') p++;
731 skipToEol = *p != '\n';
732 if (*p != 0) {
733 *p = 0;
734 p++;
735 }
736 char* end;
737 sizesArray[i] = strtoll(num, &end, 10);
Mark Salyzync6a41012014-04-24 13:05:18 -0700738 //ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 foundCount++;
740 break;
741 }
742 }
743 if (skipToEol) {
744 while (*p && *p != '\n') {
745 p++;
746 }
747 if (*p == '\n') {
748 p++;
749 }
750 }
751 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 free(buffer);
754 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000755 ALOGW("Unable to open %s", file.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700757
Steve Block6215d3f2012-01-04 20:05:49 +0000758 //ALOGI("Done!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 env->ReleaseLongArrayElements(outFields, sizesArray, 0);
760}
761
762jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
763 jstring file, jintArray lastArray)
764{
765 if (file == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -0700766 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 return NULL;
768 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 const char* file8 = env->GetStringUTFChars(file, NULL);
771 if (file8 == NULL) {
772 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
773 return NULL;
774 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 DIR* dirp = opendir(file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 if(dirp == NULL) {
781 return NULL;
782 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 jsize curCount = 0;
785 jint* curData = NULL;
786 if (lastArray != NULL) {
787 curCount = env->GetArrayLength(lastArray);
788 curData = env->GetIntArrayElements(lastArray, 0);
789 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 jint curPos = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 struct dirent* entry;
794 while ((entry=readdir(dirp)) != NULL) {
795 const char* p = entry->d_name;
796 while (*p) {
797 if (*p < '0' || *p > '9') break;
798 p++;
799 }
800 if (*p != 0) continue;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 char* end;
803 int pid = strtol(entry->d_name, &end, 10);
Steve Block6215d3f2012-01-04 20:05:49 +0000804 //ALOGI("File %s pid=%d\n", entry->d_name, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 if (curPos >= curCount) {
806 jsize newCount = (curCount == 0) ? 10 : (curCount*2);
807 jintArray newArray = env->NewIntArray(newCount);
808 if (newArray == NULL) {
809 closedir(dirp);
810 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
811 return NULL;
812 }
813 jint* newData = env->GetIntArrayElements(newArray, 0);
814 if (curData != NULL) {
815 memcpy(newData, curData, sizeof(jint)*curCount);
816 env->ReleaseIntArrayElements(lastArray, curData, 0);
817 }
818 lastArray = newArray;
819 curCount = newCount;
820 curData = newData;
821 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 curData[curPos] = pid;
824 curPos++;
825 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 closedir(dirp);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 if (curData != NULL && curPos > 0) {
830 qsort(curData, curPos, sizeof(jint), pid_compare);
831 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 while (curPos < curCount) {
834 curData[curPos] = -1;
835 curPos++;
836 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 if (curData != NULL) {
839 env->ReleaseIntArrayElements(lastArray, curData, 0);
840 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 return lastArray;
843}
844
845enum {
846 PROC_TERM_MASK = 0xff,
847 PROC_ZERO_TERM = 0,
848 PROC_SPACE_TERM = ' ',
849 PROC_COMBINE = 0x100,
850 PROC_PARENS = 0x200,
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700851 PROC_QUOTES = 0x400,
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700852 PROC_CHAR = 0x800,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 PROC_OUT_STRING = 0x1000,
854 PROC_OUT_LONG = 0x2000,
855 PROC_OUT_FLOAT = 0x4000,
856};
857
Evan Millarc64edde2009-04-18 12:26:32 -0700858jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700859 char* buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700860 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861{
Elliott Hughes69a017b2011-04-08 14:10:28 -0700862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 const jsize NF = env->GetArrayLength(format);
864 const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
865 const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
866 const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 jint* formatData = env->GetIntArrayElements(format, 0);
869 jlong* longsData = outLongs ?
870 env->GetLongArrayElements(outLongs, 0) : NULL;
871 jfloat* floatsData = outFloats ?
872 env->GetFloatArrayElements(outFloats, 0) : NULL;
873 if (formatData == NULL || (NL > 0 && longsData == NULL)
874 || (NR > 0 && floatsData == NULL)) {
875 if (formatData != NULL) {
876 env->ReleaseIntArrayElements(format, formatData, 0);
877 }
878 if (longsData != NULL) {
879 env->ReleaseLongArrayElements(outLongs, longsData, 0);
880 }
881 if (floatsData != NULL) {
882 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
883 }
884 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
885 return JNI_FALSE;
886 }
887
Evan Millarc64edde2009-04-18 12:26:32 -0700888 jsize i = startIndex;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 jsize di = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 jboolean res = JNI_TRUE;
Elliott Hughes69a017b2011-04-08 14:10:28 -0700892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 for (jsize fi=0; fi<NF; fi++) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700894 jint mode = formatData[fi];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 if ((mode&PROC_PARENS) != 0) {
896 i++;
Bernhard Rosenkränzer3b1e22e2014-11-17 22:30:56 +0100897 } else if ((mode&PROC_QUOTES) != 0) {
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700898 if (buffer[i] == '"') {
899 i++;
900 } else {
901 mode &= ~PROC_QUOTES;
902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904 const char term = (char)(mode&PROC_TERM_MASK);
905 const jsize start = i;
Evan Millarc64edde2009-04-18 12:26:32 -0700906 if (i >= endIndex) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -0800907 if (kDebugProc) {
908 ALOGW("Ran off end of data @%d", i);
909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 res = JNI_FALSE;
911 break;
912 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 jsize end = -1;
915 if ((mode&PROC_PARENS) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700916 while (i < endIndex && buffer[i] != ')') {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 i++;
918 }
919 end = i;
920 i++;
Dianne Hackborn13ac0412013-06-25 19:34:49 -0700921 } else if ((mode&PROC_QUOTES) != 0) {
922 while (buffer[i] != '"' && i < endIndex) {
923 i++;
924 }
925 end = i;
926 i++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
Elliott Hughesc367d482013-10-29 13:12:55 -0700928 while (i < endIndex && buffer[i] != term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 i++;
930 }
931 if (end < 0) {
932 end = i;
933 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700934
Evan Millarc64edde2009-04-18 12:26:32 -0700935 if (i < endIndex) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 i++;
937 if ((mode&PROC_COMBINE) != 0) {
Elliott Hughesc367d482013-10-29 13:12:55 -0700938 while (i < endIndex && buffer[i] == term) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 i++;
940 }
941 }
942 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700943
Mark Salyzync6a41012014-04-24 13:05:18 -0700944 //ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
947 char c = buffer[end];
948 buffer[end] = 0;
949 if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
950 char* end;
951 floatsData[di] = strtof(buffer+start, &end);
952 }
953 if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -0700954 if ((mode&PROC_CHAR) != 0) {
955 // Caller wants single first character returned as one long.
956 longsData[di] = buffer[start];
957 } else {
958 char* end;
959 longsData[di] = strtoll(buffer+start, &end, 10);
960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
962 if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
963 jstring str = env->NewStringUTF(buffer+start);
964 env->SetObjectArrayElement(outStrings, di, str);
965 }
966 buffer[end] = c;
967 di++;
968 }
969 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 env->ReleaseIntArrayElements(format, formatData, 0);
972 if (longsData != NULL) {
973 env->ReleaseLongArrayElements(outLongs, longsData, 0);
974 }
975 if (floatsData != NULL) {
976 env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
977 }
Elliott Hughes69a017b2011-04-08 14:10:28 -0700978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 return res;
980}
981
Evan Millarc64edde2009-04-18 12:26:32 -0700982jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
Elliott Hughes69a017b2011-04-08 14:10:28 -0700983 jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
Evan Millarc64edde2009-04-18 12:26:32 -0700984 jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
985{
986 jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
987
Elliott Hughes69a017b2011-04-08 14:10:28 -0700988 jboolean result = android_os_Process_parseProcLineArray(env, clazz,
989 (char*) bufferArray, startIndex, endIndex, format, outStrings,
Evan Millarc64edde2009-04-18 12:26:32 -0700990 outLongs, outFloats);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700991
Evan Millarc64edde2009-04-18 12:26:32 -0700992 env->ReleaseByteArrayElements(buffer, bufferArray, 0);
Elliott Hughes69a017b2011-04-08 14:10:28 -0700993
Evan Millarc64edde2009-04-18 12:26:32 -0700994 return result;
995}
996
997jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
998 jstring file, jintArray format, jobjectArray outStrings,
999 jlongArray outLongs, jfloatArray outFloats)
1000{
1001 if (file == NULL || format == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001002 jniThrowNullPointerException(env, NULL);
Evan Millarc64edde2009-04-18 12:26:32 -07001003 return JNI_FALSE;
1004 }
1005
1006 const char* file8 = env->GetStringUTFChars(file, NULL);
1007 if (file8 == NULL) {
1008 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1009 return JNI_FALSE;
1010 }
1011 int fd = open(file8, O_RDONLY);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001012
Evan Millarc64edde2009-04-18 12:26:32 -07001013 if (fd < 0) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001014 if (kDebugProc) {
1015 ALOGW("Unable to open process file: %s\n", file8);
1016 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001017 env->ReleaseStringUTFChars(file, file8);
Evan Millarc64edde2009-04-18 12:26:32 -07001018 return JNI_FALSE;
1019 }
Dianne Hackborn306af672014-06-24 15:41:03 -07001020 env->ReleaseStringUTFChars(file, file8);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001021
Evan Millarc64edde2009-04-18 12:26:32 -07001022 char buffer[256];
1023 const int len = read(fd, buffer, sizeof(buffer)-1);
1024 close(fd);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001025
Evan Millarc64edde2009-04-18 12:26:32 -07001026 if (len < 0) {
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001027 if (kDebugProc) {
1028 ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
1029 }
Evan Millarc64edde2009-04-18 12:26:32 -07001030 return JNI_FALSE;
1031 }
1032 buffer[len] = 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -07001033
1034 return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
Evan Millarc64edde2009-04-18 12:26:32 -07001035 format, outStrings, outLongs, outFloats);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001036
Evan Millarc64edde2009-04-18 12:26:32 -07001037}
1038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
1040 jobject binderObject)
1041{
1042 if (binderObject == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001043 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 return;
1045 }
1046
1047 sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
1048}
1049
1050void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
1051{
1052 if (pid > 0) {
Mark Salyzync6a41012014-04-24 13:05:18 -07001053 ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 kill(pid, sig);
1055 }
1056}
1057
Dianne Hackborn906497c2010-05-10 15:57:38 -07001058void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
1059{
1060 if (pid > 0) {
1061 kill(pid, sig);
1062 }
1063}
1064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
1066{
1067 struct timespec ts;
1068
1069 int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (res != 0) {
1072 return (jlong) 0;
Elliott Hughes69a017b2011-04-08 14:10:28 -07001073 }
1074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
1076 return (jlong) nanoseconds_to_milliseconds(when);
1077}
1078
1079static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
1080{
1081 char filename[64];
1082
Mark Salyzync6a41012014-04-24 13:05:18 -07001083 snprintf(filename, sizeof(filename), "/proc/%" PRId32 "/smaps", pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084
1085 FILE * file = fopen(filename, "r");
1086 if (!file) {
1087 return (jlong) -1;
1088 }
1089
1090 // Tally up all of the Pss from the various maps
1091 char line[256];
1092 jlong pss = 0;
1093 while (fgets(line, sizeof(line), file)) {
1094 jlong v;
Mark Salyzync6a41012014-04-24 13:05:18 -07001095 if (sscanf(line, "Pss: %" SCNd64 " kB", &v) == 1) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 pss += v;
1097 }
1098 }
1099
1100 fclose(file);
1101
1102 // Return the Pss value in bytes, not kilobytes
1103 return pss * 1024;
1104}
1105
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001106jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
1107 jobjectArray commandNames)
1108{
1109 if (commandNames == NULL) {
1110 jniThrowNullPointerException(env, NULL);
1111 return NULL;
1112 }
1113
1114 Vector<String8> commands;
1115
1116 jsize count = env->GetArrayLength(commandNames);
1117
1118 for (int i=0; i<count; i++) {
1119 jobject obj = env->GetObjectArrayElement(commandNames, i);
1120 if (obj != NULL) {
1121 const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
1122 if (str8 == NULL) {
1123 jniThrowNullPointerException(env, "Element in commandNames");
1124 return NULL;
1125 }
1126 commands.add(String8(str8));
1127 env->ReleaseStringUTFChars((jstring)obj, str8);
1128 } else {
1129 jniThrowNullPointerException(env, "Element in commandNames");
1130 return NULL;
1131 }
1132 }
1133
1134 Vector<jint> pids;
1135
1136 DIR *proc = opendir("/proc");
1137 if (proc == NULL) {
1138 fprintf(stderr, "/proc: %s\n", strerror(errno));
1139 return NULL;
1140 }
1141
1142 struct dirent *d;
1143 while ((d = readdir(proc))) {
1144 int pid = atoi(d->d_name);
1145 if (pid <= 0) continue;
1146
1147 char path[PATH_MAX];
1148 char data[PATH_MAX];
1149 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
1150
1151 int fd = open(path, O_RDONLY);
1152 if (fd < 0) {
1153 continue;
1154 }
1155 const int len = read(fd, data, sizeof(data)-1);
1156 close(fd);
1157
1158 if (len < 0) {
1159 continue;
1160 }
1161 data[len] = 0;
1162
1163 for (int i=0; i<len; i++) {
1164 if (data[i] == ' ') {
1165 data[i] = 0;
1166 break;
1167 }
1168 }
1169
1170 for (size_t i=0; i<commands.size(); i++) {
1171 if (commands[i] == data) {
1172 pids.add(pid);
1173 break;
1174 }
1175 }
1176 }
1177
1178 closedir(proc);
1179
1180 jintArray pidArray = env->NewIntArray(pids.size());
1181 if (pidArray == NULL) {
1182 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1183 return NULL;
1184 }
1185
1186 if (pids.size() > 0) {
1187 env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
1188 }
1189
1190 return pidArray;
1191}
1192
Colin Cross0769e552014-06-03 13:25:35 -07001193jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
1194{
1195 return killProcessGroup(uid, pid, SIGKILL);
1196}
1197
1198void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
1199{
1200 return removeAllProcessGroups();
1201}
1202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203static const JNINativeMethod methods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 {"getUidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
1205 {"getGidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
1206 {"setThreadPriority", "(II)V", (void*)android_os_Process_setThreadPriority},
Glenn Kasten6793ac92011-07-13 12:44:12 -07001207 {"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler},
Christopher Tate160edb32010-06-30 17:46:30 -07001208 {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 {"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority},
1210 {"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority},
Srinath Sridharan1b15d132016-07-19 15:16:11 -07001211 {"getThreadScheduler", "(I)I", (void*)android_os_Process_getThreadScheduler},
San Mehate9d376b2009-04-21 14:06:36 -07001212 {"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup},
Jeff Sharkey9e57c412013-01-17 14:12:41 -08001213 {"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup},
1214 {"getProcessGroup", "(I)I", (void*)android_os_Process_getProcessGroup},
Martijn Coenencd4bdf32016-03-03 17:30:52 +01001215 {"getExclusiveCores", "()[I", (void*)android_os_Process_getExclusiveCores},
Rom Lemarchand5534ba92013-07-12 16:15:36 -07001216 {"setSwappiness", "(IZ)Z", (void*)android_os_Process_setSwappiness},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 {"setArgV0", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
1218 {"setUid", "(I)I", (void*)android_os_Process_setUid},
1219 {"setGid", "(I)I", (void*)android_os_Process_setGid},
1220 {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
Dianne Hackborn906497c2010-05-10 15:57:38 -07001221 {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
Marco Nelissen0bca96b2009-07-17 12:59:25 -07001222 {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
Dianne Hackborn59325eb2012-05-09 18:45:20 -07001223 {"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
1225 {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
1226 {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
Evan Millarc64edde2009-04-18 12:26:32 -07001227 {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
1229 {"getPss", "(I)J", (void*)android_os_Process_getPss},
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001230 {"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
Colin Cross0769e552014-06-03 13:25:35 -07001232 {"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
1233 {"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234};
1235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236int register_android_os_Process(JNIEnv* env)
1237{
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001238 return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239}