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