dumpstate.cpp revision d6ab01105bbd80dfa2fc2debc8e31d6422c378ee
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 <libgen.h> 21#include <limits.h> 22#include <memory> 23#include <regex> 24#include <set> 25#include <stdbool.h> 26#include <stdio.h> 27#include <stdlib.h> 28#include <string> 29#include <string.h> 30#include <sys/prctl.h> 31#include <sys/resource.h> 32#include <sys/stat.h> 33#include <sys/time.h> 34#include <sys/wait.h> 35#include <unistd.h> 36 37#include <android-base/stringprintf.h> 38#include <cutils/properties.h> 39 40#include "private/android_filesystem_config.h" 41 42#define LOG_TAG "dumpstate" 43#include <cutils/log.h> 44 45#include "dumpstate.h" 46#include "ScopedFd.h" 47#include "ziparchive/zip_writer.h" 48 49#include "mincrypt/sha256.h" 50 51using android::base::StringPrintf; 52 53/* read before root is shed */ 54static char cmdline_buf[16384] = "(unknown)"; 55static const char *dump_traces_path = NULL; 56 57// TODO: should be part of dumpstate object 58static unsigned long id; 59static char build_type[PROPERTY_VALUE_MAX]; 60static time_t now; 61static std::unique_ptr<ZipWriter> zip_writer; 62static std::set<std::string> mount_points; 63void add_mountinfo(); 64static bool add_zip_entry(const std::string& entry_name, const std::string& entry_path); 65static bool add_zip_entry_from_fd(const std::string& entry_name, int fd); 66 67#define PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops" 68 69#define RAFT_DIR "/data/misc/raft/" 70#define RECOVERY_DIR "/cache/recovery" 71#define RECOVERY_DATA_DIR "/data/misc/recovery" 72#define TOMBSTONE_DIR "/data/tombstones" 73#define TOMBSTONE_FILE_PREFIX TOMBSTONE_DIR "/tombstone_" 74/* Can accomodate a tombstone number up to 9999. */ 75#define TOMBSTONE_MAX_LEN (sizeof(TOMBSTONE_FILE_PREFIX) + 4) 76#define NUM_TOMBSTONES 10 77 78typedef struct { 79 char name[TOMBSTONE_MAX_LEN]; 80 int fd; 81} tombstone_data_t; 82 83static tombstone_data_t tombstone_data[NUM_TOMBSTONES]; 84 85// Root dir for all files copied as-is into the bugreport 86const std::string& ZIP_ROOT_DIR = "FS"; 87 88/* 89 * List of supported zip format versions. 90 * 91 * See bugreport-format.txt for more info. 92 */ 93// TODO: change to "v1" before final N build 94static std::string VERSION_DEFAULT = "v1-dev3"; 95 96/* gets the tombstone data, according to the bugreport type: if zipped gets all tombstones, 97 * otherwise gets just those modified in the last half an hour. */ 98static void get_tombstone_fds(tombstone_data_t data[NUM_TOMBSTONES]) { 99 time_t thirty_minutes_ago = now - 60*30; 100 for (size_t i = 0; i < NUM_TOMBSTONES; i++) { 101 snprintf(data[i].name, sizeof(data[i].name), "%s%02zu", TOMBSTONE_FILE_PREFIX, i); 102 int fd = TEMP_FAILURE_RETRY(open(data[i].name, 103 O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); 104 struct stat st; 105 if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && 106 (zip_writer || (time_t) st.st_mtime >= thirty_minutes_ago)) { 107 data[i].fd = fd; 108 } else { 109 close(fd); 110 data[i].fd = -1; 111 } 112 } 113} 114 115// for_each_pid() callback to get mount info about a process. 116void do_mountinfo(int pid, const char *name) { 117 char path[PATH_MAX]; 118 119 // Gets the the content of the /proc/PID/ns/mnt link, so only unique mount points 120 // are added. 121 sprintf(path, "/proc/%d/ns/mnt", pid); 122 char linkname[PATH_MAX]; 123 ssize_t r = readlink(path, linkname, PATH_MAX); 124 if (r == -1) { 125 MYLOGE("Unable to read link for %s: %s\n", path, strerror(errno)); 126 return; 127 } 128 linkname[r] = '\0'; 129 130 if (mount_points.find(linkname) == mount_points.end()) { 131 // First time this mount point was found: add it 132 sprintf(path, "/proc/%d/mountinfo", pid); 133 if (add_zip_entry(ZIP_ROOT_DIR + path, path)) { 134 mount_points.insert(linkname); 135 } else { 136 MYLOGE("Unable to add mountinfo %s to zip file\n", path); 137 } 138 } 139} 140 141void add_mountinfo() { 142 if (!zip_writer) return; 143 const char *title = "MOUNT INFO"; 144 mount_points.clear(); 145 DurationReporter duration_reporter(title, NULL); 146 for_each_pid(do_mountinfo, NULL); 147 MYLOGD("%s: %d entries added to zip file\n", title, (int) mount_points.size()); 148} 149 150static void dump_dev_files(const char *title, const char *driverpath, const char *filename) 151{ 152 DIR *d; 153 struct dirent *de; 154 char path[PATH_MAX]; 155 156 d = opendir(driverpath); 157 if (d == NULL) { 158 return; 159 } 160 161 while ((de = readdir(d))) { 162 if (de->d_type != DT_LNK) { 163 continue; 164 } 165 snprintf(path, sizeof(path), "%s/%s/%s", driverpath, de->d_name, filename); 166 dump_file(title, path); 167 } 168 169 closedir(d); 170} 171 172static void dump_systrace() { 173 if (!zip_writer) { 174 MYLOGD("Not dumping systrace because zip_writer is not set\n"); 175 return; 176 } 177 const char* path = "/sys/kernel/debug/tracing/tracing_on"; 178 long int is_tracing; 179 if (read_file_as_long(path, &is_tracing)) { 180 return; // error already logged 181 } 182 if (is_tracing <= 0) { 183 MYLOGD("Skipping systrace because '%s' content is '%ld'\n", path, is_tracing); 184 return; 185 } 186 187 DurationReporter duration_reporter("SYSTRACE", nullptr); 188 // systrace output can be many MBs, so we need to redirect its stdout straight to the zip file 189 // by forking and using a pipe. 190 int pipefd[2]; 191 pipe(pipefd); 192 if (fork() == 0) { 193 close(pipefd[0]); // close reading end in the child 194 dup2(pipefd[1], STDOUT_FILENO); // send stdout to the pipe 195 dup2(pipefd[1], STDERR_FILENO); // send stderr to the pipe 196 close(pipefd[1]); // this descriptor is no longer needed 197 198 // TODO: ideally it should use run_command, but it doesn't work well with pipes. 199 // The drawback of calling execl directly is that we're not timing out if it hangs. 200 MYLOGD("Running '/system/bin/atrace --async_dump', which can take several seconds"); 201 execl("/system/bin/atrace", "/system/bin/atrace", "--async_dump", nullptr); 202 // execl should never return, but if it did, we need to exit. 203 MYLOGD("execl on '/system/bin/atrace --async_dump' failed: %s", strerror(errno)); 204 exit(EXIT_FAILURE); 205 } else { 206 close(pipefd[1]); // close the write end of the pipe in the parent 207 add_zip_entry_from_fd("systrace.txt", pipefd[0]); // write output to zip file 208 } 209} 210 211static bool skip_not_stat(const char *path) { 212 static const char stat[] = "/stat"; 213 size_t len = strlen(path); 214 if (path[len - 1] == '/') { /* Directory? */ 215 return false; 216 } 217 return strcmp(path + len - sizeof(stat) + 1, stat); /* .../stat? */ 218} 219 220static bool skip_none(const char *path) { 221 return false; 222} 223 224static const char mmcblk0[] = "/sys/block/mmcblk0/"; 225unsigned long worst_write_perf = 20000; /* in KB/s */ 226 227// 228// stat offsets 229// Name units description 230// ---- ----- ----------- 231// read I/Os requests number of read I/Os processed 232#define __STAT_READ_IOS 0 233// read merges requests number of read I/Os merged with in-queue I/O 234#define __STAT_READ_MERGES 1 235// read sectors sectors number of sectors read 236#define __STAT_READ_SECTORS 2 237// read ticks milliseconds total wait time for read requests 238#define __STAT_READ_TICKS 3 239// write I/Os requests number of write I/Os processed 240#define __STAT_WRITE_IOS 4 241// write merges requests number of write I/Os merged with in-queue I/O 242#define __STAT_WRITE_MERGES 5 243// write sectors sectors number of sectors written 244#define __STAT_WRITE_SECTORS 6 245// write ticks milliseconds total wait time for write requests 246#define __STAT_WRITE_TICKS 7 247// in_flight requests number of I/Os currently in flight 248#define __STAT_IN_FLIGHT 8 249// io_ticks milliseconds total time this block device has been active 250#define __STAT_IO_TICKS 9 251// time_in_queue milliseconds total wait time for all requests 252#define __STAT_IN_QUEUE 10 253#define __STAT_NUMBER_FIELD 11 254// 255// read I/Os, write I/Os 256// ===================== 257// 258// These values increment when an I/O request completes. 259// 260// read merges, write merges 261// ========================= 262// 263// These values increment when an I/O request is merged with an 264// already-queued I/O request. 265// 266// read sectors, write sectors 267// =========================== 268// 269// These values count the number of sectors read from or written to this 270// block device. The "sectors" in question are the standard UNIX 512-byte 271// sectors, not any device- or filesystem-specific block size. The 272// counters are incremented when the I/O completes. 273#define SECTOR_SIZE 512 274// 275// read ticks, write ticks 276// ======================= 277// 278// These values count the number of milliseconds that I/O requests have 279// waited on this block device. If there are multiple I/O requests waiting, 280// these values will increase at a rate greater than 1000/second; for 281// example, if 60 read requests wait for an average of 30 ms, the read_ticks 282// field will increase by 60*30 = 1800. 283// 284// in_flight 285// ========= 286// 287// This value counts the number of I/O requests that have been issued to 288// the device driver but have not yet completed. It does not include I/O 289// requests that are in the queue but not yet issued to the device driver. 290// 291// io_ticks 292// ======== 293// 294// This value counts the number of milliseconds during which the device has 295// had I/O requests queued. 296// 297// time_in_queue 298// ============= 299// 300// This value counts the number of milliseconds that I/O requests have waited 301// on this block device. If there are multiple I/O requests waiting, this 302// value will increase as the product of the number of milliseconds times the 303// number of requests waiting (see "read ticks" above for an example). 304#define S_TO_MS 1000 305// 306 307static int dump_stat_from_fd(const char *title __unused, const char *path, int fd) { 308 unsigned long long fields[__STAT_NUMBER_FIELD]; 309 bool z; 310 char *cp, *buffer = NULL; 311 size_t i = 0; 312 FILE *fp = fdopen(fd, "rb"); 313 getline(&buffer, &i, fp); 314 fclose(fp); 315 if (!buffer) { 316 return -errno; 317 } 318 i = strlen(buffer); 319 while ((i > 0) && (buffer[i - 1] == '\n')) { 320 buffer[--i] = '\0'; 321 } 322 if (!*buffer) { 323 free(buffer); 324 return 0; 325 } 326 z = true; 327 for (cp = buffer, i = 0; i < (sizeof(fields) / sizeof(fields[0])); ++i) { 328 fields[i] = strtoull(cp, &cp, 10); 329 if (fields[i] != 0) { 330 z = false; 331 } 332 } 333 if (z) { /* never accessed */ 334 free(buffer); 335 return 0; 336 } 337 338 if (!strncmp(path, mmcblk0, sizeof(mmcblk0) - 1)) { 339 path += sizeof(mmcblk0) - 1; 340 } 341 342 printf("%s: %s\n", path, buffer); 343 free(buffer); 344 345 if (fields[__STAT_IO_TICKS]) { 346 unsigned long read_perf = 0; 347 unsigned long read_ios = 0; 348 if (fields[__STAT_READ_TICKS]) { 349 unsigned long long divisor = fields[__STAT_READ_TICKS] 350 * fields[__STAT_IO_TICKS]; 351 read_perf = ((unsigned long long)SECTOR_SIZE 352 * fields[__STAT_READ_SECTORS] 353 * fields[__STAT_IN_QUEUE] + (divisor >> 1)) 354 / divisor; 355 read_ios = ((unsigned long long)S_TO_MS * fields[__STAT_READ_IOS] 356 * fields[__STAT_IN_QUEUE] + (divisor >> 1)) 357 / divisor; 358 } 359 360 unsigned long write_perf = 0; 361 unsigned long write_ios = 0; 362 if (fields[__STAT_WRITE_TICKS]) { 363 unsigned long long divisor = fields[__STAT_WRITE_TICKS] 364 * fields[__STAT_IO_TICKS]; 365 write_perf = ((unsigned long long)SECTOR_SIZE 366 * fields[__STAT_WRITE_SECTORS] 367 * fields[__STAT_IN_QUEUE] + (divisor >> 1)) 368 / divisor; 369 write_ios = ((unsigned long long)S_TO_MS * fields[__STAT_WRITE_IOS] 370 * fields[__STAT_IN_QUEUE] + (divisor >> 1)) 371 / divisor; 372 } 373 374 unsigned queue = (fields[__STAT_IN_QUEUE] 375 + (fields[__STAT_IO_TICKS] >> 1)) 376 / fields[__STAT_IO_TICKS]; 377 378 if (!write_perf && !write_ios) { 379 printf("%s: perf(ios) rd: %luKB/s(%lu/s) q: %u\n", 380 path, read_perf, read_ios, queue); 381 } else { 382 printf("%s: perf(ios) rd: %luKB/s(%lu/s) wr: %luKB/s(%lu/s) q: %u\n", 383 path, read_perf, read_ios, write_perf, write_ios, queue); 384 } 385 386 /* bugreport timeout factor adjustment */ 387 if ((write_perf > 1) && (write_perf < worst_write_perf)) { 388 worst_write_perf = write_perf; 389 } 390 } 391 return 0; 392} 393 394/* Copied policy from system/core/logd/LogBuffer.cpp */ 395 396#define LOG_BUFFER_SIZE (256 * 1024) 397#define LOG_BUFFER_MIN_SIZE (64 * 1024UL) 398#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL) 399 400static bool valid_size(unsigned long value) { 401 if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) { 402 return false; 403 } 404 405 long pages = sysconf(_SC_PHYS_PAGES); 406 if (pages < 1) { 407 return true; 408 } 409 410 long pagesize = sysconf(_SC_PAGESIZE); 411 if (pagesize <= 1) { 412 pagesize = PAGE_SIZE; 413 } 414 415 // maximum memory impact a somewhat arbitrary ~3% 416 pages = (pages + 31) / 32; 417 unsigned long maximum = pages * pagesize; 418 419 if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) { 420 return true; 421 } 422 423 return value <= maximum; 424} 425 426static unsigned long property_get_size(const char *key) { 427 unsigned long value; 428 char *cp, property[PROPERTY_VALUE_MAX]; 429 430 property_get(key, property, ""); 431 value = strtoul(property, &cp, 10); 432 433 switch(*cp) { 434 case 'm': 435 case 'M': 436 value *= 1024; 437 /* FALLTHRU */ 438 case 'k': 439 case 'K': 440 value *= 1024; 441 /* FALLTHRU */ 442 case '\0': 443 break; 444 445 default: 446 value = 0; 447 } 448 449 if (!valid_size(value)) { 450 value = 0; 451 } 452 453 return value; 454} 455 456/* timeout in ms */ 457static unsigned long logcat_timeout(const char *name) { 458 static const char global_tuneable[] = "persist.logd.size"; // Settings App 459 static const char global_default[] = "ro.logd.size"; // BoardConfig.mk 460 char key[PROP_NAME_MAX]; 461 unsigned long property_size, default_size; 462 463 default_size = property_get_size(global_tuneable); 464 if (!default_size) { 465 default_size = property_get_size(global_default); 466 } 467 468 snprintf(key, sizeof(key), "%s.%s", global_tuneable, name); 469 property_size = property_get_size(key); 470 471 if (!property_size) { 472 snprintf(key, sizeof(key), "%s.%s", global_default, name); 473 property_size = property_get_size(key); 474 } 475 476 if (!property_size) { 477 property_size = default_size; 478 } 479 480 if (!property_size) { 481 property_size = LOG_BUFFER_SIZE; 482 } 483 484 /* Engineering margin is ten-fold our guess */ 485 return 10 * (property_size + worst_write_perf) / worst_write_perf; 486} 487 488/* End copy from system/core/logd/LogBuffer.cpp */ 489 490/* dumps the current system state to stdout */ 491static void print_header(std::string version) { 492 char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX]; 493 char radio[PROPERTY_VALUE_MAX], bootloader[PROPERTY_VALUE_MAX]; 494 char network[PROPERTY_VALUE_MAX], date[80]; 495 496 property_get("ro.build.display.id", build, "(unknown)"); 497 property_get("ro.build.fingerprint", fingerprint, "(unknown)"); 498 property_get("ro.build.type", build_type, "(unknown)"); 499 property_get("ro.baseband", radio, "(unknown)"); 500 property_get("ro.bootloader", bootloader, "(unknown)"); 501 property_get("gsm.operator.alpha", network, "(unknown)"); 502 strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now)); 503 504 printf("========================================================\n"); 505 printf("== dumpstate: %s\n", date); 506 printf("========================================================\n"); 507 508 printf("\n"); 509 printf("Build: %s\n", build); 510 printf("Build fingerprint: '%s'\n", fingerprint); /* format is important for other tools */ 511 printf("Bootloader: %s\n", bootloader); 512 printf("Radio: %s\n", radio); 513 printf("Network: %s\n", network); 514 515 printf("Kernel: "); 516 dump_file(NULL, "/proc/version"); 517 printf("Command line: %s\n", strtok(cmdline_buf, "\n")); 518 printf("Bugreport format version: %s\n", version.c_str()); 519 printf("Dumpstate info: id=%lu pid=%d\n", id, getpid()); 520 printf("\n"); 521} 522 523/* adds a new entry to the existing zip file. */ 524static bool add_zip_entry_from_fd(const std::string& entry_name, int fd) { 525 if (!zip_writer) { 526 MYLOGD("Not adding zip entry %s from fd because zip_writer is not set\n", 527 entry_name.c_str()); 528 return false; 529 } 530 // Logging statement below is useful to time how long each entry takes, but it's too verbose. 531 // MYLOGD("Adding zip entry %s\n", entry_name.c_str()); 532 int32_t err = zip_writer->StartEntryWithTime(entry_name.c_str(), 533 ZipWriter::kCompress, get_mtime(fd, now)); 534 if (err) { 535 MYLOGE("zip_writer->StartEntryWithTime(%s): %s\n", entry_name.c_str(), 536 ZipWriter::ErrorCodeString(err)); 537 return false; 538 } 539 540 std::vector<uint8_t> buffer(65536); 541 while (1) { 542 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), sizeof(buffer))); 543 if (bytes_read == 0) { 544 break; 545 } else if (bytes_read == -1) { 546 MYLOGE("read(%s): %s\n", entry_name.c_str(), strerror(errno)); 547 return false; 548 } 549 err = zip_writer->WriteBytes(buffer.data(), bytes_read); 550 if (err) { 551 MYLOGE("zip_writer->WriteBytes(): %s\n", ZipWriter::ErrorCodeString(err)); 552 return false; 553 } 554 } 555 556 err = zip_writer->FinishEntry(); 557 if (err) { 558 MYLOGE("zip_writer->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err)); 559 return false; 560 } 561 562 return true; 563} 564 565/* adds a new entry to the existing zip file. */ 566static bool add_zip_entry(const std::string& entry_name, const std::string& entry_path) { 567 ScopedFd fd(TEMP_FAILURE_RETRY(open(entry_path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC))); 568 if (fd.get() == -1) { 569 MYLOGE("open(%s): %s\n", entry_path.c_str(), strerror(errno)); 570 return false; 571 } 572 573 return add_zip_entry_from_fd(entry_name, fd.get()); 574} 575 576/* adds a file to the existing zipped bugreport */ 577static int _add_file_from_fd(const char *title, const char *path, int fd) { 578 return add_zip_entry_from_fd(ZIP_ROOT_DIR + path, fd) ? 0 : 1; 579} 580 581/* adds all files from a directory to the zipped bugreport file */ 582void add_dir(const char *dir, bool recursive) { 583 if (!zip_writer) { 584 MYLOGD("Not adding dir %s because zip_writer is not set\n", dir); 585 return; 586 } 587 MYLOGD("Adding dir %s (recursive: %d)\n", dir, recursive); 588 DurationReporter duration_reporter(dir, NULL); 589 dump_files(NULL, dir, recursive ? skip_none : is_dir, _add_file_from_fd); 590} 591 592/* adds a text entry entry to the existing zip file. */ 593static bool add_text_zip_entry(const std::string& entry_name, const std::string& content) { 594 if (!zip_writer) { 595 MYLOGD("Not adding text zip entry %s because zip_writer is not set\n", entry_name.c_str()); 596 return false; 597 } 598 MYLOGD("Adding zip text entry %s\n", entry_name.c_str()); 599 int32_t err = zip_writer->StartEntryWithTime(entry_name.c_str(), ZipWriter::kCompress, now); 600 if (err) { 601 MYLOGE("zip_writer->StartEntryWithTime(%s): %s\n", entry_name.c_str(), 602 ZipWriter::ErrorCodeString(err)); 603 return false; 604 } 605 606 err = zip_writer->WriteBytes(content.c_str(), content.length()); 607 if (err) { 608 MYLOGE("zip_writer->WriteBytes(%s): %s\n", entry_name.c_str(), 609 ZipWriter::ErrorCodeString(err)); 610 return false; 611 } 612 613 err = zip_writer->FinishEntry(); 614 if (err) { 615 MYLOGE("zip_writer->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err)); 616 return false; 617 } 618 619 return true; 620} 621 622static void dumpstate(const std::string& screenshot_path, const std::string& version) { 623 DurationReporter duration_reporter("DUMPSTATE"); 624 unsigned long timeout; 625 626 dump_dev_files("TRUSTY VERSION", "/sys/bus/platform/drivers/trusty", "trusty_version"); 627 run_command("UPTIME", 10, "uptime", NULL); 628 dump_files("UPTIME MMC PERF", mmcblk0, skip_not_stat, dump_stat_from_fd); 629 dump_emmc_ecsd("/d/mmc0/mmc0:0001/ext_csd"); 630 dump_file("MEMORY INFO", "/proc/meminfo"); 631 run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-H", NULL); 632 run_command("PROCRANK", 20, SU_PATH, "root", "procrank", NULL); 633 dump_file("VIRTUAL MEMORY STATS", "/proc/vmstat"); 634 dump_file("VMALLOC INFO", "/proc/vmallocinfo"); 635 dump_file("SLAB INFO", "/proc/slabinfo"); 636 dump_file("ZONEINFO", "/proc/zoneinfo"); 637 dump_file("PAGETYPEINFO", "/proc/pagetypeinfo"); 638 dump_file("BUDDYINFO", "/proc/buddyinfo"); 639 dump_file("FRAGMENTATION INFO", "/d/extfrag/unusable_index"); 640 641 dump_file("KERNEL WAKE SOURCES", "/d/wakeup_sources"); 642 dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state"); 643 dump_file("KERNEL SYNC", "/d/sync"); 644 645 run_command("PROCESSES AND THREADS", 10, "ps", "-Z", "-t", "-p", "-P", NULL); 646 run_command("LIBRANK", 10, SU_PATH, "root", "librank", NULL); 647 648 run_command("PRINTENV", 10, "printenv", NULL); 649 run_command("NETSTAT", 10, "netstat", "-n", NULL); 650 run_command("LSMOD", 10, "lsmod", NULL); 651 652 do_dmesg(); 653 654 run_command("LIST OF OPEN FILES", 10, SU_PATH, "root", "lsof", NULL); 655 for_each_pid(do_showmap, "SMAPS OF ALL PROCESSES"); 656 for_each_tid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS"); 657 for_each_pid(show_showtime, "PROCESS TIMES (pid cmd user system iowait+percentage)"); 658 659 if (!screenshot_path.empty()) { 660 MYLOGI("taking late screenshot\n"); 661 take_screenshot(screenshot_path); 662 MYLOGI("wrote screenshot: %s\n", screenshot_path.c_str()); 663 } 664 665 // dump_file("EVENT LOG TAGS", "/etc/event-log-tags"); 666 // calculate timeout 667 timeout = logcat_timeout("main") + logcat_timeout("system") + logcat_timeout("crash"); 668 if (timeout < 20000) { 669 timeout = 20000; 670 } 671 run_command("SYSTEM LOG", timeout / 1000, "logcat", "-v", "threadtime", 672 "-v", "printable", 673 "-d", 674 "*:v", NULL); 675 timeout = logcat_timeout("events"); 676 if (timeout < 20000) { 677 timeout = 20000; 678 } 679 run_command("EVENT LOG", timeout / 1000, "logcat", "-b", "events", 680 "-v", "threadtime", 681 "-v", "printable", 682 "-d", 683 "*:v", NULL); 684 timeout = logcat_timeout("radio"); 685 if (timeout < 20000) { 686 timeout = 20000; 687 } 688 run_command("RADIO LOG", timeout / 1000, "logcat", "-b", "radio", 689 "-v", "threadtime", 690 "-v", "printable", 691 "-d", 692 "*:v", NULL); 693 694 run_command("LOG STATISTICS", 10, "logcat", "-b", "all", "-S", NULL); 695 696 run_command("RAFT LOGS", 600, SU_PATH, "root", "logcompressor", "-r", RAFT_DIR, NULL); 697 698 /* show the traces we collected in main(), if that was done */ 699 if (dump_traces_path != NULL) { 700 dump_file("VM TRACES JUST NOW", dump_traces_path); 701 } 702 703 /* only show ANR traces if they're less than 15 minutes old */ 704 struct stat st; 705 char anr_traces_path[PATH_MAX]; 706 property_get("dalvik.vm.stack-trace-file", anr_traces_path, ""); 707 if (!anr_traces_path[0]) { 708 printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n"); 709 } else { 710 int fd = TEMP_FAILURE_RETRY(open(anr_traces_path, 711 O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)); 712 if (fd < 0) { 713 printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_path, strerror(errno)); 714 } else { 715 dump_file_from_fd("VM TRACES AT LAST ANR", anr_traces_path, fd); 716 } 717 } 718 719 /* slow traces for slow operations */ 720 if (anr_traces_path[0] != 0) { 721 int tail = strlen(anr_traces_path)-1; 722 while (tail > 0 && anr_traces_path[tail] != '/') { 723 tail--; 724 } 725 int i = 0; 726 while (1) { 727 sprintf(anr_traces_path+tail+1, "slow%02d.txt", i); 728 if (stat(anr_traces_path, &st)) { 729 // No traces file at this index, done with the files. 730 break; 731 } 732 dump_file("VM TRACES WHEN SLOW", anr_traces_path); 733 i++; 734 } 735 } 736 737 int dumped = 0; 738 for (size_t i = 0; i < NUM_TOMBSTONES; i++) { 739 if (tombstone_data[i].fd != -1) { 740 const char *name = tombstone_data[i].name; 741 int fd = tombstone_data[i].fd; 742 dumped = 1; 743 if (zip_writer) { 744 if (!add_zip_entry_from_fd(ZIP_ROOT_DIR + name, fd)) { 745 MYLOGE("Unable to add tombstone %s to zip file\n", name); 746 } 747 } else { 748 dump_file_from_fd("TOMBSTONE", name, fd); 749 } 750 close(fd); 751 tombstone_data[i].fd = -1; 752 } 753 } 754 if (!dumped) { 755 printf("*** NO TOMBSTONES to dump in %s\n\n", TOMBSTONE_DIR); 756 } 757 758 dump_file("NETWORK DEV INFO", "/proc/net/dev"); 759 dump_file("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all"); 760 dump_file("QTAGUID NETWORK INTERFACES INFO (xt)", "/proc/net/xt_qtaguid/iface_stat_fmt"); 761 dump_file("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl"); 762 dump_file("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats"); 763 764 if (!stat(PSTORE_LAST_KMSG, &st)) { 765 /* Also TODO: Make console-ramoops CAP_SYSLOG protected. */ 766 dump_file("LAST KMSG", PSTORE_LAST_KMSG); 767 } else { 768 /* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */ 769 dump_file("LAST KMSG", "/proc/last_kmsg"); 770 } 771 772 /* kernels must set CONFIG_PSTORE_PMSG, slice up pstore with device tree */ 773 run_command("LAST LOGCAT", 10, "logcat", "-L", 774 "-b", "all", 775 "-v", "threadtime", 776 "-v", "printable", 777 "-d", 778 "*:v", NULL); 779 780 /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */ 781 782 run_command("NETWORK INTERFACES", 10, "ip", "link", NULL); 783 784 run_command("IPv4 ADDRESSES", 10, "ip", "-4", "addr", "show", NULL); 785 run_command("IPv6 ADDRESSES", 10, "ip", "-6", "addr", "show", NULL); 786 787 run_command("IP RULES", 10, "ip", "rule", "show", NULL); 788 run_command("IP RULES v6", 10, "ip", "-6", "rule", "show", NULL); 789 790 dump_route_tables(); 791 792 run_command("ARP CACHE", 10, "ip", "-4", "neigh", "show", NULL); 793 run_command("IPv6 ND CACHE", 10, "ip", "-6", "neigh", "show", NULL); 794 795 run_command("IPTABLES", 10, SU_PATH, "root", "iptables", "-L", "-nvx", NULL); 796 run_command("IP6TABLES", 10, SU_PATH, "root", "ip6tables", "-L", "-nvx", NULL); 797 run_command("IPTABLE NAT", 10, SU_PATH, "root", "iptables", "-t", "nat", "-L", "-nvx", NULL); 798 /* no ip6 nat */ 799 run_command("IPTABLE RAW", 10, SU_PATH, "root", "iptables", "-t", "raw", "-L", "-nvx", NULL); 800 run_command("IP6TABLE RAW", 10, SU_PATH, "root", "ip6tables", "-t", "raw", "-L", "-nvx", NULL); 801 802 run_command("WIFI NETWORKS", 20, 803 SU_PATH, "root", "wpa_cli", "IFNAME=wlan0", "list_networks", NULL); 804 805#ifdef FWDUMP_bcmdhd 806 run_command("ND OFFLOAD TABLE", 5, 807 SU_PATH, "root", "wlutil", "nd_hostip", NULL); 808 809 run_command("DUMP WIFI INTERNAL COUNTERS (1)", 20, 810 SU_PATH, "root", "wlutil", "counters", NULL); 811 812 run_command("ND OFFLOAD STATUS (1)", 5, 813 SU_PATH, "root", "wlutil", "nd_status", NULL); 814 815#endif 816 dump_file("INTERRUPTS (1)", "/proc/interrupts"); 817 818 run_command("NETWORK DIAGNOSTICS", 10, "dumpsys", "connectivity", "--diag", NULL); 819 820#ifdef FWDUMP_bcmdhd 821 run_command("DUMP WIFI STATUS", 20, 822 SU_PATH, "root", "dhdutil", "-i", "wlan0", "dump", NULL); 823 824 run_command("DUMP WIFI INTERNAL COUNTERS (2)", 20, 825 SU_PATH, "root", "wlutil", "counters", NULL); 826 827 run_command("ND OFFLOAD STATUS (2)", 5, 828 SU_PATH, "root", "wlutil", "nd_status", NULL); 829#endif 830 dump_file("INTERRUPTS (2)", "/proc/interrupts"); 831 832 print_properties(); 833 834 run_command("VOLD DUMP", 10, "vdc", "dump", NULL); 835 run_command("SECURE CONTAINERS", 10, "vdc", "asec", "list", NULL); 836 837 run_command("FILESYSTEMS & FREE SPACE", 10, "df", NULL); 838 839 run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL); 840 841 printf("------ BACKLIGHTS ------\n"); 842 printf("LCD brightness="); 843 dump_file(NULL, "/sys/class/leds/lcd-backlight/brightness"); 844 printf("Button brightness="); 845 dump_file(NULL, "/sys/class/leds/button-backlight/brightness"); 846 printf("Keyboard brightness="); 847 dump_file(NULL, "/sys/class/leds/keyboard-backlight/brightness"); 848 printf("ALS mode="); 849 dump_file(NULL, "/sys/class/leds/lcd-backlight/als"); 850 printf("LCD driver registers:\n"); 851 dump_file(NULL, "/sys/class/leds/lcd-backlight/registers"); 852 printf("\n"); 853 854 /* Binder state is expensive to look at as it uses a lot of memory. */ 855 dump_file("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log"); 856 dump_file("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log"); 857 dump_file("BINDER TRANSACTIONS", "/sys/kernel/debug/binder/transactions"); 858 dump_file("BINDER STATS", "/sys/kernel/debug/binder/stats"); 859 dump_file("BINDER STATE", "/sys/kernel/debug/binder/state"); 860 861 printf("========================================================\n"); 862 printf("== Board\n"); 863 printf("========================================================\n"); 864 865 dumpstate_board(); 866 printf("\n"); 867 868 /* Migrate the ril_dumpstate to a dumpstate_board()? */ 869 char ril_dumpstate_timeout[PROPERTY_VALUE_MAX] = {0}; 870 property_get("ril.dumpstate.timeout", ril_dumpstate_timeout, "30"); 871 if (strnlen(ril_dumpstate_timeout, PROPERTY_VALUE_MAX - 1) > 0) { 872 if (0 == strncmp(build_type, "user", PROPERTY_VALUE_MAX - 1)) { 873 // su does not exist on user builds, so try running without it. 874 // This way any implementations of vril-dump that do not require 875 // root can run on user builds. 876 run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout), 877 "vril-dump", NULL); 878 } else { 879 run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout), 880 SU_PATH, "root", "vril-dump", NULL); 881 } 882 } 883 884 printf("========================================================\n"); 885 printf("== Android Framework Services\n"); 886 printf("========================================================\n"); 887 888 run_command("DUMPSYS", 60, "dumpsys", "-t", "60", "--skip", "meminfo,cpuinfo", NULL); 889 890 printf("========================================================\n"); 891 printf("== Checkins\n"); 892 printf("========================================================\n"); 893 894 run_command("CHECKIN BATTERYSTATS", 30, "dumpsys", "batterystats", "-c", NULL); 895 run_command("CHECKIN MEMINFO", 30, "dumpsys", "meminfo", "--checkin", NULL); 896 run_command("CHECKIN NETSTATS", 30, "dumpsys", "netstats", "--checkin", NULL); 897 run_command("CHECKIN PROCSTATS", 30, "dumpsys", "procstats", "-c", NULL); 898 run_command("CHECKIN USAGESTATS", 30, "dumpsys", "usagestats", "-c", NULL); 899 run_command("CHECKIN PACKAGE", 30, "dumpsys", "package", "--checkin", NULL); 900 901 printf("========================================================\n"); 902 printf("== Running Application Activities\n"); 903 printf("========================================================\n"); 904 905 run_command("APP ACTIVITIES", 30, "dumpsys", "activity", "all", NULL); 906 907 printf("========================================================\n"); 908 printf("== Running Application Services\n"); 909 printf("========================================================\n"); 910 911 run_command("APP SERVICES", 30, "dumpsys", "activity", "service", "all", NULL); 912 913 printf("========================================================\n"); 914 printf("== Running Application Providers\n"); 915 printf("========================================================\n"); 916 917 run_command("APP SERVICES", 30, "dumpsys", "activity", "provider", "all", NULL); 918 919 920 printf("========================================================\n"); 921 printf("== Final progress (pid %d): %d/%d (originally %d)\n", 922 getpid(), progress, weight_total, WEIGHT_TOTAL); 923 printf("========================================================\n"); 924 printf("== dumpstate: done\n"); 925 printf("========================================================\n"); 926} 927 928static void usage() { 929 fprintf(stderr, "usage: dumpstate [-b soundfile] [-e soundfile] [-o file [-d] [-p] [-z]] [-s] [-q] [-B] [-P] [-R] [-V version]\n" 930 " -b: play sound file instead of vibrate, at beginning of job\n" 931 " -e: play sound file instead of vibrate, at end of job\n" 932 " -o: write to file (instead of stdout)\n" 933 " -d: append date to filename (requires -o)\n" 934 " -p: capture screenshot to filename.png (requires -o)\n" 935 " -z: generates zipped file (requires -o)\n" 936 " -s: write output to control socket (for init)\n" 937 " -q: disable vibrate\n" 938 " -B: send broadcast when finished (requires -o)\n" 939 " -P: send broadcast when started and update system properties on progress (requires -o and -B)\n" 940 " -R: take bugreport in remote mode (requires -o, -z, -d and -B, shouldn't be used with -P)\n" 941 " -V: sets the bugreport format version (valid values: %s)\n", 942 VERSION_DEFAULT.c_str()); 943} 944 945static void sigpipe_handler(int n) { 946 // don't complain to stderr or stdout 947 _exit(EXIT_FAILURE); 948} 949 950/* adds the temporary report to the existing .zip file, closes the .zip file, and removes the 951 temporary file. 952 */ 953static bool finish_zip_file(const std::string& bugreport_name, const std::string& bugreport_path, 954 time_t now) { 955 if (!add_zip_entry(bugreport_name, bugreport_path)) { 956 MYLOGE("Failed to add text entry to .zip file\n"); 957 return false; 958 } 959 if (!add_text_zip_entry("main_entry.txt", bugreport_name)) { 960 MYLOGE("Failed to add main_entry.txt to .zip file\n"); 961 return false; 962 } 963 964 int32_t err = zip_writer->Finish(); 965 if (err) { 966 MYLOGE("zip_writer->Finish(): %s\n", ZipWriter::ErrorCodeString(err)); 967 return false; 968 } 969 970 return true; 971} 972 973static std::string SHA256_file_hash(std::string filepath) { 974 ScopedFd fd(TEMP_FAILURE_RETRY(open(filepath.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC 975 | O_NOFOLLOW))); 976 if (fd.get() == -1) { 977 MYLOGE("open(%s): %s\n", filepath.c_str(), strerror(errno)); 978 return NULL; 979 } 980 981 SHA256_CTX ctx; 982 SHA256_init(&ctx); 983 984 std::vector<uint8_t> buffer(65536); 985 while (1) { 986 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd.get(), buffer.data(), buffer.size())); 987 if (bytes_read == 0) { 988 break; 989 } else if (bytes_read == -1) { 990 MYLOGE("read(%s): %s\n", filepath.c_str(), strerror(errno)); 991 return NULL; 992 } 993 994 SHA256_update(&ctx, buffer.data(), bytes_read); 995 } 996 997 uint8_t hash[SHA256_DIGEST_SIZE]; 998 memcpy(hash, SHA256_final(&ctx), SHA256_DIGEST_SIZE); 999 char hash_buffer[SHA256_DIGEST_SIZE * 2 + 1]; 1000 for(size_t i = 0; i < SHA256_DIGEST_SIZE; i++) { 1001 sprintf(hash_buffer + (i * 2), "%02x", hash[i]); 1002 } 1003 hash_buffer[sizeof(hash_buffer) - 1] = 0; 1004 return std::string(hash_buffer); 1005} 1006 1007int main(int argc, char *argv[]) { 1008 struct sigaction sigact; 1009 int do_add_date = 0; 1010 int do_zip_file = 0; 1011 int do_vibrate = 1; 1012 char* use_outfile = 0; 1013 int use_socket = 0; 1014 int do_fb = 0; 1015 int do_broadcast = 0; 1016 int do_early_screenshot = 0; 1017 int is_remote_mode = 0; 1018 std::string version = VERSION_DEFAULT; 1019 1020 now = time(NULL); 1021 1022 if (getuid() != 0) { 1023 // Old versions of the adb client would call the 1024 // dumpstate command directly. Newer clients 1025 // call /system/bin/bugreport instead. If we detect 1026 // we're being called incorrectly, then exec the 1027 // correct program. 1028 return execl("/system/bin/bugreport", "/system/bin/bugreport", NULL); 1029 } 1030 1031 MYLOGI("begin\n"); 1032 1033 /* gets the sequential id */ 1034 char last_id[PROPERTY_VALUE_MAX]; 1035 property_get("dumpstate.last_id", last_id, "0"); 1036 id = strtoul(last_id, NULL, 10) + 1; 1037 sprintf(last_id, "%lu", id); 1038 property_set("dumpstate.last_id", last_id); 1039 MYLOGI("dumpstate id: %lu\n", id); 1040 1041 /* clear SIGPIPE handler */ 1042 memset(&sigact, 0, sizeof(sigact)); 1043 sigact.sa_handler = sigpipe_handler; 1044 sigaction(SIGPIPE, &sigact, NULL); 1045 1046 /* set as high priority, and protect from OOM killer */ 1047 setpriority(PRIO_PROCESS, 0, -20); 1048 FILE *oom_adj = fopen("/proc/self/oom_adj", "we"); 1049 if (oom_adj) { 1050 fputs("-17", oom_adj); 1051 fclose(oom_adj); 1052 } 1053 1054 /* parse arguments */ 1055 std::string args; 1056 format_args(argc, const_cast<const char **>(argv), &args); 1057 MYLOGD("Dumpstate command line: %s\n", args.c_str()); 1058 int c; 1059 while ((c = getopt(argc, argv, "dho:svqzpPBRV:")) != -1) { 1060 switch (c) { 1061 case 'd': do_add_date = 1; break; 1062 case 'z': do_zip_file = 1; break; 1063 case 'o': use_outfile = optarg; break; 1064 case 's': use_socket = 1; break; 1065 case 'v': break; // compatibility no-op 1066 case 'q': do_vibrate = 0; break; 1067 case 'p': do_fb = 1; break; 1068 case 'P': do_update_progress = 1; break; 1069 case 'R': is_remote_mode = 1; break; 1070 case 'B': do_broadcast = 1; break; 1071 case 'V': version = optarg; break; 1072 case '?': printf("\n"); 1073 case 'h': 1074 usage(); 1075 exit(1); 1076 } 1077 } 1078 1079 if ((do_zip_file || do_add_date || do_update_progress || do_broadcast) && !use_outfile) { 1080 usage(); 1081 exit(1); 1082 } 1083 1084 if (do_update_progress && !do_broadcast) { 1085 usage(); 1086 exit(1); 1087 } 1088 1089 if (is_remote_mode && (do_update_progress || !do_broadcast || !do_zip_file || !do_add_date)) { 1090 usage(); 1091 exit(1); 1092 } 1093 1094 if (version != VERSION_DEFAULT) { 1095 usage(); 1096 exit(1); 1097 } 1098 1099 MYLOGI("bugreport format version: %s\n", version.c_str()); 1100 1101 do_early_screenshot = do_update_progress; 1102 1103 // If we are going to use a socket, do it as early as possible 1104 // to avoid timeouts from bugreport. 1105 if (use_socket) { 1106 redirect_to_socket(stdout, "dumpstate"); 1107 } 1108 1109 /* full path of the directory where the bugreport files will be written */ 1110 std::string bugreport_dir; 1111 1112 /* full path of the temporary file containing the bugreport */ 1113 std::string tmp_path; 1114 1115 /* full path of the file containing the dumpstate logs*/ 1116 std::string log_path; 1117 1118 /* full path of the temporary file containing the screenshot (when requested) */ 1119 std::string screenshot_path; 1120 1121 /* base name (without suffix or extensions) of the bugreport files */ 1122 std::string base_name; 1123 1124 /* suffix of the bugreport files - it's typically the date (when invoked with -d), 1125 * although it could be changed by the user using a system property */ 1126 std::string suffix; 1127 1128 /* pointer to the actual path, be it zip or text */ 1129 std::string path; 1130 1131 /* pointer to the zipped file */ 1132 std::unique_ptr<FILE, int(*)(FILE*)> zip_file(NULL, fclose); 1133 1134 /* redirect output if needed */ 1135 bool is_redirecting = !use_socket && use_outfile; 1136 1137 if (is_redirecting) { 1138 bugreport_dir = dirname(use_outfile); 1139 base_name = basename(use_outfile); 1140 if (do_add_date) { 1141 char date[80]; 1142 strftime(date, sizeof(date), "%Y-%m-%d-%H-%M-%S", localtime(&now)); 1143 suffix = date; 1144 } else { 1145 suffix = "undated"; 1146 } 1147 if (do_fb) { 1148 // TODO: if dumpstate was an object, the paths could be internal variables and then 1149 // we could have a function to calculate the derived values, such as: 1150 // screenshot_path = GetPath(".png"); 1151 screenshot_path = bugreport_dir + "/" + base_name + "-" + suffix + ".png"; 1152 } 1153 tmp_path = bugreport_dir + "/" + base_name + "-" + suffix + ".tmp"; 1154 log_path = bugreport_dir + "/dumpstate_log-" + suffix + "-" 1155 + std::to_string(getpid()) + ".txt"; 1156 1157 MYLOGD("Bugreport dir: %s\n" 1158 "Base name: %s\n" 1159 "Suffix: %s\n" 1160 "Log path: %s\n" 1161 "Temporary path: %s\n" 1162 "Screenshot path: %s\n", 1163 bugreport_dir.c_str(), base_name.c_str(), suffix.c_str(), 1164 log_path.c_str(), tmp_path.c_str(), screenshot_path.c_str()); 1165 1166 if (do_zip_file) { 1167 path = bugreport_dir + "/" + base_name + "-" + suffix + ".zip"; 1168 MYLOGD("Creating initial .zip file (%s)\n", path.c_str()); 1169 create_parent_dirs(path.c_str()); 1170 zip_file.reset(fopen(path.c_str(), "wb")); 1171 if (!zip_file) { 1172 MYLOGE("fopen(%s, 'wb'): %s\n", path.c_str(), strerror(errno)); 1173 do_zip_file = 0; 1174 } else { 1175 zip_writer.reset(new ZipWriter(zip_file.get())); 1176 } 1177 add_text_zip_entry("version.txt", version); 1178 } 1179 1180 if (do_update_progress) { 1181 std::vector<std::string> am_args = { 1182 "--receiver-permission", "android.permission.DUMP", "--receiver-foreground", 1183 "--es", "android.intent.extra.NAME", suffix, 1184 "--ei", "android.intent.extra.ID", std::to_string(id), 1185 "--ei", "android.intent.extra.PID", std::to_string(getpid()), 1186 "--ei", "android.intent.extra.MAX", std::to_string(WEIGHT_TOTAL), 1187 }; 1188 send_broadcast("android.intent.action.BUGREPORT_STARTED", am_args); 1189 } 1190 } 1191 1192 /* read /proc/cmdline before dropping root */ 1193 FILE *cmdline = fopen("/proc/cmdline", "re"); 1194 if (cmdline) { 1195 fgets(cmdline_buf, sizeof(cmdline_buf), cmdline); 1196 fclose(cmdline); 1197 } 1198 1199 /* open the vibrator before dropping root */ 1200 std::unique_ptr<FILE, int(*)(FILE*)> vibrator(NULL, fclose); 1201 if (do_vibrate) { 1202 vibrator.reset(fopen("/sys/class/timed_output/vibrator/enable", "we")); 1203 if (vibrator) { 1204 vibrate(vibrator.get(), 150); 1205 } 1206 } 1207 1208 if (do_fb && do_early_screenshot) { 1209 if (screenshot_path.empty()) { 1210 // should not have happened 1211 MYLOGE("INTERNAL ERROR: skipping early screenshot because path was not set\n"); 1212 } else { 1213 MYLOGI("taking early screenshot\n"); 1214 take_screenshot(screenshot_path); 1215 MYLOGI("wrote screenshot: %s\n", screenshot_path.c_str()); 1216 if (chown(screenshot_path.c_str(), AID_SHELL, AID_SHELL)) { 1217 MYLOGE("Unable to change ownership of screenshot file %s: %s\n", 1218 screenshot_path.c_str(), strerror(errno)); 1219 } 1220 } 1221 } 1222 1223 if (do_zip_file) { 1224 if (chown(path.c_str(), AID_SHELL, AID_SHELL)) { 1225 MYLOGE("Unable to change ownership of zip file %s: %s\n", path.c_str(), strerror(errno)); 1226 } 1227 } 1228 1229 if (is_redirecting) { 1230 redirect_to_file(stderr, const_cast<char*>(log_path.c_str())); 1231 if (chown(log_path.c_str(), AID_SHELL, AID_SHELL)) { 1232 MYLOGE("Unable to change ownership of dumpstate log file %s: %s\n", 1233 log_path.c_str(), strerror(errno)); 1234 } 1235 /* TODO: rather than generating a text file now and zipping it later, 1236 it would be more efficient to redirect stdout to the zip entry 1237 directly, but the libziparchive doesn't support that option yet. */ 1238 redirect_to_file(stdout, const_cast<char*>(tmp_path.c_str())); 1239 if (chown(tmp_path.c_str(), AID_SHELL, AID_SHELL)) { 1240 MYLOGE("Unable to change ownership of temporary bugreport file %s: %s\n", 1241 tmp_path.c_str(), strerror(errno)); 1242 } 1243 } 1244 // NOTE: there should be no stdout output until now, otherwise it would break the header. 1245 // In particular, DurationReport objects should be created passing 'title, NULL', so their 1246 // duration is logged into MYLOG instead. 1247 print_header(version); 1248 1249 // Dumps systrace right away, otherwise it will be filled with unnecessary events. 1250 dump_systrace(); 1251 1252 // Invoking the following dumpsys calls before dump_traces() to try and 1253 // keep the system stats as close to its initial state as possible. 1254 run_command_as_shell("DUMPSYS MEMINFO", 30, "dumpsys", "-t", "30", "meminfo", "-a", NULL); 1255 run_command_as_shell("DUMPSYS CPUINFO", 10, "dumpsys", "cpuinfo", "-a", NULL); 1256 1257 /* collect stack traces from Dalvik and native processes (needs root) */ 1258 dump_traces_path = dump_traces(); 1259 1260 /* Get the tombstone fds, recovery files, and mount info here while we are running as root. */ 1261 get_tombstone_fds(tombstone_data); 1262 add_dir(RECOVERY_DIR, true); 1263 add_dir(RECOVERY_DATA_DIR, true); 1264 add_mountinfo(); 1265 1266 if (!drop_root_user()) { 1267 return -1; 1268 } 1269 1270 dumpstate(do_early_screenshot ? "": screenshot_path, version); 1271 1272 /* close output if needed */ 1273 if (is_redirecting) { 1274 fclose(stdout); 1275 } 1276 1277 /* rename or zip the (now complete) .tmp file to its final location */ 1278 if (use_outfile) { 1279 1280 /* check if user changed the suffix using system properties */ 1281 char key[PROPERTY_KEY_MAX]; 1282 char value[PROPERTY_VALUE_MAX]; 1283 sprintf(key, "dumpstate.%d.name", getpid()); 1284 property_get(key, value, ""); 1285 bool change_suffix= false; 1286 if (value[0]) { 1287 /* must whitelist which characters are allowed, otherwise it could cross directories */ 1288 std::regex valid_regex("^[-_a-zA-Z0-9]+$"); 1289 if (std::regex_match(value, valid_regex)) { 1290 change_suffix = true; 1291 } else { 1292 MYLOGE("invalid suffix provided by user: %s\n", value); 1293 } 1294 } 1295 if (change_suffix) { 1296 MYLOGI("changing suffix from %s to %s\n", suffix.c_str(), value); 1297 suffix = value; 1298 if (!screenshot_path.empty()) { 1299 std::string new_screenshot_path = 1300 bugreport_dir + "/" + base_name + "-" + suffix + ".png"; 1301 if (rename(screenshot_path.c_str(), new_screenshot_path.c_str())) { 1302 MYLOGE("rename(%s, %s): %s\n", screenshot_path.c_str(), 1303 new_screenshot_path.c_str(), strerror(errno)); 1304 } else { 1305 screenshot_path = new_screenshot_path; 1306 } 1307 } 1308 } 1309 1310 bool do_text_file = true; 1311 if (do_zip_file) { 1312 std::string entry_name = base_name + "-" + suffix + ".txt"; 1313 MYLOGD("Adding main entry (%s) to .zip bugreport\n", entry_name.c_str()); 1314 if (!finish_zip_file(entry_name, tmp_path, now)) { 1315 MYLOGE("Failed to finish zip file; sending text bugreport instead\n"); 1316 do_text_file = true; 1317 } else { 1318 do_text_file = false; 1319 // Since zip file is already created, it needs to be renamed. 1320 std::string new_path = bugreport_dir + "/" + base_name + "-" + suffix + ".zip"; 1321 if (path != new_path) { 1322 MYLOGD("Renaming zip file from %s to %s\n", path.c_str(), new_path.c_str()); 1323 if (rename(path.c_str(), new_path.c_str())) { 1324 MYLOGE("rename(%s, %s): %s\n", path.c_str(), 1325 new_path.c_str(), strerror(errno)); 1326 } else { 1327 path = new_path; 1328 } 1329 } 1330 } 1331 } 1332 if (do_text_file) { 1333 path = bugreport_dir + "/" + base_name + "-" + suffix + ".txt"; 1334 MYLOGD("Generating .txt bugreport at %s from %s\n", path.c_str(), tmp_path.c_str()); 1335 if (rename(tmp_path.c_str(), path.c_str())) { 1336 MYLOGE("rename(%s, %s): %s\n", tmp_path.c_str(), path.c_str(), strerror(errno)); 1337 path.clear(); 1338 } 1339 } 1340 } 1341 1342 /* vibrate a few but shortly times to let user know it's finished */ 1343 if (vibrator) { 1344 for (int i = 0; i < 3; i++) { 1345 vibrate(vibrator.get(), 75); 1346 usleep((75 + 50) * 1000); 1347 } 1348 } 1349 1350 /* tell activity manager we're done */ 1351 if (do_broadcast) { 1352 if (!path.empty()) { 1353 MYLOGI("Final bugreport path: %s\n", path.c_str()); 1354 std::vector<std::string> am_args = { 1355 "--receiver-permission", "android.permission.DUMP", "--receiver-foreground", 1356 "--ei", "android.intent.extra.ID", std::to_string(id), 1357 "--ei", "android.intent.extra.PID", std::to_string(getpid()), 1358 "--ei", "android.intent.extra.MAX", std::to_string(weight_total), 1359 "--es", "android.intent.extra.BUGREPORT", path, 1360 "--es", "android.intent.extra.DUMPSTATE_LOG", log_path 1361 }; 1362 if (do_fb) { 1363 am_args.push_back("--es"); 1364 am_args.push_back("android.intent.extra.SCREENSHOT"); 1365 am_args.push_back(screenshot_path); 1366 } 1367 if (is_remote_mode) { 1368 am_args.push_back("--es"); 1369 am_args.push_back("android.intent.extra.REMOTE_BUGREPORT_HASH"); 1370 am_args.push_back(SHA256_file_hash(path)); 1371 send_broadcast("android.intent.action.REMOTE_BUGREPORT_FINISHED", am_args); 1372 } else { 1373 send_broadcast("android.intent.action.BUGREPORT_FINISHED", am_args); 1374 } 1375 } else { 1376 MYLOGE("Skipping finished broadcast because bugreport could not be generated\n"); 1377 } 1378 } 1379 1380 MYLOGD("Final progress: %d/%d (originally %d)\n", progress, weight_total, WEIGHT_TOTAL); 1381 MYLOGI("done\n"); 1382 1383 if (is_redirecting) { 1384 fclose(stderr); 1385 } 1386 1387 return 0; 1388} 1389