utils.cpp revision baa85bd893665a48aee73d7ca7b73cd39b48f998
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include <dirent.h> 18#include <errno.h> 19#include <fcntl.h> 20#include <limits.h> 21#include <poll.h> 22#include <signal.h> 23#include <stdarg.h> 24#include <stdio.h> 25#include <stdlib.h> 26#include <string> 27#include <string.h> 28#include <sys/capability.h> 29#include <sys/inotify.h> 30#include <sys/stat.h> 31#include <sys/sysconf.h> 32#include <sys/time.h> 33#include <sys/wait.h> 34#include <sys/klog.h> 35#include <time.h> 36#include <unistd.h> 37#include <vector> 38#include <sys/prctl.h> 39 40#define LOG_TAG "dumpstate" 41#include <cutils/debugger.h> 42#include <cutils/log.h> 43#include <cutils/properties.h> 44#include <cutils/sockets.h> 45#include <private/android_filesystem_config.h> 46 47#include <selinux/android.h> 48 49#include "dumpstate.h" 50 51static const int64_t NANOS_PER_SEC = 1000000000; 52 53/* list of native processes to include in the native dumps */ 54static const char* native_processes_to_dump[] = { 55 "/system/bin/audioserver", 56 "/system/bin/cameraserver", 57 "/system/bin/drmserver", 58 "/system/bin/mediaserver", 59 "/system/bin/sdcard", 60 "/system/bin/surfaceflinger", 61 "/system/bin/vehicle_network_service", 62 NULL, 63}; 64 65DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {} 66 67DurationReporter::DurationReporter(const char *title, FILE *out) { 68 title_ = title; 69 if (title) { 70 started_ = DurationReporter::nanotime(); 71 } 72 out_ = out; 73} 74 75DurationReporter::~DurationReporter() { 76 if (title_) { 77 uint64_t elapsed = DurationReporter::nanotime() - started_; 78 // Use "Yoda grammar" to make it easier to grep|sort sections. 79 if (out_) { 80 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n", 81 (float) elapsed / NANOS_PER_SEC, title_); 82 } else { 83 MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC); 84 } 85 } 86} 87 88uint64_t DurationReporter::DurationReporter::nanotime() { 89 struct timespec ts; 90 clock_gettime(CLOCK_MONOTONIC, &ts); 91 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec; 92} 93 94void for_each_userid(void (*func)(int), const char *header) { 95 ON_DRY_RUN_RETURN(); 96 DIR *d; 97 struct dirent *de; 98 99 if (header) printf("\n------ %s ------\n", header); 100 func(0); 101 102 if (!(d = opendir("/data/system/users"))) { 103 printf("Failed to open /data/system/users (%s)\n", strerror(errno)); 104 return; 105 } 106 107 while ((de = readdir(d))) { 108 int userid; 109 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) { 110 continue; 111 } 112 func(userid); 113 } 114 115 closedir(d); 116} 117 118static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) { 119 DIR *d; 120 struct dirent *de; 121 122 if (!(d = opendir("/proc"))) { 123 printf("Failed to open /proc (%s)\n", strerror(errno)); 124 return; 125 } 126 127 if (header) printf("\n------ %s ------\n", header); 128 while ((de = readdir(d))) { 129 int pid; 130 int fd; 131 char cmdpath[255]; 132 char cmdline[255]; 133 134 if (!(pid = atoi(de->d_name))) { 135 continue; 136 } 137 138 memset(cmdline, 0, sizeof(cmdline)); 139 140 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid); 141 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) { 142 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2)); 143 close(fd); 144 if (cmdline[0]) { 145 helper(pid, cmdline, arg); 146 continue; 147 } 148 } 149 150 // if no cmdline, a kernel thread has comm 151 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid); 152 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) { 153 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4)); 154 close(fd); 155 if (cmdline[1]) { 156 cmdline[0] = '['; 157 size_t len = strcspn(cmdline, "\f\b\r\n"); 158 cmdline[len] = ']'; 159 cmdline[len+1] = '\0'; 160 } 161 } 162 if (!cmdline[0]) { 163 strcpy(cmdline, "N/A"); 164 } 165 helper(pid, cmdline, arg); 166 } 167 168 closedir(d); 169} 170 171static void for_each_pid_helper(int pid, const char *cmdline, void *arg) { 172 for_each_pid_func *func = (for_each_pid_func*) arg; 173 func(pid, cmdline); 174} 175 176void for_each_pid(for_each_pid_func func, const char *header) { 177 ON_DRY_RUN_RETURN(); 178 __for_each_pid(for_each_pid_helper, header, (void *)func); 179} 180 181static void for_each_tid_helper(int pid, const char *cmdline, void *arg) { 182 DIR *d; 183 struct dirent *de; 184 char taskpath[255]; 185 for_each_tid_func *func = (for_each_tid_func *) arg; 186 187 sprintf(taskpath, "/proc/%d/task", pid); 188 189 if (!(d = opendir(taskpath))) { 190 printf("Failed to open %s (%s)\n", taskpath, strerror(errno)); 191 return; 192 } 193 194 func(pid, pid, cmdline); 195 196 while ((de = readdir(d))) { 197 int tid; 198 int fd; 199 char commpath[255]; 200 char comm[255]; 201 202 if (!(tid = atoi(de->d_name))) { 203 continue; 204 } 205 206 if (tid == pid) 207 continue; 208 209 sprintf(commpath,"/proc/%d/comm", tid); 210 memset(comm, 0, sizeof(comm)); 211 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) { 212 strcpy(comm, "N/A"); 213 } else { 214 char *c; 215 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2)); 216 close(fd); 217 218 c = strrchr(comm, '\n'); 219 if (c) { 220 *c = '\0'; 221 } 222 } 223 func(pid, tid, comm); 224 } 225 226 closedir(d); 227} 228 229void for_each_tid(for_each_tid_func func, const char *header) { 230 ON_DRY_RUN_RETURN(); 231 __for_each_pid(for_each_tid_helper, header, (void *) func); 232} 233 234void show_wchan(int pid, int tid, const char *name) { 235 ON_DRY_RUN_RETURN(); 236 char path[255]; 237 char buffer[255]; 238 int fd, ret, save_errno; 239 char name_buffer[255]; 240 241 memset(buffer, 0, sizeof(buffer)); 242 243 sprintf(path, "/proc/%d/wchan", tid); 244 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) { 245 printf("Failed to open '%s' (%s)\n", path, strerror(errno)); 246 return; 247 } 248 249 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer))); 250 save_errno = errno; 251 close(fd); 252 253 if (ret < 0) { 254 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno)); 255 return; 256 } 257 258 snprintf(name_buffer, sizeof(name_buffer), "%*s%s", 259 pid == tid ? 0 : 3, "", name); 260 261 printf("%-7d %-32s %s\n", tid, name_buffer, buffer); 262 263 return; 264} 265 266// print time in centiseconds 267static void snprcent(char *buffer, size_t len, size_t spc, 268 unsigned long long time) { 269 static long hz; // cache discovered hz 270 271 if (hz <= 0) { 272 hz = sysconf(_SC_CLK_TCK); 273 if (hz <= 0) { 274 hz = 1000; 275 } 276 } 277 278 // convert to centiseconds 279 time = (time * 100 + (hz / 2)) / hz; 280 281 char str[16]; 282 283 snprintf(str, sizeof(str), " %llu.%02u", 284 time / 100, (unsigned)(time % 100)); 285 size_t offset = strlen(buffer); 286 snprintf(buffer + offset, (len > offset) ? len - offset : 0, 287 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str); 288} 289 290// print permille as a percent 291static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) { 292 char str[16]; 293 294 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10); 295 size_t offset = strlen(buffer); 296 snprintf(buffer + offset, (len > offset) ? len - offset : 0, 297 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str); 298} 299 300void show_showtime(int pid, const char *name) { 301 ON_DRY_RUN_RETURN(); 302 char path[255]; 303 char buffer[1023]; 304 int fd, ret, save_errno; 305 306 memset(buffer, 0, sizeof(buffer)); 307 308 sprintf(path, "/proc/%d/stat", pid); 309 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) { 310 printf("Failed to open '%s' (%s)\n", path, strerror(errno)); 311 return; 312 } 313 314 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer))); 315 save_errno = errno; 316 close(fd); 317 318 if (ret < 0) { 319 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno)); 320 return; 321 } 322 323 // field 14 is utime 324 // field 15 is stime 325 // field 42 is iotime 326 unsigned long long utime = 0, stime = 0, iotime = 0; 327 if (sscanf(buffer, 328 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d " 329 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d " 330 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d " 331 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ", 332 &utime, &stime, &iotime) != 3) { 333 return; 334 } 335 336 unsigned long long total = utime + stime; 337 if (!total) { 338 return; 339 } 340 341 unsigned permille = (iotime * 1000 + (total / 2)) / total; 342 if (permille > 1000) { 343 permille = 1000; 344 } 345 346 // try to beautify and stabilize columns at <80 characters 347 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name); 348 if ((name[0] != '[') || utime) { 349 snprcent(buffer, sizeof(buffer), 57, utime); 350 } 351 snprcent(buffer, sizeof(buffer), 65, stime); 352 if ((name[0] != '[') || iotime) { 353 snprcent(buffer, sizeof(buffer), 73, iotime); 354 } 355 if (iotime) { 356 snprdec(buffer, sizeof(buffer), 79, permille); 357 } 358 puts(buffer); // adds a trailing newline 359 360 return; 361} 362 363void do_dmesg() { 364 const char *title = "KERNEL LOG (dmesg)"; 365 DurationReporter duration_reporter(title); 366 printf("------ %s ------\n", title); 367 368 ON_DRY_RUN_RETURN(); 369 /* Get size of kernel buffer */ 370 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0); 371 if (size <= 0) { 372 printf("Unexpected klogctl return value: %d\n\n", size); 373 return; 374 } 375 char *buf = (char *) malloc(size + 1); 376 if (buf == NULL) { 377 printf("memory allocation failed\n\n"); 378 return; 379 } 380 int retval = klogctl(KLOG_READ_ALL, buf, size); 381 if (retval < 0) { 382 printf("klogctl failure\n\n"); 383 free(buf); 384 return; 385 } 386 buf[retval] = '\0'; 387 printf("%s\n\n", buf); 388 free(buf); 389 return; 390} 391 392void do_showmap(int pid, const char *name) { 393 char title[255]; 394 char arg[255]; 395 396 sprintf(title, "SHOW MAP %d (%s)", pid, name); 397 sprintf(arg, "%d", pid); 398 run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL); 399} 400 401static int _dump_file_from_fd(const char *title, const char *path, int fd) { 402 if (title) { 403 printf("------ %s (%s", title, path); 404 405 struct stat st; 406 // Only show the modification time of non-device files. 407 size_t path_len = strlen(path); 408 if ((path_len < 6 || memcmp(path, "/proc/", 6)) && 409 (path_len < 5 || memcmp(path, "/sys/", 5)) && 410 (path_len < 3 || memcmp(path, "/d/", 3)) && 411 !fstat(fd, &st)) { 412 char stamp[80]; 413 time_t mtime = st.st_mtime; 414 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime)); 415 printf(": %s", stamp); 416 } 417 printf(") ------\n"); 418 } 419 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; }); 420 421 bool newline = false; 422 fd_set read_set; 423 struct timeval tm; 424 while (1) { 425 FD_ZERO(&read_set); 426 FD_SET(fd, &read_set); 427 /* Timeout if no data is read for 30 seconds. */ 428 tm.tv_sec = 30; 429 tm.tv_usec = 0; 430 uint64_t elapsed = DurationReporter::nanotime(); 431 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm)); 432 if (ret == -1) { 433 printf("*** %s: select failed: %s\n", path, strerror(errno)); 434 newline = true; 435 break; 436 } else if (ret == 0) { 437 elapsed = DurationReporter::nanotime() - elapsed; 438 printf("*** %s: Timed out after %.3fs\n", path, 439 (float) elapsed / NANOS_PER_SEC); 440 newline = true; 441 break; 442 } else { 443 char buffer[65536]; 444 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer))); 445 if (bytes_read > 0) { 446 fwrite(buffer, bytes_read, 1, stdout); 447 newline = (buffer[bytes_read-1] == '\n'); 448 } else { 449 if (bytes_read == -1) { 450 printf("*** %s: Failed to read from fd: %s", path, strerror(errno)); 451 newline = true; 452 } 453 break; 454 } 455 } 456 } 457 update_progress(WEIGHT_FILE); 458 close(fd); 459 460 if (!newline) printf("\n"); 461 if (title) printf("\n"); 462 return 0; 463} 464 465/* prints the contents of a file */ 466int dump_file(const char *title, const char *path) { 467 DurationReporter duration_reporter(title); 468 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC)); 469 if (fd < 0) { 470 int err = errno; 471 printf("*** %s: %s\n", path, strerror(err)); 472 if (title) printf("\n"); 473 return -1; 474 } 475 return _dump_file_from_fd(title, path, fd); 476} 477 478int read_file_as_long(const char *path, long int *output) { 479 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC)); 480 if (fd < 0) { 481 int err = errno; 482 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err)); 483 return -1; 484 } 485 char buffer[50]; 486 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer))); 487 if (bytes_read == -1) { 488 MYLOGE("Error reading file %s: %s\n", path, strerror(errno)); 489 return -2; 490 } 491 if (bytes_read == 0) { 492 MYLOGE("File %s is empty\n", path); 493 return -3; 494 } 495 *output = atoi(buffer); 496 return 0; 497} 498 499/* calls skip to gate calling dump_from_fd recursively 500 * in the specified directory. dump_from_fd defaults to 501 * dump_file_from_fd above when set to NULL. skip defaults 502 * to false when set to NULL. dump_from_fd will always be 503 * called with title NULL. 504 */ 505int dump_files(const char *title, const char *dir, 506 bool (*skip)(const char *path), 507 int (*dump_from_fd)(const char *title, const char *path, int fd)) { 508 DurationReporter duration_reporter(title); 509 DIR *dirp; 510 struct dirent *d; 511 char *newpath = NULL; 512 const char *slash = "/"; 513 int fd, retval = 0; 514 515 if (title) { 516 printf("------ %s (%s) ------\n", title, dir); 517 } 518 ON_DRY_RUN_RETURN(0); 519 520 if (dir[strlen(dir) - 1] == '/') { 521 ++slash; 522 } 523 dirp = opendir(dir); 524 if (dirp == NULL) { 525 retval = -errno; 526 MYLOGE("%s: %s\n", dir, strerror(errno)); 527 return retval; 528 } 529 530 if (!dump_from_fd) { 531 dump_from_fd = dump_file_from_fd; 532 } 533 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) { 534 if ((d->d_name[0] == '.') 535 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0')) 536 || (d->d_name[1] == '\0'))) { 537 continue; 538 } 539 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name, 540 (d->d_type == DT_DIR) ? "/" : ""); 541 if (!newpath) { 542 retval = -errno; 543 continue; 544 } 545 if (skip && (*skip)(newpath)) { 546 continue; 547 } 548 if (d->d_type == DT_DIR) { 549 int ret = dump_files(NULL, newpath, skip, dump_from_fd); 550 if (ret < 0) { 551 retval = ret; 552 } 553 continue; 554 } 555 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)); 556 if (fd < 0) { 557 retval = fd; 558 printf("*** %s: %s\n", newpath, strerror(errno)); 559 continue; 560 } 561 (*dump_from_fd)(NULL, newpath, fd); 562 } 563 closedir(dirp); 564 if (title) { 565 printf("\n"); 566 } 567 return retval; 568} 569 570/* fd must have been opened with the flag O_NONBLOCK. With this flag set, 571 * it's possible to avoid issues where opening the file itself can get 572 * stuck. 573 */ 574int dump_file_from_fd(const char *title, const char *path, int fd) { 575 int flags = fcntl(fd, F_GETFL); 576 if (flags == -1) { 577 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno)); 578 close(fd); 579 return -1; 580 } else if (!(flags & O_NONBLOCK)) { 581 printf("*** %s: fd must have O_NONBLOCK set.\n", path); 582 close(fd); 583 return -1; 584 } 585 return _dump_file_from_fd(title, path, fd); 586} 587 588bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) { 589 sigset_t child_mask, old_mask; 590 sigemptyset(&child_mask); 591 sigaddset(&child_mask, SIGCHLD); 592 593 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) { 594 printf("*** sigprocmask failed: %s\n", strerror(errno)); 595 return false; 596 } 597 598 struct timespec ts; 599 ts.tv_sec = timeout_seconds; 600 ts.tv_nsec = 0; 601 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts)); 602 int saved_errno = errno; 603 // Set the signals back the way they were. 604 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) { 605 printf("*** sigprocmask failed: %s\n", strerror(errno)); 606 if (ret == 0) { 607 return false; 608 } 609 } 610 if (ret == -1) { 611 errno = saved_errno; 612 if (errno == EAGAIN) { 613 errno = ETIMEDOUT; 614 } else { 615 printf("*** sigtimedwait failed: %s\n", strerror(errno)); 616 } 617 return false; 618 } 619 620 pid_t child_pid = waitpid(pid, status, WNOHANG); 621 if (child_pid != pid) { 622 if (child_pid != -1) { 623 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid); 624 } else { 625 printf("*** waitpid failed: %s\n", strerror(errno)); 626 } 627 return false; 628 } 629 return true; 630} 631 632// TODO: refactor all those commands that convert args 633void format_args(const char* command, const char *args[], std::string *string); 634 635int run_command(const char *title, int timeout_seconds, const char *command, ...) { 636 DurationReporter duration_reporter(title); 637 fflush(stdout); 638 639 const char *args[1024] = {command}; 640 size_t arg; 641 va_list ap; 642 va_start(ap, command); 643 if (title) printf("------ %s (%s", title, command); 644 bool null_terminated = false; 645 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) { 646 args[arg] = va_arg(ap, const char *); 647 if (args[arg] == nullptr) { 648 null_terminated = true; 649 break; 650 } 651 // TODO: null_terminated check is not really working; line below would crash dumpstate if 652 // nullptr is missing 653 if (title) printf(" %s", args[arg]); 654 } 655 if (title) printf(") ------\n"); 656 fflush(stdout); 657 if (!null_terminated) { 658 // Fail now, otherwise execvp() call on run_command_always() might hang. 659 std::string cmd; 660 format_args(command, args, &cmd); 661 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str()); 662 return -1; 663 } 664 665 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; }); 666 667 int status = run_command_always(title, false, timeout_seconds, args); 668 va_end(ap); 669 return status; 670} 671 672int run_command_as_shell(const char *title, int timeout_seconds, const char *command, ...) { 673 DurationReporter duration_reporter(title); 674 fflush(stdout); 675 676 const char *args[1024] = {command}; 677 size_t arg; 678 va_list ap; 679 va_start(ap, command); 680 if (title) printf("------ %s (%s", title, command); 681 bool null_terminated = false; 682 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) { 683 args[arg] = va_arg(ap, const char *); 684 if (args[arg] == nullptr) { 685 null_terminated = true; 686 break; 687 } 688 // TODO: null_terminated check is not really working; line below would crash dumpstate if 689 // nullptr is missing 690 if (title) printf(" %s", args[arg]); 691 } 692 if (title) printf(") ------\n"); 693 fflush(stdout); 694 if (!null_terminated) { 695 // Fail now, otherwise execvp() call on run_command_always() might hang. 696 std::string cmd; 697 format_args(command, args, &cmd); 698 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str()); 699 return -1; 700 } 701 702 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; }); 703 704 int status = run_command_always(title, true, timeout_seconds, args); 705 va_end(ap); 706 return status; 707} 708 709/* forks a command and waits for it to finish */ 710int run_command_always(const char *title, bool drop_root, int timeout_seconds, const char *args[]) { 711 // TODO: need to check if args is null-terminated, otherwise execvp will crash dumpstate 712 713 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight. 714 * It's a good approximation for most cases, except when calling dumpsys, where its weight 715 * should be much higher proportionally to its timeout. */ 716 int weight = timeout_seconds; 717 718 const char *command = args[0]; 719 uint64_t start = DurationReporter::nanotime(); 720 pid_t pid = fork(); 721 722 /* handle error case */ 723 if (pid < 0) { 724 printf("*** fork: %s\n", strerror(errno)); 725 return pid; 726 } 727 728 /* handle child case */ 729 if (pid == 0) { 730 if (drop_root && !drop_root_user()) { 731 printf("*** could not drop root before running %s: %s\n", command, strerror(errno)); 732 return -1; 733 } 734 735 /* make sure the child dies when dumpstate dies */ 736 prctl(PR_SET_PDEATHSIG, SIGKILL); 737 738 /* just ignore SIGPIPE, will go down with parent's */ 739 struct sigaction sigact; 740 memset(&sigact, 0, sizeof(sigact)); 741 sigact.sa_handler = SIG_IGN; 742 sigaction(SIGPIPE, &sigact, NULL); 743 744 execvp(command, (char**) args); 745 // execvp's result will be handled after waitpid_with_timeout() below, but if it failed, 746 // it's safer to exit dumpstate. 747 MYLOGD("execvp on command '%s' failed (error: %s)", command, strerror(errno)); 748 fflush(stdout); 749 // Must call _exit (instead of exit), otherwise it will corrupt the zip file. 750 _exit(EXIT_FAILURE); 751 } 752 753 /* handle parent case */ 754 int status; 755 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status); 756 uint64_t elapsed = DurationReporter::nanotime() - start; 757 std::string cmd; // used to log command and its args 758 if (!ret) { 759 if (errno == ETIMEDOUT) { 760 format_args(command, args, &cmd); 761 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(), 762 (float) elapsed / NANOS_PER_SEC, pid); 763 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(), 764 (float) elapsed / NANOS_PER_SEC, pid); 765 } else { 766 format_args(command, args, &cmd); 767 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(), 768 (float) elapsed / NANOS_PER_SEC, pid); 769 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(), 770 (float) elapsed / NANOS_PER_SEC, pid); 771 } 772 kill(pid, SIGTERM); 773 if (!waitpid_with_timeout(pid, 5, NULL)) { 774 kill(pid, SIGKILL); 775 if (!waitpid_with_timeout(pid, 5, NULL)) { 776 printf("couldn not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid); 777 MYLOGE("couldn not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid); 778 } 779 } 780 return -1; 781 } else if (status) { 782 format_args(command, args, &cmd); 783 printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno)); 784 MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno)); 785 return -2; 786 } 787 788 if (WIFSIGNALED(status)) { 789 printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status)); 790 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) { 791 printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status)); 792 } 793 794 if (weight > 0) { 795 update_progress(weight); 796 } 797 return status; 798} 799 800bool drop_root_user() { 801 if (getgid() == AID_SHELL && getuid() == AID_SHELL) { 802 MYLOGD("drop_root_user(): already running as Shell"); 803 return true; 804 } 805 /* ensure we will keep capabilities when we drop root */ 806 if (prctl(PR_SET_KEEPCAPS, 1) < 0) { 807 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno)); 808 return false; 809 } 810 811 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW, 812 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC }; 813 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) { 814 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno)); 815 return false; 816 } 817 if (setgid(AID_SHELL) != 0) { 818 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno)); 819 return false; 820 } 821 if (setuid(AID_SHELL) != 0) { 822 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno)); 823 return false; 824 } 825 826 struct __user_cap_header_struct capheader; 827 struct __user_cap_data_struct capdata[2]; 828 memset(&capheader, 0, sizeof(capheader)); 829 memset(&capdata, 0, sizeof(capdata)); 830 capheader.version = _LINUX_CAPABILITY_VERSION_3; 831 capheader.pid = 0; 832 833 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG); 834 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG); 835 capdata[0].inheritable = 0; 836 capdata[1].inheritable = 0; 837 838 if (capset(&capheader, &capdata[0]) < 0) { 839 MYLOGE("capset failed: %s\n", strerror(errno)); 840 return false; 841 } 842 843 return true; 844} 845 846void send_broadcast(const std::string& action, const std::vector<std::string>& args) { 847 if (args.size() > 1000) { 848 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size()); 849 return; 850 } 851 const char *am_args[1024] = { "/system/bin/am", "broadcast", "--user", "0", "-a", 852 action.c_str() }; 853 size_t am_index = 5; // Starts at the index of last initial value above. 854 for (const std::string& arg : args) { 855 am_args[++am_index] = arg.c_str(); 856 } 857 // Always terminate with NULL. 858 am_args[am_index + 1] = NULL; 859 std::string args_string; 860 format_args(am_index + 1, am_args, &args_string); 861 MYLOGD("send_broadcast command: %s\n", args_string.c_str()); 862 run_command_always(NULL, true, 20, am_args); 863} 864 865size_t num_props = 0; 866static char* props[2000]; 867 868static void print_prop(const char *key, const char *name, void *user) { 869 (void) user; 870 if (num_props < sizeof(props) / sizeof(props[0])) { 871 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10]; 872 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name); 873 props[num_props++] = strdup(buf); 874 } 875} 876 877static int compare_prop(const void *a, const void *b) { 878 return strcmp(*(char * const *) a, *(char * const *) b); 879} 880 881/* prints all the system properties */ 882void print_properties() { 883 const char* title = "SYSTEM PROPERTIES"; 884 DurationReporter duration_reporter(title); 885 printf("------ %s ------\n", title); 886 ON_DRY_RUN_RETURN(); 887 size_t i; 888 num_props = 0; 889 property_list(print_prop, NULL); 890 qsort(&props, num_props, sizeof(props[0]), compare_prop); 891 892 for (i = 0; i < num_props; ++i) { 893 fputs(props[i], stdout); 894 free(props[i]); 895 } 896 printf("\n"); 897} 898 899/* redirect output to a service control socket */ 900void redirect_to_socket(FILE *redirect, const char *service) { 901 int s = android_get_control_socket(service); 902 if (s < 0) { 903 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno)); 904 exit(1); 905 } 906 fcntl(s, F_SETFD, FD_CLOEXEC); 907 if (listen(s, 4) < 0) { 908 MYLOGE("listen(control socket): %s\n", strerror(errno)); 909 exit(1); 910 } 911 912 struct sockaddr addr; 913 socklen_t alen = sizeof(addr); 914 int fd = accept(s, &addr, &alen); 915 if (fd < 0) { 916 MYLOGE("accept(control socket): %s\n", strerror(errno)); 917 exit(1); 918 } 919 920 fflush(redirect); 921 dup2(fd, fileno(redirect)); 922 close(fd); 923} 924 925void create_parent_dirs(const char *path) { 926 char *chp = const_cast<char *> (path); 927 928 /* skip initial slash */ 929 if (chp[0] == '/') 930 chp++; 931 932 /* create leading directories, if necessary */ 933 struct stat dir_stat; 934 while (chp && chp[0]) { 935 chp = strchr(chp, '/'); 936 if (chp) { 937 *chp = 0; 938 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) { 939 MYLOGI("Creating directory %s\n", path); 940 if (mkdir(path, 0770)) { /* drwxrwx--- */ 941 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno)); 942 } else if (chown(path, AID_SHELL, AID_SHELL)) { 943 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno)); 944 } 945 } 946 *chp++ = '/'; 947 } 948 } 949} 950 951/* redirect output to a file */ 952void redirect_to_file(FILE *redirect, char *path) { 953 create_parent_dirs(path); 954 955 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 956 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)); 957 if (fd < 0) { 958 MYLOGE("%s: %s\n", path, strerror(errno)); 959 exit(1); 960 } 961 962 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect))); 963 close(fd); 964} 965 966static bool should_dump_native_traces(const char* path) { 967 for (const char** p = native_processes_to_dump; *p; p++) { 968 if (!strcmp(*p, path)) { 969 return true; 970 } 971 } 972 return false; 973} 974 975/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */ 976const char *dump_traces() { 977 DurationReporter duration_reporter("DUMP TRACES", NULL); 978 ON_DRY_RUN_RETURN(NULL); 979 const char* result = NULL; 980 981 char traces_path[PROPERTY_VALUE_MAX] = ""; 982 property_get("dalvik.vm.stack-trace-file", traces_path, ""); 983 if (!traces_path[0]) return NULL; 984 985 /* move the old traces.txt (if any) out of the way temporarily */ 986 char anr_traces_path[PATH_MAX]; 987 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path)); 988 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path)); 989 if (rename(traces_path, anr_traces_path) && errno != ENOENT) { 990 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno)); 991 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead 992 } 993 994 /* create a new, empty traces.txt file to receive stack dumps */ 995 int fd = TEMP_FAILURE_RETRY(open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 996 0666)); /* -rw-rw-rw- */ 997 if (fd < 0) { 998 MYLOGE("%s: %s\n", traces_path, strerror(errno)); 999 return NULL; 1000 } 1001 int chmod_ret = fchmod(fd, 0666); 1002 if (chmod_ret < 0) { 1003 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno)); 1004 close(fd); 1005 return NULL; 1006 } 1007 1008 /* Variables below must be initialized before 'goto' statements */ 1009 int dalvik_found = 0; 1010 int ifd, wfd = -1; 1011 1012 /* walk /proc and kill -QUIT all Dalvik processes */ 1013 DIR *proc = opendir("/proc"); 1014 if (proc == NULL) { 1015 MYLOGE("/proc: %s\n", strerror(errno)); 1016 goto error_close_fd; 1017 } 1018 1019 /* use inotify to find when processes are done dumping */ 1020 ifd = inotify_init(); 1021 if (ifd < 0) { 1022 MYLOGE("inotify_init: %s\n", strerror(errno)); 1023 goto error_close_fd; 1024 } 1025 1026 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE); 1027 if (wfd < 0) { 1028 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno)); 1029 goto error_close_ifd; 1030 } 1031 1032 struct dirent *d; 1033 while ((d = readdir(proc))) { 1034 int pid = atoi(d->d_name); 1035 if (pid <= 0) continue; 1036 1037 char path[PATH_MAX]; 1038 char data[PATH_MAX]; 1039 snprintf(path, sizeof(path), "/proc/%d/exe", pid); 1040 ssize_t len = readlink(path, data, sizeof(data) - 1); 1041 if (len <= 0) { 1042 continue; 1043 } 1044 data[len] = '\0'; 1045 1046 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) { 1047 /* skip zygote -- it won't dump its stack anyway */ 1048 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid); 1049 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC)); 1050 len = read(cfd, data, sizeof(data) - 1); 1051 close(cfd); 1052 if (len <= 0) { 1053 continue; 1054 } 1055 data[len] = '\0'; 1056 if (!strncmp(data, "zygote", strlen("zygote"))) { 1057 continue; 1058 } 1059 1060 ++dalvik_found; 1061 uint64_t start = DurationReporter::nanotime(); 1062 if (kill(pid, SIGQUIT)) { 1063 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno)); 1064 continue; 1065 } 1066 1067 /* wait for the writable-close notification from inotify */ 1068 struct pollfd pfd = { ifd, POLLIN, 0 }; 1069 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */ 1070 if (ret < 0) { 1071 MYLOGE("poll: %s\n", strerror(errno)); 1072 } else if (ret == 0) { 1073 MYLOGE("warning: timed out dumping pid %d\n", pid); 1074 } else { 1075 struct inotify_event ie; 1076 read(ifd, &ie, sizeof(ie)); 1077 } 1078 1079 if (lseek(fd, 0, SEEK_END) < 0) { 1080 MYLOGE("lseek: %s\n", strerror(errno)); 1081 } else { 1082 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", 1083 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC); 1084 } 1085 } else if (should_dump_native_traces(data)) { 1086 /* dump native process if appropriate */ 1087 if (lseek(fd, 0, SEEK_END) < 0) { 1088 MYLOGE("lseek: %s\n", strerror(errno)); 1089 } else { 1090 static uint16_t timeout_failures = 0; 1091 uint64_t start = DurationReporter::nanotime(); 1092 1093 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */ 1094 if (timeout_failures == 3) { 1095 dprintf(fd, "too many stack dump failures, skipping...\n"); 1096 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) { 1097 dprintf(fd, "dumping failed, likely due to a timeout\n"); 1098 timeout_failures++; 1099 } else { 1100 timeout_failures = 0; 1101 } 1102 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", 1103 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC); 1104 } 1105 } 1106 } 1107 1108 if (dalvik_found == 0) { 1109 MYLOGE("Warning: no Dalvik processes found to dump stacks\n"); 1110 } 1111 1112 static char dump_traces_path[PATH_MAX]; 1113 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path)); 1114 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path)); 1115 if (rename(traces_path, dump_traces_path)) { 1116 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno)); 1117 goto error_close_ifd; 1118 } 1119 result = dump_traces_path; 1120 1121 /* replace the saved [ANR] traces.txt file */ 1122 rename(anr_traces_path, traces_path); 1123 1124error_close_ifd: 1125 close(ifd); 1126error_close_fd: 1127 close(fd); 1128 return result; 1129} 1130 1131void dump_route_tables() { 1132 DurationReporter duration_reporter("DUMP ROUTE TABLES"); 1133 ON_DRY_RUN_RETURN(); 1134 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables"; 1135 dump_file("RT_TABLES", RT_TABLES_PATH); 1136 FILE* fp = fopen(RT_TABLES_PATH, "re"); 1137 if (!fp) { 1138 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno)); 1139 return; 1140 } 1141 char table[16]; 1142 // Each line has an integer (the table number), a space, and a string (the table name). We only 1143 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name. 1144 // Add a fixed max limit so this doesn't go awry. 1145 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) { 1146 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL); 1147 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL); 1148 } 1149 fclose(fp); 1150} 1151 1152/* overall progress */ 1153int progress = 0; 1154int do_update_progress = 0; // Set by dumpstate.cpp 1155int weight_total = WEIGHT_TOTAL; 1156 1157// TODO: make this function thread safe if sections are generated in parallel. 1158void update_progress(int delta) { 1159 if (!do_update_progress) return; 1160 1161 progress += delta; 1162 1163 char key[PROPERTY_KEY_MAX]; 1164 char value[PROPERTY_VALUE_MAX]; 1165 1166 // adjusts max on the fly 1167 if (progress > weight_total) { 1168 int new_total = weight_total * 1.2; 1169 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total); 1170 weight_total = new_total; 1171 sprintf(key, "dumpstate.%d.max", getpid()); 1172 sprintf(value, "%d", weight_total); 1173 int status = property_set(key, value); 1174 if (status) { 1175 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n", 1176 key, value, status); 1177 } 1178 } 1179 1180 sprintf(key, "dumpstate.%d.progress", getpid()); 1181 sprintf(value, "%d", progress); 1182 1183 if (progress % 100 == 0) { 1184 // We don't want to spam logcat, so only log multiples of 100. 1185 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total); 1186 } else { 1187 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate 1188 // directly for debuggging. 1189 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total); 1190 } 1191 1192 int status = property_set(key, value); 1193 if (status) { 1194 MYLOGE("Could not update progress by setting system property %s to %s: %d\n", 1195 key, value, status); 1196 } 1197} 1198 1199void take_screenshot(const std::string& path) { 1200 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL }; 1201 run_command_always(NULL, false, 10, args); 1202} 1203 1204void vibrate(FILE* vibrator, int ms) { 1205 fprintf(vibrator, "%d\n", ms); 1206 fflush(vibrator); 1207} 1208 1209bool is_dir(const char* pathname) { 1210 struct stat info; 1211 if (stat(pathname, &info) == -1) { 1212 return false; 1213 } 1214 return S_ISDIR(info.st_mode); 1215} 1216 1217time_t get_mtime(int fd, time_t default_mtime) { 1218 struct stat info; 1219 if (fstat(fd, &info) == -1) { 1220 return default_mtime; 1221 } 1222 return info.st_mtime; 1223} 1224 1225void dump_emmc_ecsd(const char *ext_csd_path) { 1226 static const size_t EXT_CSD_REV = 192; 1227 static const size_t EXT_PRE_EOL_INFO = 267; 1228 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268; 1229 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269; 1230 struct hex { 1231 char str[2]; 1232 } buffer[512]; 1233 int fd, ext_csd_rev, ext_pre_eol_info; 1234 ssize_t bytes_read; 1235 static const char *ver_str[] = { 1236 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0" 1237 }; 1238 static const char *eol_str[] = { 1239 "Undefined", 1240 "Normal", 1241 "Warning (consumed 80% of reserve)", 1242 "Urgent (consumed 90% of reserve)" 1243 }; 1244 1245 printf("------ %s Extended CSD ------\n", ext_csd_path); 1246 1247 fd = TEMP_FAILURE_RETRY(open(ext_csd_path, 1248 O_RDONLY | O_NONBLOCK | O_CLOEXEC)); 1249 if (fd < 0) { 1250 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno)); 1251 return; 1252 } 1253 1254 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer))); 1255 close(fd); 1256 if (bytes_read < 0) { 1257 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno)); 1258 return; 1259 } 1260 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) { 1261 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read); 1262 return; 1263 } 1264 1265 ext_csd_rev = 0; 1266 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) { 1267 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n", 1268 ext_csd_path, buffer[EXT_CSD_REV].str); 1269 return; 1270 } 1271 1272 printf("rev 1.%d (MMC %s)\n", 1273 ext_csd_rev, 1274 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? 1275 ver_str[ext_csd_rev] : 1276 "Unknown"); 1277 if (ext_csd_rev < 7) { 1278 printf("\n"); 1279 return; 1280 } 1281 1282 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) { 1283 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read); 1284 return; 1285 } 1286 1287 ext_pre_eol_info = 0; 1288 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) { 1289 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n", 1290 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str); 1291 return; 1292 } 1293 printf("PRE_EOL_INFO %d (MMC %s)\n", 1294 ext_pre_eol_info, 1295 eol_str[(ext_pre_eol_info < (int) 1296 (sizeof(eol_str) / sizeof(eol_str[0]))) ? 1297 ext_pre_eol_info : 0]); 1298 1299 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A; 1300 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B; 1301 ++lifetime) { 1302 int ext_device_life_time_est; 1303 static const char *est_str[] = { 1304 "Undefined", 1305 "0-10% of device lifetime used", 1306 "10-20% of device lifetime used", 1307 "20-30% of device lifetime used", 1308 "30-40% of device lifetime used", 1309 "40-50% of device lifetime used", 1310 "50-60% of device lifetime used", 1311 "60-70% of device lifetime used", 1312 "70-80% of device lifetime used", 1313 "80-90% of device lifetime used", 1314 "90-100% of device lifetime used", 1315 "Exceeded the maximum estimated device lifetime", 1316 }; 1317 1318 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) { 1319 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read); 1320 break; 1321 } 1322 1323 ext_device_life_time_est = 0; 1324 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) { 1325 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n", 1326 ext_csd_path, 1327 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A', 1328 buffer[lifetime].str); 1329 continue; 1330 } 1331 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n", 1332 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A', 1333 ext_device_life_time_est, 1334 est_str[(ext_device_life_time_est < (int) 1335 (sizeof(est_str) / sizeof(est_str[0]))) ? 1336 ext_device_life_time_est : 0]); 1337 } 1338 1339 printf("\n"); 1340} 1341 1342// TODO: refactor all those commands that convert args 1343void format_args(int argc, const char *argv[], std::string *args) { 1344 LOG_ALWAYS_FATAL_IF(args == nullptr); 1345 for (int i = 0; i < argc; i++) { 1346 args->append(argv[i]); 1347 if (i < argc -1) { 1348 args->append(" "); 1349 } 1350 } 1351} 1352void format_args(const char* command, const char *args[], std::string *string) { 1353 LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr); 1354 string->append(command); 1355 if (args[0] == nullptr) return; 1356 string->append(" "); 1357 1358 for (int arg = 1; arg <= 1000; ++arg) { 1359 if (args[arg] == nullptr) return; 1360 string->append(args[arg]); 1361 if (args[arg+1] != nullptr) { 1362 string->append(" "); 1363 } 1364 } 1365 // TODO: not really working: if NULL is missing, it will crash dumpstate. 1366 MYLOGE("internal error: missing NULL entry on %s", string->c_str()); 1367} 1368