android_util_Process.cpp revision 6793ac943afeb16642f477c43ddfd27e498db37b
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#include <unistd.h> 42 43#define POLICY_DEBUG 0 44#define GUARD_THREAD_PRIORITY 0 45 46using namespace android; 47 48#if GUARD_THREAD_PRIORITY 49Mutex gKeyCreateMutex; 50static pthread_key_t gBgKey = -1; 51#endif 52 53static void signalExceptionForPriorityError(JNIEnv* env, int err) 54{ 55 switch (err) { 56 case EINVAL: 57 jniThrowException(env, "java/lang/IllegalArgumentException", NULL); 58 break; 59 case ESRCH: 60 jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist"); 61 break; 62 case EPERM: 63 jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread"); 64 break; 65 case EACCES: 66 jniThrowException(env, "java/lang/SecurityException", "No permission to set to given priority"); 67 break; 68 default: 69 jniThrowException(env, "java/lang/RuntimeException", "Unknown error"); 70 break; 71 } 72} 73 74static void signalExceptionForGroupError(JNIEnv* env, int err) 75{ 76 switch (err) { 77 case EINVAL: 78 jniThrowException(env, "java/lang/IllegalArgumentException", NULL); 79 break; 80 case ESRCH: 81 jniThrowException(env, "java/lang/IllegalArgumentException", "Given thread does not exist"); 82 break; 83 case EPERM: 84 jniThrowException(env, "java/lang/SecurityException", "No permission to modify given thread"); 85 break; 86 case EACCES: 87 jniThrowException(env, "java/lang/SecurityException", "No permission to set to given group"); 88 break; 89 default: 90 jniThrowException(env, "java/lang/RuntimeException", "Unknown error"); 91 break; 92 } 93} 94 95jint android_os_Process_myPid(JNIEnv* env, jobject clazz) 96{ 97 return getpid(); 98} 99 100jint android_os_Process_myUid(JNIEnv* env, jobject clazz) 101{ 102 return getuid(); 103} 104 105jint android_os_Process_myTid(JNIEnv* env, jobject clazz) 106{ 107 return androidGetTid(); 108} 109 110jint android_os_Process_getUidForName(JNIEnv* env, jobject clazz, jstring name) 111{ 112 if (name == NULL) { 113 jniThrowNullPointerException(env, NULL); 114 return -1; 115 } 116 117 const jchar* str16 = env->GetStringCritical(name, 0); 118 String8 name8; 119 if (str16) { 120 name8 = String8(str16, env->GetStringLength(name)); 121 env->ReleaseStringCritical(name, str16); 122 } 123 124 const size_t N = name8.size(); 125 if (N > 0) { 126 const char* str = name8.string(); 127 for (size_t i=0; i<N; i++) { 128 if (str[i] < '0' || str[i] > '9') { 129 struct passwd* pwd = getpwnam(str); 130 if (pwd == NULL) { 131 return -1; 132 } 133 return pwd->pw_uid; 134 } 135 } 136 return atoi(str); 137 } 138 return -1; 139} 140 141jint android_os_Process_getGidForName(JNIEnv* env, jobject clazz, jstring name) 142{ 143 if (name == NULL) { 144 jniThrowNullPointerException(env, NULL); 145 return -1; 146 } 147 148 const jchar* str16 = env->GetStringCritical(name, 0); 149 String8 name8; 150 if (str16) { 151 name8 = String8(str16, env->GetStringLength(name)); 152 env->ReleaseStringCritical(name, str16); 153 } 154 155 const size_t N = name8.size(); 156 if (N > 0) { 157 const char* str = name8.string(); 158 for (size_t i=0; i<N; i++) { 159 if (str[i] < '0' || str[i] > '9') { 160 struct group* grp = getgrnam(str); 161 if (grp == NULL) { 162 return -1; 163 } 164 return grp->gr_gid; 165 } 166 } 167 return atoi(str); 168 } 169 return -1; 170} 171 172void android_os_Process_setThreadGroup(JNIEnv* env, jobject clazz, int pid, jint grp) 173{ 174 int res = androidSetThreadSchedulingGroup(pid, grp); 175 if (res != NO_ERROR) { 176 signalExceptionForGroupError(env, res == BAD_VALUE ? EINVAL : errno); 177 return; 178 } 179} 180 181void android_os_Process_setProcessGroup(JNIEnv* env, jobject clazz, int pid, jint grp) 182{ 183 DIR *d; 184 FILE *fp; 185 char proc_path[255]; 186 struct dirent *de; 187 188 if (grp > ANDROID_TGROUP_MAX || grp < 0) { 189 signalExceptionForGroupError(env, EINVAL); 190 return; 191 } 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 (grp == ANDROID_TGROUP_BG_NONINTERACT) { 208 LOGD("setProcessGroup: vvv pid %d (%s)", pid, cmdline); 209 } else { 210 LOGD("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 LOGE("Error getting pid for '%s'\n", de->d_name); 231 continue; 232 } 233 234 t_pri = getpriority(PRIO_PROCESS, t_pid); 235 236 if (grp == ANDROID_TGROUP_DEFAULT && 237 t_pri >= ANDROID_PRIORITY_BACKGROUND) { 238 // This task wants to stay at background 239 continue; 240 } 241 242 if (androidSetThreadSchedulingGroup(t_pid, grp) != NO_ERROR) { 243 signalExceptionForGroupError(env, errno); 244 break; 245 } 246 } 247 closedir(d); 248} 249 250static void android_os_Process_setCanSelfBackground(JNIEnv* env, jobject clazz, jboolean bgOk) { 251 // Establishes the calling thread as illegal to put into the background. 252 // Typically used only for the system process's main looper. 253#if GUARD_THREAD_PRIORITY 254 LOGV("Process.setCanSelfBackground(%d) : tid=%d", bgOk, androidGetTid()); 255 { 256 Mutex::Autolock _l(gKeyCreateMutex); 257 if (gBgKey == -1) { 258 pthread_key_create(&gBgKey, NULL); 259 } 260 } 261 262 // inverted: not-okay, we set a sentinel value 263 pthread_setspecific(gBgKey, (void*)(bgOk ? 0 : 0xbaad)); 264#endif 265} 266 267void android_os_Process_setThreadScheduler(JNIEnv* env, jclass clazz, 268 jint tid, jint policy, jint pri) 269{ 270 struct sched_param param; 271 param.sched_priority = pri; 272 int rc = sched_setscheduler(tid, policy, ¶m); 273 if (rc) { 274 signalExceptionForPriorityError(env, errno); 275 } 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, errno); 300 } else { 301 signalExceptionForGroupError(env, 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, 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 {"setThreadScheduler", "(III)V", (void*)android_os_Process_setThreadScheduler}, 882 {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground}, 883 {"setThreadPriority", "(I)V", (void*)android_os_Process_setCallingThreadPriority}, 884 {"getThreadPriority", "(I)I", (void*)android_os_Process_getThreadPriority}, 885 {"setThreadGroup", "(II)V", (void*)android_os_Process_setThreadGroup}, 886 {"setProcessGroup", "(II)V", (void*)android_os_Process_setProcessGroup}, 887 {"setOomAdj", "(II)Z", (void*)android_os_Process_setOomAdj}, 888 {"setArgV0", "(Ljava/lang/String;)V", (void*)android_os_Process_setArgV0}, 889 {"setUid", "(I)I", (void*)android_os_Process_setUid}, 890 {"setGid", "(I)I", (void*)android_os_Process_setGid}, 891 {"sendSignal", "(II)V", (void*)android_os_Process_sendSignal}, 892 {"sendSignalQuiet", "(II)V", (void*)android_os_Process_sendSignalQuiet}, 893 {"supportsProcesses", "()Z", (void*)android_os_Process_supportsProcesses}, 894 {"getFreeMemory", "()J", (void*)android_os_Process_getFreeMemory}, 895 {"readProcLines", "(Ljava/lang/String;[Ljava/lang/String;[J)V", (void*)android_os_Process_readProcLines}, 896 {"getPids", "(Ljava/lang/String;[I)[I", (void*)android_os_Process_getPids}, 897 {"readProcFile", "(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_readProcFile}, 898 {"parseProcLine", "([BII[I[Ljava/lang/String;[J[F)Z", (void*)android_os_Process_parseProcLine}, 899 {"getElapsedCpuTime", "()J", (void*)android_os_Process_getElapsedCpuTime}, 900 {"getPss", "(I)J", (void*)android_os_Process_getPss}, 901 //{"setApplicationObject", "(Landroid/os/IBinder;)V", (void*)android_os_Process_setApplicationObject}, 902}; 903 904const char* const kProcessPathName = "android/os/Process"; 905 906int register_android_os_Process(JNIEnv* env) 907{ 908 return AndroidRuntime::registerNativeMethods( 909 env, kProcessPathName, 910 methods, NELEM(methods)); 911} 912