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