1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
|
/* //device/libs/android_runtime/android_util_Process.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#define LOG_TAG "Process"
// To make sure cpu_set_t is included from sched.h
#define _GNU_SOURCE 1
#include <utils/Log.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <cutils/process_name.h>
#include <cutils/sched_policy.h>
#include <utils/String8.h>
#include <utils/Vector.h>
#include <processgroup/processgroup.h>
#include "core_jni_helpers.h"
#include "android_util_Binder.h"
#include "JNIHelp.h"
#include <dirent.h>
#include <fcntl.h>
#include <grp.h>
#include <inttypes.h>
#include <pwd.h>
#include <signal.h>
#include <sys/errno.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define GUARD_THREAD_PRIORITY 0
using namespace android;
static const bool kDebugPolicy = false;
static const bool kDebugProc = false;
#if GUARD_THREAD_PRIORITY
Mutex gKeyCreateMutex;
static pthread_key_t gBgKey = -1;
#endif
// For both of these, err should be in the errno range (positive), not a status_t (negative)
static void signalExceptionForPriorityError(JNIEnv* env, int err)
{
switch (err) {
case EINVAL:
jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
break;
case ESRCH:
jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist");
break;
case EPERM:
jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread");
break;
case EACCES:
jniThrowException(env, "java/lang/SecurityException", "No permission to set to given priority");
break;
default:
jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
break;
}
}
static void signalExceptionForGroupError(JNIEnv* env, int err)
{
switch (err) {
case EINVAL:
jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
break;
case ESRCH:
jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist");
break;
case EPERM:
jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread");
break;
case EACCES:
jniThrowException(env, "java/lang/SecurityException", "No permission to set to given group");
break;
default:
jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
break;
}
}
jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name)
{
if (name == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
const jchar* str16 = env->GetStringCritical(name, 0);
String8 name8;
if (str16) {
name8 = String8(reinterpret_cast<const char16_t*>(str16),
env->GetStringLength(name));
env->ReleaseStringCritical(name, str16);
}
const size_t N = name8.size();
if (N > 0) {
const char* str = name8.string();
for (size_t i=0; i<N; i++) {
if (str[i] < '0' || str[i] > '9') {
struct passwd* pwd = getpwnam(str);
if (pwd == NULL) {
return -1;
}
return pwd->pw_uid;
}
}
return atoi(str);
}
return -1;
}
jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name)
{
if (name == NULL) {
jniThrowNullPointerException(env, NULL);
return -1;
}
const jchar* str16 = env->GetStringCritical(name, 0);
String8 name8;
if (str16) {
name8 = String8(reinterpret_cast<const char16_t*>(str16),
env->GetStringLength(name));
env->ReleaseStringCritical(name, str16);
}
const size_t N = name8.size();
if (N > 0) {
const char* str = name8.string();
for (size_t i=0; i<N; i++) {
if (str[i] < '0' || str[i] > '9') {
struct group* grp = getgrnam(str);
if (grp == NULL) {
return -1;
}
return grp->gr_gid;
}
}
return atoi(str);
}
return -1;
}
void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int tid, jint grp)
{
ALOGV("%s tid=%d grp=%" PRId32, __func__, tid, grp);
SchedPolicy sp = (SchedPolicy) grp;
int res = set_sched_policy(tid, sp);
if (res != NO_ERROR) {
signalExceptionForGroupError(env, -res);
}
}
void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp)
{
ALOGV("%s pid=%d grp=%" PRId32, __func__, pid, grp);
DIR *d;
char proc_path[255];
struct dirent *de;
if ((grp == SP_FOREGROUND) || (grp > SP_MAX)) {
signalExceptionForGroupError(env, EINVAL);
return;
}
bool isDefault = false;
if (grp < 0) {
grp = SP_FOREGROUND;
isDefault = true;
}
SchedPolicy sp = (SchedPolicy) grp;
if (kDebugPolicy) {
char cmdline[32];
int fd;
strcpy(cmdline, "unknown");
sprintf(proc_path, "/proc/%d/cmdline", pid);
fd = open(proc_path, O_RDONLY);
if (fd >= 0) {
int rc = read(fd, cmdline, sizeof(cmdline)-1);
cmdline[rc] = 0;
close(fd);
}
if (sp == SP_BACKGROUND) {
ALOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline);
} else {
ALOGD("setProcessGroup: ^^^ pid %d (%s)", pid, cmdline);
}
}
sprintf(proc_path, "/proc/%d/task", pid);
if (!(d = opendir(proc_path))) {
// If the process exited on us, don't generate an exception
if (errno != ENOENT)
signalExceptionForGroupError(env, errno);
return;
}
while ((de = readdir(d))) {
int t_pid;
int t_pri;
if (de->d_name[0] == '.')
continue;
t_pid = atoi(de->d_name);
if (!t_pid) {
ALOGE("Error getting pid for '%s'\n", de->d_name);
continue;
}
t_pri = getpriority(PRIO_PROCESS, t_pid);
if (t_pri <= ANDROID_PRIORITY_AUDIO) {
int scheduler = sched_getscheduler(t_pid);
if ((scheduler == SCHED_FIFO) || (scheduler == SCHED_RR)) {
// This task wants to stay in its current audio group so it can keep its budget
// don't update its cpuset or cgroup
continue;
}
}
if (isDefault) {
if (t_pri >= ANDROID_PRIORITY_BACKGROUND) {
// This task wants to stay at background
// update its cpuset so it doesn't only run on bg core(s)
#ifdef ENABLE_CPUSETS
int err = set_cpuset_policy(t_pid, sp);
if (err != NO_ERROR) {
signalExceptionForGroupError(env, -err);
break;
}
#endif
continue;
}
}
int err;
#ifdef ENABLE_CPUSETS
// set both cpuset and cgroup for general threads
err = set_cpuset_policy(t_pid, sp);
if (err != NO_ERROR) {
signalExceptionForGroupError(env, -err);
break;
}
#endif
err = set_sched_policy(t_pid, sp);
if (err != NO_ERROR) {
signalExceptionForGroupError(env, -err);
break;
}
}
closedir(d);
}
jint android_os_Process_getProcessGroup(JNIEnv* env, jobject clazz, jint pid)
{
SchedPolicy sp;
if (get_sched_policy(pid, &sp) != 0) {
signalExceptionForGroupError(env, errno);
}
return (int) sp;
}
#ifdef ENABLE_CPUSETS
/** Sample CPUset list format:
* 0-3,4,6-8
*/
static void parse_cpuset_cpus(char *cpus, cpu_set_t *cpu_set) {
unsigned int start, end, matched, i;
char *cpu_range = strtok(cpus, ",");
while (cpu_range != NULL) {
start = end = 0;
matched = sscanf(cpu_range, "%u-%u", &start, &end);
cpu_range = strtok(NULL, ",");
if (start >= CPU_SETSIZE) {
ALOGE("parse_cpuset_cpus: ignoring CPU number larger than %d.", CPU_SETSIZE);
continue;
} else if (end >= CPU_SETSIZE) {
ALOGE("parse_cpuset_cpus: ignoring CPU numbers larger than %d.", CPU_SETSIZE);
end = CPU_SETSIZE - 1;
}
if (matched == 1) {
CPU_SET(start, cpu_set);
} else if (matched == 2) {
for (i = start; i <= end; i++) {
CPU_SET(i, cpu_set);
}
} else {
ALOGE("Failed to match cpus");
}
}
return;
}
/**
* Stores the CPUs assigned to the cpuset corresponding to the
* SchedPolicy in the passed in cpu_set.
*/
static void get_cpuset_cores_for_policy(SchedPolicy policy, cpu_set_t *cpu_set)
{
FILE *file;
const char *filename;
CPU_ZERO(cpu_set);
switch (policy) {
case SP_BACKGROUND:
filename = "/dev/cpuset/background/cpus";
break;
case SP_FOREGROUND:
case SP_AUDIO_APP:
case SP_AUDIO_SYS:
filename = "/dev/cpuset/foreground/cpus";
break;
case SP_TOP_APP:
filename = "/dev/cpuset/top-app/cpus";
break;
default:
filename = NULL;
}
if (!filename) return;
file = fopen(filename, "re");
if (file != NULL) {
// Parse cpus string
char *line = NULL;
size_t len = 0;
ssize_t num_read = getline(&line, &len, file);
fclose (file);
if (num_read > 0) {
parse_cpuset_cpus(line, cpu_set);
} else {
ALOGE("Failed to read %s", filename);
}
free(line);
}
return;
}
#endif
/**
* Determine CPU cores exclusively assigned to the
* cpuset corresponding to the SchedPolicy and store
* them in the passed in cpu_set_t
*/
void get_exclusive_cpuset_cores(SchedPolicy policy, cpu_set_t *cpu_set) {
#ifdef ENABLE_CPUSETS
int i;
cpu_set_t tmp_set;
get_cpuset_cores_for_policy(policy, cpu_set);
for (i = 0; i < SP_CNT; i++) {
if ((SchedPolicy) i == policy) continue;
get_cpuset_cores_for_policy((SchedPolicy)i, &tmp_set);
// First get cores exclusive to one set or the other
CPU_XOR(&tmp_set, cpu_set, &tmp_set);
// Then get the ones only in cpu_set
CPU_AND(cpu_set, cpu_set, &tmp_set);
}
#else
(void) policy;
CPU_ZERO(cpu_set);
#endif
return;
}
jintArray android_os_Process_getExclusiveCores(JNIEnv* env, jobject clazz) {
SchedPolicy sp;
cpu_set_t cpu_set;
jintArray cpus;
int pid = getpid();
if (get_sched_policy(pid, &sp) != 0) {
signalExceptionForGroupError(env, errno);
return NULL;
}
get_exclusive_cpuset_cores(sp, &cpu_set);
int num_cpus = CPU_COUNT(&cpu_set);
cpus = env->NewIntArray(num_cpus);
if (cpus == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return NULL;
}
jint* cpu_elements = env->GetIntArrayElements(cpus, 0);
int count = 0;
for (int i = 0; i < CPU_SETSIZE && count < num_cpus; i++) {
if (CPU_ISSET(i, &cpu_set)) {
cpu_elements[count++] = i;
}
}
env->ReleaseIntArrayElements(cpus, cpu_elements, 0);
return cpus;
}
static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) {
// Establishes the calling thread as illegal to put into the background.
// Typically used only for the system process's main looper.
#if GUARD_THREAD_PRIORITY
ALOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, gettid());
{
Mutex::Autolock _l(gKeyCreateMutex);
if (gBgKey == -1) {
pthread_key_create(&gBgKey, NULL);
}
}
// inverted: not-okay, we set a sentinel value
pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad));
#endif
}
void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz,
jint tid, jint policy, jint pri)
{
// linux has sched_setscheduler(), others don't.
#if defined(__linux__)
struct sched_param param;
param.sched_priority = pri;
int rc = sched_setscheduler(tid, policy, ¶m);
if (rc) {
signalExceptionForPriorityError(env, errno);
}
#else
signalExceptionForPriorityError(env, ENOSYS);
#endif
}
void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
jint pid, jint pri)
{
#if GUARD_THREAD_PRIORITY
// if we're putting the current thread into the background, check the TLS
// to make sure this thread isn't guarded. If it is, raise an exception.
if (pri >= ANDROID_PRIORITY_BACKGROUND) {
if (pid == gettid()) {
void* bgOk = pthread_getspecific(gBgKey);
if (bgOk == ((void*)0xbaad)) {
ALOGE("Thread marked fg-only put self in background!");
jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
return;
}
}
}
#endif
int rc = androidSetThreadPriority(pid, pri);
if (rc != 0) {
if (rc == INVALID_OPERATION) {
signalExceptionForPriorityError(env, errno);
} else {
signalExceptionForGroupError(env, errno);
}
}
//ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
// pid, pri, getpriority(PRIO_PROCESS, pid));
}
void android_os_Process_setCallingThreadPriority(JNIEnv* env, jobject clazz,
jint pri)
{
android_os_Process_setThreadPriority(env, clazz, gettid(), pri);
}
jint android_os_Process_getThreadPriority(JNIEnv* env, jobject clazz,
jint pid)
{
errno = 0;
jint pri = getpriority(PRIO_PROCESS, pid);
if (errno != 0) {
signalExceptionForPriorityError(env, errno);
}
//ALOGI("Returning priority of %" PRId32 ": %" PRId32 "\n", pid, pri);
return pri;
}
jboolean android_os_Process_setSwappiness(JNIEnv *env, jobject clazz,
jint pid, jboolean is_increased)
{
char text[64];
if (is_increased) {
strcpy(text, "/sys/fs/cgroup/memory/sw/tasks");
} else {
strcpy(text, "/sys/fs/cgroup/memory/tasks");
}
struct stat st;
if (stat(text, &st) || !S_ISREG(st.st_mode)) {
return false;
}
int fd = open(text, O_WRONLY);
if (fd >= 0) {
sprintf(text, "%" PRId32, pid);
write(fd, text, strlen(text));
close(fd);
}
return true;
}
void android_os_Process_setArgV0(JNIEnv* env, jobject clazz, jstring name)
{
if (name == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
const jchar* str = env->GetStringCritical(name, 0);
String8 name8;
if (str) {
name8 = String8(reinterpret_cast<const char16_t*>(str),
env->GetStringLength(name));
env->ReleaseStringCritical(name, str);
}
if (name8.size() > 0) {
const char* procName = name8.string();
set_process_name(procName);
AndroidRuntime::getRuntime()->setArgv0(procName);
}
}
jint android_os_Process_setUid(JNIEnv* env, jobject clazz, jint uid)
{
return setuid(uid) == 0 ? 0 : errno;
}
jint android_os_Process_setGid(JNIEnv* env, jobject clazz, jint uid)
{
return setgid(uid) == 0 ? 0 : errno;
}
static int pid_compare(const void* v1, const void* v2)
{
//ALOGI("Compare %" PRId32 " vs %" PRId32 "\n", *((const jint*)v1), *((const jint*)v2));
return *((const jint*)v1) - *((const jint*)v2);
}
static jlong getFreeMemoryImpl(const char* const sums[], const size_t sumsLen[], size_t num)
{
int fd = open("/proc/meminfo", O_RDONLY);
if (fd < 0) {
ALOGW("Unable to open /proc/meminfo");
return -1;
}
char buffer[256];
const int len = read(fd, buffer, sizeof(buffer)-1);
close(fd);
if (len < 0) {
ALOGW("Unable to read /proc/meminfo");
return -1;
}
buffer[len] = 0;
size_t numFound = 0;
jlong mem = 0;
char* p = buffer;
while (*p && numFound < num) {
int i = 0;
while (sums[i]) {
if (strncmp(p, sums[i], sumsLen[i]) == 0) {
p += sumsLen[i];
while (*p == ' ') p++;
char* num = p;
while (*p >= '0' && *p <= '9') p++;
if (*p != 0) {
*p = 0;
p++;
if (*p == 0) p--;
}
mem += atoll(num) * 1024;
numFound++;
break;
}
i++;
}
p++;
}
return numFound > 0 ? mem : -1;
}
static jlong android_os_Process_getFreeMemory(JNIEnv* env, jobject clazz)
{
static const char* const sums[] = { "MemFree:", "Cached:", NULL };
static const size_t sumsLen[] = { strlen("MemFree:"), strlen("Cached:"), 0 };
return getFreeMemoryImpl(sums, sumsLen, 2);
}
static jlong android_os_Process_getTotalMemory(JNIEnv* env, jobject clazz)
{
static const char* const sums[] = { "MemTotal:", NULL };
static const size_t sumsLen[] = { strlen("MemTotal:"), 0 };
return getFreeMemoryImpl(sums, sumsLen, 1);
}
void android_os_Process_readProcLines(JNIEnv* env, jobject clazz, jstring fileStr,
jobjectArray reqFields, jlongArray outFields)
{
//ALOGI("getMemInfo: %p %p", reqFields, outFields);
if (fileStr == NULL || reqFields == NULL || outFields == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
const char* file8 = env->GetStringUTFChars(fileStr, NULL);
if (file8 == NULL) {
return;
}
String8 file(file8);
env->ReleaseStringUTFChars(fileStr, file8);
jsize count = env->GetArrayLength(reqFields);
if (count > env->GetArrayLength(outFields)) {
jniThrowException(env, "java/lang/IllegalArgumentException", "Array lengths differ");
return;
}
Vector<String8> fields;
int i;
for (i=0; i<count; i++) {
jobject obj = env->GetObjectArrayElement(reqFields, i);
if (obj != NULL) {
const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
//ALOGI("String at %d: %p = %s", i, obj, str8);
if (str8 == NULL) {
jniThrowNullPointerException(env, "Element in reqFields");
return;
}
fields.add(String8(str8));
env->ReleaseStringUTFChars((jstring)obj, str8);
} else {
jniThrowNullPointerException(env, "Element in reqFields");
return;
}
}
jlong* sizesArray = env->GetLongArrayElements(outFields, 0);
if (sizesArray == NULL) {
return;
}
//ALOGI("Clearing %" PRId32 " sizes", count);
for (i=0; i<count; i++) {
sizesArray[i] = 0;
}
int fd = open(file.string(), O_RDONLY);
if (fd >= 0) {
const size_t BUFFER_SIZE = 2048;
char* buffer = (char*)malloc(BUFFER_SIZE);
int len = read(fd, buffer, BUFFER_SIZE-1);
close(fd);
if (len < 0) {
ALOGW("Unable to read %s", file.string());
len = 0;
}
buffer[len] = 0;
int foundCount = 0;
char* p = buffer;
while (*p && foundCount < count) {
bool skipToEol = true;
//ALOGI("Parsing at: %s", p);
for (i=0; i<count; i++) {
const String8& field = fields[i];
if (strncmp(p, field.string(), field.length()) == 0) {
p += field.length();
while (*p == ' ' || *p == '\t') p++;
char* num = p;
while (*p >= '0' && *p <= '9') p++;
skipToEol = *p != '\n';
if (*p != 0) {
*p = 0;
p++;
}
char* end;
sizesArray[i] = strtoll(num, &end, 10);
//ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
foundCount++;
break;
}
}
if (skipToEol) {
while (*p && *p != '\n') {
p++;
}
if (*p == '\n') {
p++;
}
}
}
free(buffer);
} else {
ALOGW("Unable to open %s", file.string());
}
//ALOGI("Done!");
env->ReleaseLongArrayElements(outFields, sizesArray, 0);
}
jintArray android_os_Process_getPids(JNIEnv* env, jobject clazz,
jstring file, jintArray lastArray)
{
if (file == NULL) {
jniThrowNullPointerException(env, NULL);
return NULL;
}
const char* file8 = env->GetStringUTFChars(file, NULL);
if (file8 == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return NULL;
}
DIR* dirp = opendir(file8);
env->ReleaseStringUTFChars(file, file8);
if(dirp == NULL) {
return NULL;
}
jsize curCount = 0;
jint* curData = NULL;
if (lastArray != NULL) {
curCount = env->GetArrayLength(lastArray);
curData = env->GetIntArrayElements(lastArray, 0);
}
jint curPos = 0;
struct dirent* entry;
while ((entry=readdir(dirp)) != NULL) {
const char* p = entry->d_name;
while (*p) {
if (*p < '0' || *p > '9') break;
p++;
}
if (*p != 0) continue;
char* end;
int pid = strtol(entry->d_name, &end, 10);
//ALOGI("File %s pid=%d\n", entry->d_name, pid);
if (curPos >= curCount) {
jsize newCount = (curCount == 0) ? 10 : (curCount*2);
jintArray newArray = env->NewIntArray(newCount);
if (newArray == NULL) {
closedir(dirp);
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return NULL;
}
jint* newData = env->GetIntArrayElements(newArray, 0);
if (curData != NULL) {
memcpy(newData, curData, sizeof(jint)*curCount);
env->ReleaseIntArrayElements(lastArray, curData, 0);
}
lastArray = newArray;
curCount = newCount;
curData = newData;
}
curData[curPos] = pid;
curPos++;
}
closedir(dirp);
if (curData != NULL && curPos > 0) {
qsort(curData, curPos, sizeof(jint), pid_compare);
}
while (curPos < curCount) {
curData[curPos] = -1;
curPos++;
}
if (curData != NULL) {
env->ReleaseIntArrayElements(lastArray, curData, 0);
}
return lastArray;
}
enum {
PROC_TERM_MASK = 0xff,
PROC_ZERO_TERM = 0,
PROC_SPACE_TERM = ' ',
PROC_COMBINE = 0x100,
PROC_PARENS = 0x200,
PROC_QUOTES = 0x400,
PROC_CHAR = 0x800,
PROC_OUT_STRING = 0x1000,
PROC_OUT_LONG = 0x2000,
PROC_OUT_FLOAT = 0x4000,
};
jboolean android_os_Process_parseProcLineArray(JNIEnv* env, jobject clazz,
char* buffer, jint startIndex, jint endIndex, jintArray format,
jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
{
const jsize NF = env->GetArrayLength(format);
const jsize NS = outStrings ? env->GetArrayLength(outStrings) : 0;
const jsize NL = outLongs ? env->GetArrayLength(outLongs) : 0;
const jsize NR = outFloats ? env->GetArrayLength(outFloats) : 0;
jint* formatData = env->GetIntArrayElements(format, 0);
jlong* longsData = outLongs ?
env->GetLongArrayElements(outLongs, 0) : NULL;
jfloat* floatsData = outFloats ?
env->GetFloatArrayElements(outFloats, 0) : NULL;
if (formatData == NULL || (NL > 0 && longsData == NULL)
|| (NR > 0 && floatsData == NULL)) {
if (formatData != NULL) {
env->ReleaseIntArrayElements(format, formatData, 0);
}
if (longsData != NULL) {
env->ReleaseLongArrayElements(outLongs, longsData, 0);
}
if (floatsData != NULL) {
env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
}
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return JNI_FALSE;
}
jsize i = startIndex;
jsize di = 0;
jboolean res = JNI_TRUE;
for (jsize fi=0; fi<NF; fi++) {
jint mode = formatData[fi];
if ((mode&PROC_PARENS) != 0) {
i++;
} else if ((mode&PROC_QUOTES) != 0) {
if (buffer[i] == '"') {
i++;
} else {
mode &= ~PROC_QUOTES;
}
}
const char term = (char)(mode&PROC_TERM_MASK);
const jsize start = i;
if (i >= endIndex) {
if (kDebugProc) {
ALOGW("Ran off end of data @%d", i);
}
res = JNI_FALSE;
break;
}
jsize end = -1;
if ((mode&PROC_PARENS) != 0) {
while (i < endIndex && buffer[i] != ')') {
i++;
}
end = i;
i++;
} else if ((mode&PROC_QUOTES) != 0) {
while (buffer[i] != '"' && i < endIndex) {
i++;
}
end = i;
i++;
}
while (i < endIndex && buffer[i] != term) {
i++;
}
if (end < 0) {
end = i;
}
if (i < endIndex) {
i++;
if ((mode&PROC_COMBINE) != 0) {
while (i < endIndex && buffer[i] == term) {
i++;
}
}
}
//ALOGI("Field %" PRId32 ": %" PRId32 "-%" PRId32 " dest=%" PRId32 " mode=0x%" PRIx32 "\n", i, start, end, di, mode);
if ((mode&(PROC_OUT_FLOAT|PROC_OUT_LONG|PROC_OUT_STRING)) != 0) {
char c = buffer[end];
buffer[end] = 0;
if ((mode&PROC_OUT_FLOAT) != 0 && di < NR) {
char* end;
floatsData[di] = strtof(buffer+start, &end);
}
if ((mode&PROC_OUT_LONG) != 0 && di < NL) {
if ((mode&PROC_CHAR) != 0) {
// Caller wants single first character returned as one long.
longsData[di] = buffer[start];
} else {
char* end;
longsData[di] = strtoll(buffer+start, &end, 10);
}
}
if ((mode&PROC_OUT_STRING) != 0 && di < NS) {
jstring str = env->NewStringUTF(buffer+start);
env->SetObjectArrayElement(outStrings, di, str);
}
buffer[end] = c;
di++;
}
}
env->ReleaseIntArrayElements(format, formatData, 0);
if (longsData != NULL) {
env->ReleaseLongArrayElements(outLongs, longsData, 0);
}
if (floatsData != NULL) {
env->ReleaseFloatArrayElements(outFloats, floatsData, 0);
}
return res;
}
jboolean android_os_Process_parseProcLine(JNIEnv* env, jobject clazz,
jbyteArray buffer, jint startIndex, jint endIndex, jintArray format,
jobjectArray outStrings, jlongArray outLongs, jfloatArray outFloats)
{
jbyte* bufferArray = env->GetByteArrayElements(buffer, NULL);
jboolean result = android_os_Process_parseProcLineArray(env, clazz,
(char*) bufferArray, startIndex, endIndex, format, outStrings,
outLongs, outFloats);
env->ReleaseByteArrayElements(buffer, bufferArray, 0);
return result;
}
jboolean android_os_Process_readProcFile(JNIEnv* env, jobject clazz,
jstring file, jintArray format, jobjectArray outStrings,
jlongArray outLongs, jfloatArray outFloats)
{
if (file == NULL || format == NULL) {
jniThrowNullPointerException(env, NULL);
return JNI_FALSE;
}
const char* file8 = env->GetStringUTFChars(file, NULL);
if (file8 == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return JNI_FALSE;
}
int fd = open(file8, O_RDONLY);
if (fd < 0) {
if (kDebugProc) {
ALOGW("Unable to open process file: %s\n", file8);
}
env->ReleaseStringUTFChars(file, file8);
return JNI_FALSE;
}
env->ReleaseStringUTFChars(file, file8);
char buffer[256];
const int len = read(fd, buffer, sizeof(buffer)-1);
close(fd);
if (len < 0) {
if (kDebugProc) {
ALOGW("Unable to open process file: %s fd=%d\n", file8, fd);
}
return JNI_FALSE;
}
buffer[len] = 0;
return android_os_Process_parseProcLineArray(env, clazz, buffer, 0, len,
format, outStrings, outLongs, outFloats);
}
void android_os_Process_setApplicationObject(JNIEnv* env, jobject clazz,
jobject binderObject)
{
if (binderObject == NULL) {
jniThrowNullPointerException(env, NULL);
return;
}
sp<IBinder> binder = ibinderForJavaObject(env, binderObject);
}
void android_os_Process_sendSignal(JNIEnv* env, jobject clazz, jint pid, jint sig)
{
if (pid > 0) {
ALOGI("Sending signal. PID: %" PRId32 " SIG: %" PRId32, pid, sig);
kill(pid, sig);
}
}
void android_os_Process_sendSignalQuiet(JNIEnv* env, jobject clazz, jint pid, jint sig)
{
if (pid > 0) {
kill(pid, sig);
}
}
static jlong android_os_Process_getElapsedCpuTime(JNIEnv* env, jobject clazz)
{
struct timespec ts;
int res = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
if (res != 0) {
return (jlong) 0;
}
nsecs_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
return (jlong) nanoseconds_to_milliseconds(when);
}
static jlong android_os_Process_getPss(JNIEnv* env, jobject clazz, jint pid)
{
char filename[64];
snprintf(filename, sizeof(filename), "/proc/%" PRId32 "/smaps", pid);
FILE * file = fopen(filename, "r");
if (!file) {
return (jlong) -1;
}
// Tally up all of the Pss from the various maps
char line[256];
jlong pss = 0;
while (fgets(line, sizeof(line), file)) {
jlong v;
if (sscanf(line, "Pss: %" SCNd64 " kB", &v) == 1) {
pss += v;
}
}
fclose(file);
// Return the Pss value in bytes, not kilobytes
return pss * 1024;
}
jintArray android_os_Process_getPidsForCommands(JNIEnv* env, jobject clazz,
jobjectArray commandNames)
{
if (commandNames == NULL) {
jniThrowNullPointerException(env, NULL);
return NULL;
}
Vector<String8> commands;
jsize count = env->GetArrayLength(commandNames);
for (int i=0; i<count; i++) {
jobject obj = env->GetObjectArrayElement(commandNames, i);
if (obj != NULL) {
const char* str8 = env->GetStringUTFChars((jstring)obj, NULL);
if (str8 == NULL) {
jniThrowNullPointerException(env, "Element in commandNames");
return NULL;
}
commands.add(String8(str8));
env->ReleaseStringUTFChars((jstring)obj, str8);
} else {
jniThrowNullPointerException(env, "Element in commandNames");
return NULL;
}
}
Vector<jint> pids;
DIR *proc = opendir("/proc");
if (proc == NULL) {
fprintf(stderr, "/proc: %s\n", strerror(errno));
return NULL;
}
struct dirent *d;
while ((d = readdir(proc))) {
int pid = atoi(d->d_name);
if (pid <= 0) continue;
char path[PATH_MAX];
char data[PATH_MAX];
snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
int fd = open(path, O_RDONLY);
if (fd < 0) {
continue;
}
const int len = read(fd, data, sizeof(data)-1);
close(fd);
if (len < 0) {
continue;
}
data[len] = 0;
for (int i=0; i<len; i++) {
if (data[i] == ' ') {
data[i] = 0;
break;
}
}
for (size_t i=0; i<commands.size(); i++) {
if (commands[i] == data) {
pids.add(pid);
break;
}
}
}
closedir(proc);
jintArray pidArray = env->NewIntArray(pids.size());
if (pidArray == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return NULL;
}
if (pids.size() > 0) {
env->SetIntArrayRegion(pidArray, 0, pids.size(), pids.array());
}
return pidArray;
}
jint android_os_Process_killProcessGroup(JNIEnv* env, jobject clazz, jint uid, jint pid)
{
return killProcessGroup(uid, pid, SIGKILL);
}
void android_os_Process_removeAllProcessGroups(JNIEnv* env, jobject clazz)
{
return removeAllProcessGroups();
}
static const JNINativeMethod methods[] = {
{"getUidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getUidForName},
{"getGidForName", "(Ljava/lang/String;)I", (void*)android_os_Process_getGidForName},
{"setThreadPriority", "(II)V", (void*)android_os_Process_setThreadPriority},
{"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler},
{"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
{"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority},
{"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority},
{"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup},
{"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup},
{"getProcessGroup", "(I)I", (void*)android_os_Process_getProcessGroup},
{"getExclusiveCores", "()[I", (void*)android_os_Process_getExclusiveCores},
{"setSwappiness", "(IZ)Z", (void*)android_os_Process_setSwappiness},
{"setArgV0", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0},
{"setUid", "(I)I", (void*)android_os_Process_setUid},
{"setGid", "(I)I", (void*)android_os_Process_setGid},
{"sendSignal", "(II)V", (void*)android_os_Process_sendSignal},
{"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet},
{"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory},
{"getTotalMemory", "()J", (void*)android_os_Process_getTotalMemory},
{"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines},
{"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids},
{"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile},
{"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine},
{"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime},
{"getPss", "(I)J", (void*)android_os_Process_getPss},
{"getPidsForCommands", "([Ljava/lang/String;)[I", (void*)android_os_Process_getPidsForCommands},
//{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject},
{"killProcessGroup", "(II)I", (void*)android_os_Process_killProcessGroup},
{"removeAllProcessGroups", "()V", (void*)android_os_Process_removeAllProcessGroups},
};
int register_android_os_Process(JNIEnv* env)
{
return RegisterMethodsOrDie(env, "android/os/Process", methods, NELEM(methods));
}
|