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