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