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