blob: 054db74f34bfb8367ab98831e8ff6c1f5fc454e0 [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
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
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -070017#include <dirent.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070018#include <errno.h>
19#include <fcntl.h>
Felipe Lemead5f6c42015-11-30 14:26:46 -080020#include <libgen.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070021#include <limits.h>
Felipe Leme6e01fa62015-11-11 19:35:14 -080022#include <memory>
Felipe Lemead5f6c42015-11-30 14:26:46 -080023#include <regex>
Felipe Leme635ca312016-01-05 14:23:02 -080024#include <set>
Mark Salyzyn8f37aa52015-06-12 12:28:24 -070025#include <stdbool.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070026#include <stdio.h>
27#include <stdlib.h>
Felipe Leme6e01fa62015-11-11 19:35:14 -080028#include <string>
Colin Crossf45fa6b2012-03-26 12:38:26 -070029#include <string.h>
Christopher Ferris7dc7f322014-07-22 16:08:19 -070030#include <sys/capability.h>
31#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/resource.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <sys/wait.h>
36#include <unistd.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070037
Elliott Hughes9dc117c2015-12-07 14:21:50 -080038#include <android-base/stringprintf.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070039#include <cutils/properties.h>
40
41#include "private/android_filesystem_config.h"
42
43#define LOG_TAG "dumpstate"
Alex Ray656a6b92013-07-23 13:44:34 -070044#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070045
46#include "dumpstate.h"
Felipe Leme6e01fa62015-11-11 19:35:14 -080047#include "ScopedFd.h"
48#include "ziparchive/zip_writer.h"
49
Michal Karpinski4db754f2015-12-11 18:04:32 +000050#include "mincrypt/sha256.h"
51
Felipe Leme6e01fa62015-11-11 19:35:14 -080052using android::base::StringPrintf;
Colin Crossf45fa6b2012-03-26 12:38:26 -070053
54/* read before root is shed */
55static char cmdline_buf[16384] = "(unknown)";
56static const char *dump_traces_path = NULL;
57
Felipe Lemee82a27d2016-01-05 13:35:44 -080058// TODO: should be part of dumpstate object
Felipe Leme78f2c862015-12-21 09:55:22 -080059static char build_type[PROPERTY_VALUE_MAX];
Felipe Lemee82a27d2016-01-05 13:35:44 -080060static time_t now;
61static std::unique_ptr<ZipWriter> zip_writer;
Felipe Leme635ca312016-01-05 14:23:02 -080062static std::set<std::string> mount_points;
63void add_mountinfo();
64static bool add_zip_entry(const std::string& entry_name, const std::string& entry_path);
Felipe Leme78f2c862015-12-21 09:55:22 -080065
Todd Poynor2a83daa2013-11-22 15:44:22 -080066#define PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops"
67
Sharvil Nanavati8d4cb7f2015-07-24 02:01:13 -070068#define RAFT_DIR "/data/misc/raft/"
Felipe Lemee82a27d2016-01-05 13:35:44 -080069#define RECOVERY_DIR "/cache/recovery"
Christopher Ferris7dc7f322014-07-22 16:08:19 -070070#define TOMBSTONE_DIR "/data/tombstones"
71#define TOMBSTONE_FILE_PREFIX TOMBSTONE_DIR "/tombstone_"
72/* Can accomodate a tombstone number up to 9999. */
73#define TOMBSTONE_MAX_LEN (sizeof(TOMBSTONE_FILE_PREFIX) + 4)
74#define NUM_TOMBSTONES 10
75
76typedef struct {
77 char name[TOMBSTONE_MAX_LEN];
78 int fd;
79} tombstone_data_t;
80
81static tombstone_data_t tombstone_data[NUM_TOMBSTONES];
82
Felipe Lemee82a27d2016-01-05 13:35:44 -080083// Root dir for all files copied as-is into the bugreport
84const std::string& ZIP_ROOT_DIR = "FS";
85
Felipe Leme809d74e2016-02-02 12:57:00 -080086/*
87 * List of supported zip format versions.
88 *
89 * See bugreport-format.txt for more info.
90 */
91// TODO: change to "v1" before final N build
92static std::string VERSION_DEFAULT = "v1-dev1";
93// TODO: remove before final N build
94static std::string VERSION_DUMPSYS_SPLIT = "v1-dev1-dumpsys-split";
95
Felipe Lemee82a27d2016-01-05 13:35:44 -080096/* 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. */
Christopher Ferris7dc7f322014-07-22 16:08:19 -070098static void get_tombstone_fds(tombstone_data_t data[NUM_TOMBSTONES]) {
Felipe Lemee82a27d2016-01-05 13:35:44 -080099 time_t thirty_minutes_ago = now - 60*30;
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700100 for (size_t i = 0; i < NUM_TOMBSTONES; i++) {
101 snprintf(data[i].name, sizeof(data[i].name), "%s%02zu", TOMBSTONE_FILE_PREFIX, i);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800102 int fd = TEMP_FAILURE_RETRY(open(data[i].name,
103 O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK));
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700104 struct stat st;
105 if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
Felipe Lemee82a27d2016-01-05 13:35:44 -0800106 (zip_writer || (time_t) st.st_mtime >= thirty_minutes_ago)) {
107 data[i].fd = fd;
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700108 } else {
Felipe Lemee82a27d2016-01-05 13:35:44 -0800109 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700110 data[i].fd = -1;
111 }
112 }
113}
114
Felipe Leme635ca312016-01-05 14:23:02 -0800115// 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 ALOGE("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 ALOGE("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();
Felipe Leme608385d2016-02-01 10:35:38 -0800145 DurationReporter duration_reporter(title, NULL);
Felipe Leme635ca312016-01-05 14:23:02 -0800146 for_each_pid(do_mountinfo, NULL);
Felipe Leme809d74e2016-02-02 12:57:00 -0800147 ALOGD("%s: %lu entries added to zip file\n", title, mount_points.size());
Felipe Leme635ca312016-01-05 14:23:02 -0800148}
149
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -0700150static 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
Mark Salyzyn326842f2015-04-30 09:49:41 -0700172static bool skip_not_stat(const char *path) {
173 static const char stat[] = "/stat";
174 size_t len = strlen(path);
175 if (path[len - 1] == '/') { /* Directory? */
176 return false;
177 }
178 return strcmp(path + len - sizeof(stat) + 1, stat); /* .../stat? */
179}
180
Felipe Lemee82a27d2016-01-05 13:35:44 -0800181static bool skip_none(const char *path) {
182 return false;
183}
184
Mark Salyzyn326842f2015-04-30 09:49:41 -0700185static const char mmcblk0[] = "/sys/block/mmcblk0/";
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700186unsigned long worst_write_perf = 20000; /* in KB/s */
Mark Salyzyn326842f2015-04-30 09:49:41 -0700187
188static int dump_stat_from_fd(const char *title __unused, const char *path, int fd) {
189 unsigned long fields[11], read_perf, write_perf;
190 bool z;
191 char *cp, *buffer = NULL;
192 size_t i = 0;
193 FILE *fp = fdopen(fd, "rb");
194 getline(&buffer, &i, fp);
195 fclose(fp);
196 if (!buffer) {
197 return -errno;
198 }
199 i = strlen(buffer);
200 while ((i > 0) && (buffer[i - 1] == '\n')) {
201 buffer[--i] = '\0';
202 }
203 if (!*buffer) {
204 free(buffer);
205 return 0;
206 }
207 z = true;
208 for (cp = buffer, i = 0; i < (sizeof(fields) / sizeof(fields[0])); ++i) {
209 fields[i] = strtol(cp, &cp, 0);
210 if (fields[i] != 0) {
211 z = false;
212 }
213 }
214 if (z) { /* never accessed */
215 free(buffer);
216 return 0;
217 }
218
219 if (!strncmp(path, mmcblk0, sizeof(mmcblk0) - 1)) {
220 path += sizeof(mmcblk0) - 1;
221 }
222
223 printf("%s: %s\n", path, buffer);
224 free(buffer);
225
226 read_perf = 0;
227 if (fields[3]) {
228 read_perf = 512 * fields[2] / fields[3];
229 }
230 write_perf = 0;
231 if (fields[7]) {
232 write_perf = 512 * fields[6] / fields[7];
233 }
234 printf("%s: read: %luKB/s write: %luKB/s\n", path, read_perf, write_perf);
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700235 if ((write_perf > 1) && (write_perf < worst_write_perf)) {
236 worst_write_perf = write_perf;
237 }
Mark Salyzyn326842f2015-04-30 09:49:41 -0700238 return 0;
239}
240
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700241/* Copied policy from system/core/logd/LogBuffer.cpp */
242
243#define LOG_BUFFER_SIZE (256 * 1024)
244#define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
245#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
246
247static bool valid_size(unsigned long value) {
248 if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
249 return false;
250 }
251
252 long pages = sysconf(_SC_PHYS_PAGES);
253 if (pages < 1) {
254 return true;
255 }
256
257 long pagesize = sysconf(_SC_PAGESIZE);
258 if (pagesize <= 1) {
259 pagesize = PAGE_SIZE;
260 }
261
262 // maximum memory impact a somewhat arbitrary ~3%
263 pages = (pages + 31) / 32;
264 unsigned long maximum = pages * pagesize;
265
266 if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
267 return true;
268 }
269
270 return value <= maximum;
271}
272
273static unsigned long property_get_size(const char *key) {
274 unsigned long value;
275 char *cp, property[PROPERTY_VALUE_MAX];
276
277 property_get(key, property, "");
278 value = strtoul(property, &cp, 10);
279
280 switch(*cp) {
281 case 'm':
282 case 'M':
283 value *= 1024;
284 /* FALLTHRU */
285 case 'k':
286 case 'K':
287 value *= 1024;
288 /* FALLTHRU */
289 case '\0':
290 break;
291
292 default:
293 value = 0;
294 }
295
296 if (!valid_size(value)) {
297 value = 0;
298 }
299
300 return value;
301}
302
303/* timeout in ms */
Felipe Leme8620bb42015-11-10 11:04:45 -0800304static unsigned long logcat_timeout(const char *name) {
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700305 static const char global_tuneable[] = "persist.logd.size"; // Settings App
306 static const char global_default[] = "ro.logd.size"; // BoardConfig.mk
307 char key[PROP_NAME_MAX];
308 unsigned long property_size, default_size;
309
310 default_size = property_get_size(global_tuneable);
311 if (!default_size) {
312 default_size = property_get_size(global_default);
313 }
314
315 snprintf(key, sizeof(key), "%s.%s", global_tuneable, name);
316 property_size = property_get_size(key);
317
318 if (!property_size) {
319 snprintf(key, sizeof(key), "%s.%s", global_default, name);
320 property_size = property_get_size(key);
321 }
322
323 if (!property_size) {
324 property_size = default_size;
325 }
326
327 if (!property_size) {
328 property_size = LOG_BUFFER_SIZE;
329 }
330
331 /* Engineering margin is ten-fold our guess */
332 return 10 * (property_size + worst_write_perf) / worst_write_perf;
333}
334
335/* End copy from system/core/logd/LogBuffer.cpp */
336
Colin Crossf45fa6b2012-03-26 12:38:26 -0700337/* dumps the current system state to stdout */
Felipe Leme809d74e2016-02-02 12:57:00 -0800338static void print_header(std::string version) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700339 char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX];
340 char radio[PROPERTY_VALUE_MAX], bootloader[PROPERTY_VALUE_MAX];
341 char network[PROPERTY_VALUE_MAX], date[80];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700342
343 property_get("ro.build.display.id", build, "(unknown)");
344 property_get("ro.build.fingerprint", fingerprint, "(unknown)");
345 property_get("ro.build.type", build_type, "(unknown)");
346 property_get("ro.baseband", radio, "(unknown)");
347 property_get("ro.bootloader", bootloader, "(unknown)");
348 property_get("gsm.operator.alpha", network, "(unknown)");
349 strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now));
350
351 printf("========================================================\n");
352 printf("== dumpstate: %s\n", date);
353 printf("========================================================\n");
354
355 printf("\n");
356 printf("Build: %s\n", build);
357 printf("Build fingerprint: '%s'\n", fingerprint); /* format is important for other tools */
358 printf("Bootloader: %s\n", bootloader);
359 printf("Radio: %s\n", radio);
360 printf("Network: %s\n", network);
361
362 printf("Kernel: ");
363 dump_file(NULL, "/proc/version");
364 printf("Command line: %s\n", strtok(cmdline_buf, "\n"));
Felipe Leme809d74e2016-02-02 12:57:00 -0800365 printf("Bugreport format version: %s\n", version.c_str());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700366 printf("\n");
Felipe Leme78f2c862015-12-21 09:55:22 -0800367}
368
Felipe Lemee82a27d2016-01-05 13:35:44 -0800369/* adds a new entry to the existing zip file. */
370static bool add_zip_entry_from_fd(const std::string& entry_name, int fd) {
Felipe Leme770410d2016-01-26 17:07:14 -0800371 ALOGD("Adding zip entry %s", entry_name.c_str());
Felipe Lemee82a27d2016-01-05 13:35:44 -0800372 int32_t err = zip_writer->StartEntryWithTime(entry_name.c_str(),
373 ZipWriter::kCompress, get_mtime(fd, now));
374 if (err) {
Felipe Leme809d74e2016-02-02 12:57:00 -0800375 ALOGE("zip_writer->StartEntryWithTime(%s): %s\n", entry_name.c_str(),
376 ZipWriter::ErrorCodeString(err));
Felipe Lemee82a27d2016-01-05 13:35:44 -0800377 return false;
378 }
379
Felipe Leme770410d2016-01-26 17:07:14 -0800380 std::vector<uint8_t> buffer(65536);
Felipe Lemee82a27d2016-01-05 13:35:44 -0800381 while (1) {
Felipe Lemee82a27d2016-01-05 13:35:44 -0800382 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), sizeof(buffer)));
383 if (bytes_read == 0) {
384 break;
385 } else if (bytes_read == -1) {
386 ALOGE("read(%s): %s\n", entry_name.c_str(), strerror(errno));
387 return false;
388 }
389 err = zip_writer->WriteBytes(buffer.data(), bytes_read);
390 if (err) {
391 ALOGE("zip_writer->WriteBytes(): %s\n", ZipWriter::ErrorCodeString(err));
392 return false;
393 }
394 }
395
396 err = zip_writer->FinishEntry();
397 if (err) {
398 ALOGE("zip_writer->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err));
399 return false;
400 }
401
402 return true;
403}
404
405/* adds a new entry to the existing zip file. */
406static bool add_zip_entry(const std::string& entry_name, const std::string& entry_path) {
407 ScopedFd fd(TEMP_FAILURE_RETRY(open(entry_path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
408 if (fd.get() == -1) {
409 ALOGE("open(%s): %s\n", entry_path.c_str(), strerror(errno));
410 return false;
411 }
412
413 return add_zip_entry_from_fd(entry_name, fd.get());
414}
415
416/* adds a file to the existing zipped bugreport */
417static int _add_file_from_fd(const char *title, const char *path, int fd) {
418 return add_zip_entry_from_fd(ZIP_ROOT_DIR + path, fd) ? 0 : 1;
419}
420
421/* adds all files from a directory to the zipped bugreport file */
422void add_dir(const char *dir, bool recursive) {
423 if (!zip_writer) return;
Felipe Leme608385d2016-02-01 10:35:38 -0800424 DurationReporter duration_reporter(dir, NULL);
Felipe Lemee82a27d2016-01-05 13:35:44 -0800425 dump_files(NULL, dir, recursive ? skip_none : is_dir, _add_file_from_fd);
426}
427
Felipe Leme809d74e2016-02-02 12:57:00 -0800428/* adds a text entry entry to the existing zip file. */
429static bool add_text_zip_entry(const std::string& entry_name, const std::string& content) {
430 ALOGD("Adding zip text entry %s (%s)", entry_name.c_str(), content.c_str());
431 int32_t err = zip_writer->StartEntryWithTime(entry_name.c_str(), ZipWriter::kCompress, now);
432 if (err) {
433 ALOGE("zip_writer->StartEntryWithTime(%s): %s\n", entry_name.c_str(),
434 ZipWriter::ErrorCodeString(err));
435 return false;
436 }
437
438 err = zip_writer->WriteBytes(content.c_str(), content.length());
439 if (err) {
440 ALOGE("zip_writer->WriteBytes(%s): %s\n", entry_name.c_str(),
441 ZipWriter::ErrorCodeString(err));
442 return false;
443 }
444
445 err = zip_writer->FinishEntry();
446 if (err) {
447 ALOGE("zip_writer->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err));
448 return false;
449 }
450
451 return true;
452}
453
Felipe Leme78f2c862015-12-21 09:55:22 -0800454static void dumpstate(const std::string& screenshot_path) {
Felipe Leme770410d2016-01-26 17:07:14 -0800455 DurationReporter duration_reporter("DUMPSTATE");
Felipe Leme78f2c862015-12-21 09:55:22 -0800456 unsigned long timeout;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700457
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -0700458 dump_dev_files("TRUSTY VERSION", "/sys/bus/platform/drivers/trusty", "trusty_version");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700459 run_command("UPTIME", 10, "uptime", NULL);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700460 dump_files("UPTIME MMC PERF", mmcblk0, skip_not_stat, dump_stat_from_fd);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800461 dump_emmc_ecsd("/d/mmc0/mmc0:0001/ext_csd");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700462 dump_file("MEMORY INFO", "/proc/meminfo");
Elliott Hughesb32c7e12015-11-13 11:32:48 -0800463 run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-H", NULL);
Nick Kralevich2b1f88b2015-10-07 16:38:42 -0700464 run_command("PROCRANK", 20, SU_PATH, "root", "procrank", NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700465 dump_file("VIRTUAL MEMORY STATS", "/proc/vmstat");
466 dump_file("VMALLOC INFO", "/proc/vmallocinfo");
467 dump_file("SLAB INFO", "/proc/slabinfo");
468 dump_file("ZONEINFO", "/proc/zoneinfo");
469 dump_file("PAGETYPEINFO", "/proc/pagetypeinfo");
470 dump_file("BUDDYINFO", "/proc/buddyinfo");
Colin Cross2281af92012-10-28 22:41:06 -0700471 dump_file("FRAGMENTATION INFO", "/d/extfrag/unusable_index");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700472
Colin Crossf45fa6b2012-03-26 12:38:26 -0700473 dump_file("KERNEL WAKELOCKS", "/proc/wakelocks");
Todd Poynor29e27a82012-05-22 17:54:59 -0700474 dump_file("KERNEL WAKE SOURCES", "/d/wakeup_sources");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700475 dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
Mathias Agopian85aea742012-08-08 15:32:02 -0700476 dump_file("KERNEL SYNC", "/d/sync");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700477
Elliott Hughesa3533a32015-10-30 16:17:49 -0700478 run_command("PROCESSES AND THREADS", 10, "ps", "-Z", "-t", "-p", "-P", NULL);
Nick Kralevichb82c9252015-11-27 17:56:13 -0800479 run_command("LIBRANK", 10, SU_PATH, "root", "librank", NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700480
Michal Karpinski4db754f2015-12-11 18:04:32 +0000481 run_command("ROUTE", 10, "route", NULL);
482 run_command("PRINTENV", 10, "printenv", NULL);
483 run_command("NETSTAT", 10, "netstat", NULL);
484 run_command("LSMOD", 10, "lsmod", NULL);
485
Colin Crossf45fa6b2012-03-26 12:38:26 -0700486 do_dmesg();
487
488 run_command("LIST OF OPEN FILES", 10, SU_PATH, "root", "lsof", NULL);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700489 for_each_pid(do_showmap, "SMAPS OF ALL PROCESSES");
490 for_each_tid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700491
Felipe Leme6e01fa62015-11-11 19:35:14 -0800492 if (!screenshot_path.empty()) {
Felipe Lemee338bf62015-12-07 14:03:50 -0800493 ALOGI("taking late screenshot\n");
494 take_screenshot(screenshot_path);
Felipe Leme6e01fa62015-11-11 19:35:14 -0800495 ALOGI("wrote screenshot: %s\n", screenshot_path.c_str());
Jeff Sharkey5a930032013-03-19 15:05:19 -0700496 }
497
Colin Crossf45fa6b2012-03-26 12:38:26 -0700498 // dump_file("EVENT LOG TAGS", "/etc/event-log-tags");
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700499 // calculate timeout
500 timeout = logcat_timeout("main") + logcat_timeout("system") + logcat_timeout("crash");
501 if (timeout < 20000) {
502 timeout = 20000;
503 }
Mark Salyzyn78316382015-10-09 14:02:07 -0700504 run_command("SYSTEM LOG", timeout / 1000, "logcat", "-v", "threadtime",
505 "-v", "printable",
506 "-d",
507 "*:v", NULL);
Mark Salyzyn43afe5d2016-01-26 07:24:08 -0800508 timeout = logcat_timeout("events");
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700509 if (timeout < 20000) {
510 timeout = 20000;
511 }
Mark Salyzyn78316382015-10-09 14:02:07 -0700512 run_command("EVENT LOG", timeout / 1000, "logcat", "-b", "events",
513 "-v", "threadtime",
514 "-v", "printable",
515 "-d",
516 "*:v", NULL);
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700517 timeout = logcat_timeout("radio");
518 if (timeout < 20000) {
519 timeout = 20000;
520 }
Mark Salyzyn78316382015-10-09 14:02:07 -0700521 run_command("RADIO LOG", timeout / 1000, "logcat", "-b", "radio",
522 "-v", "threadtime",
523 "-v", "printable",
524 "-d",
525 "*:v", NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700526
Mark Salyzynecc07632015-07-30 14:57:09 -0700527 run_command("LOG STATISTICS", 10, "logcat", "-b", "all", "-S", NULL);
528
Sharvil Nanavati804339a2015-11-27 21:04:11 -0800529 run_command("RAFT LOGS", 600, SU_PATH, "root", "logcompressor", "-r", RAFT_DIR, NULL);
Sharvil Nanavati8d4cb7f2015-07-24 02:01:13 -0700530
Colin Crossf45fa6b2012-03-26 12:38:26 -0700531 /* show the traces we collected in main(), if that was done */
532 if (dump_traces_path != NULL) {
533 dump_file("VM TRACES JUST NOW", dump_traces_path);
534 }
535
536 /* only show ANR traces if they're less than 15 minutes old */
537 struct stat st;
538 char anr_traces_path[PATH_MAX];
539 property_get("dalvik.vm.stack-trace-file", anr_traces_path, "");
540 if (!anr_traces_path[0]) {
541 printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700542 } else {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800543 int fd = TEMP_FAILURE_RETRY(open(anr_traces_path,
544 O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK));
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700545 if (fd < 0) {
546 printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_path, strerror(errno));
547 } else {
548 dump_file_from_fd("VM TRACES AT LAST ANR", anr_traces_path, fd);
549 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700550 }
551
552 /* slow traces for slow operations */
553 if (anr_traces_path[0] != 0) {
554 int tail = strlen(anr_traces_path)-1;
555 while (tail > 0 && anr_traces_path[tail] != '/') {
556 tail--;
557 }
558 int i = 0;
559 while (1) {
560 sprintf(anr_traces_path+tail+1, "slow%02d.txt", i);
561 if (stat(anr_traces_path, &st)) {
562 // No traces file at this index, done with the files.
563 break;
564 }
565 dump_file("VM TRACES WHEN SLOW", anr_traces_path);
566 i++;
567 }
568 }
569
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700570 int dumped = 0;
571 for (size_t i = 0; i < NUM_TOMBSTONES; i++) {
572 if (tombstone_data[i].fd != -1) {
Felipe Lemee82a27d2016-01-05 13:35:44 -0800573 const char *name = tombstone_data[i].name;
574 int fd = tombstone_data[i].fd;
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700575 dumped = 1;
Felipe Lemee82a27d2016-01-05 13:35:44 -0800576 if (zip_writer) {
577 if (!add_zip_entry_from_fd(ZIP_ROOT_DIR + name, fd)) {
578 ALOGE("Unable to add tombstone %s to zip file\n", name);
579 }
580 } else {
581 dump_file_from_fd("TOMBSTONE", name, fd);
582 }
583 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700584 tombstone_data[i].fd = -1;
585 }
586 }
587 if (!dumped) {
588 printf("*** NO TOMBSTONES to dump in %s\n\n", TOMBSTONE_DIR);
589 }
590
Colin Crossf45fa6b2012-03-26 12:38:26 -0700591 dump_file("NETWORK DEV INFO", "/proc/net/dev");
592 dump_file("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all");
JP Abgrall012c2ea2012-05-16 20:49:29 -0700593 dump_file("QTAGUID NETWORK INTERFACES INFO (xt)", "/proc/net/xt_qtaguid/iface_stat_fmt");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700594 dump_file("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl");
595 dump_file("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats");
596
Todd Poynor2a83daa2013-11-22 15:44:22 -0800597 if (!stat(PSTORE_LAST_KMSG, &st)) {
598 /* Also TODO: Make console-ramoops CAP_SYSLOG protected. */
599 dump_file("LAST KMSG", PSTORE_LAST_KMSG);
600 } else {
601 /* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */
602 dump_file("LAST KMSG", "/proc/last_kmsg");
603 }
604
Mark Salyzyn2262c162014-12-16 09:09:26 -0800605 /* kernels must set CONFIG_PSTORE_PMSG, slice up pstore with device tree */
Mark Salyzyn78316382015-10-09 14:02:07 -0700606 run_command("LAST LOGCAT", 10, "logcat", "-L",
607 "-b", "all",
608 "-v", "threadtime",
609 "-v", "printable",
610 "-d",
611 "*:v", NULL);
Mark Salyzyn2262c162014-12-16 09:09:26 -0800612
Colin Crossf45fa6b2012-03-26 12:38:26 -0700613 /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */
Elliott Hughesa59828a2015-01-27 20:48:52 -0800614
615 run_command("NETWORK INTERFACES", 10, "ip", "link", NULL);
Lorenzo Colittid4c3d382014-07-30 14:38:20 +0900616
617 run_command("IPv4 ADDRESSES", 10, "ip", "-4", "addr", "show", NULL);
618 run_command("IPv6 ADDRESSES", 10, "ip", "-6", "addr", "show", NULL);
619
Colin Crossf45fa6b2012-03-26 12:38:26 -0700620 run_command("IP RULES", 10, "ip", "rule", "show", NULL);
621 run_command("IP RULES v6", 10, "ip", "-6", "rule", "show", NULL);
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700622
623 dump_route_tables();
624
Lorenzo Colittid4c3d382014-07-30 14:38:20 +0900625 run_command("ARP CACHE", 10, "ip", "-4", "neigh", "show", NULL);
626 run_command("IPv6 ND CACHE", 10, "ip", "-6", "neigh", "show", NULL);
627
Colin Crossf45fa6b2012-03-26 12:38:26 -0700628 run_command("IPTABLES", 10, SU_PATH, "root", "iptables", "-L", "-nvx", NULL);
629 run_command("IP6TABLES", 10, SU_PATH, "root", "ip6tables", "-L", "-nvx", NULL);
JP Abgrall012c2ea2012-05-16 20:49:29 -0700630 run_command("IPTABLE NAT", 10, SU_PATH, "root", "iptables", "-t", "nat", "-L", "-nvx", NULL);
631 /* no ip6 nat */
632 run_command("IPTABLE RAW", 10, SU_PATH, "root", "iptables", "-t", "raw", "-L", "-nvx", NULL);
633 run_command("IP6TABLE RAW", 10, SU_PATH, "root", "ip6tables", "-t", "raw", "-L", "-nvx", NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700634
635 run_command("WIFI NETWORKS", 20,
Dmitry Shmidt1d6b97c2013-08-21 10:58:29 -0700636 SU_PATH, "root", "wpa_cli", "IFNAME=wlan0", "list_networks", NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700637
Dmitry Shmidtc11f56e2012-11-07 10:42:05 -0800638#ifdef FWDUMP_bcmdhd
Lorenzo Colitti6afc38c2015-09-09 22:59:25 +0900639 run_command("ND OFFLOAD TABLE", 5,
640 SU_PATH, "root", "wlutil", "nd_hostip", NULL);
641
642 run_command("DUMP WIFI INTERNAL COUNTERS (1)", 20,
Dmitry Shmidtc11f56e2012-11-07 10:42:05 -0800643 SU_PATH, "root", "wlutil", "counters", NULL);
Lorenzo Colitti6afc38c2015-09-09 22:59:25 +0900644
645 run_command("ND OFFLOAD STATUS (1)", 5,
646 SU_PATH, "root", "wlutil", "nd_status", NULL);
647
Dmitry Shmidtc11f56e2012-11-07 10:42:05 -0800648#endif
Dmitry Shmidt0b2c9262012-11-07 11:09:46 -0800649 dump_file("INTERRUPTS (1)", "/proc/interrupts");
650
Lorenzo Colitti6afc38c2015-09-09 22:59:25 +0900651 run_command("NETWORK DIAGNOSTICS", 10, "dumpsys", "connectivity", "--diag", NULL);
652
Dmitry Shmidtc11f56e2012-11-07 10:42:05 -0800653#ifdef FWDUMP_bcmdhd
Colin Crossf45fa6b2012-03-26 12:38:26 -0700654 run_command("DUMP WIFI STATUS", 20,
655 SU_PATH, "root", "dhdutil", "-i", "wlan0", "dump", NULL);
Lorenzo Colitti6afc38c2015-09-09 22:59:25 +0900656
657 run_command("DUMP WIFI INTERNAL COUNTERS (2)", 20,
Colin Crossf45fa6b2012-03-26 12:38:26 -0700658 SU_PATH, "root", "wlutil", "counters", NULL);
Lorenzo Colitti6afc38c2015-09-09 22:59:25 +0900659
660 run_command("ND OFFLOAD STATUS (2)", 5,
661 SU_PATH, "root", "wlutil", "nd_status", NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700662#endif
Dmitry Shmidt0b2c9262012-11-07 11:09:46 -0800663 dump_file("INTERRUPTS (2)", "/proc/interrupts");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700664
665 print_properties();
666
667 run_command("VOLD DUMP", 10, "vdc", "dump", NULL);
668 run_command("SECURE CONTAINERS", 10, "vdc", "asec", "list", NULL);
669
Ken Sumrall8f75fa72013-02-08 17:35:58 -0800670 run_command("FILESYSTEMS & FREE SPACE", 10, "df", NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700671
Colin Crossf45fa6b2012-03-26 12:38:26 -0700672 run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL);
673
674 printf("------ BACKLIGHTS ------\n");
675 printf("LCD brightness=");
676 dump_file(NULL, "/sys/class/leds/lcd-backlight/brightness");
677 printf("Button brightness=");
678 dump_file(NULL, "/sys/class/leds/button-backlight/brightness");
679 printf("Keyboard brightness=");
680 dump_file(NULL, "/sys/class/leds/keyboard-backlight/brightness");
681 printf("ALS mode=");
682 dump_file(NULL, "/sys/class/leds/lcd-backlight/als");
683 printf("LCD driver registers:\n");
684 dump_file(NULL, "/sys/class/leds/lcd-backlight/registers");
685 printf("\n");
686
687 /* Binder state is expensive to look at as it uses a lot of memory. */
688 dump_file("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log");
689 dump_file("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log");
690 dump_file("BINDER TRANSACTIONS", "/sys/kernel/debug/binder/transactions");
691 dump_file("BINDER STATS", "/sys/kernel/debug/binder/stats");
692 dump_file("BINDER STATE", "/sys/kernel/debug/binder/state");
693
Colin Crossf45fa6b2012-03-26 12:38:26 -0700694 printf("========================================================\n");
695 printf("== Board\n");
696 printf("========================================================\n");
697
698 dumpstate_board();
699 printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700700
701 /* Migrate the ril_dumpstate to a dumpstate_board()? */
702 char ril_dumpstate_timeout[PROPERTY_VALUE_MAX] = {0};
703 property_get("ril.dumpstate.timeout", ril_dumpstate_timeout, "30");
704 if (strnlen(ril_dumpstate_timeout, PROPERTY_VALUE_MAX - 1) > 0) {
705 if (0 == strncmp(build_type, "user", PROPERTY_VALUE_MAX - 1)) {
706 // su does not exist on user builds, so try running without it.
707 // This way any implementations of vril-dump that do not require
708 // root can run on user builds.
709 run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
710 "vril-dump", NULL);
711 } else {
712 run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
713 SU_PATH, "root", "vril-dump", NULL);
714 }
715 }
716
717 printf("========================================================\n");
718 printf("== Android Framework Services\n");
719 printf("========================================================\n");
720
721 /* the full dumpsys is starting to take a long time, so we need
722 to increase its timeout. we really need to do the timeouts in
723 dumpsys itself... */
724 run_command("DUMPSYS", 60, "dumpsys", NULL);
725
726 printf("========================================================\n");
Dianne Hackborn02bea972013-06-26 18:59:09 -0700727 printf("== Checkins\n");
728 printf("========================================================\n");
729
Dianne Hackborn59b15162013-09-04 18:04:14 -0700730 run_command("CHECKIN BATTERYSTATS", 30, "dumpsys", "batterystats", "-c", NULL);
Dianne Hackborn3e5fa732013-07-03 16:51:15 -0700731 run_command("CHECKIN MEMINFO", 30, "dumpsys", "meminfo", "--checkin", NULL);
Dianne Hackborn02bea972013-06-26 18:59:09 -0700732 run_command("CHECKIN NETSTATS", 30, "dumpsys", "netstats", "--checkin", NULL);
Dianne Hackborn5cd46aa2013-07-09 15:01:40 -0700733 run_command("CHECKIN PROCSTATS", 30, "dumpsys", "procstats", "-c", NULL);
Dianne Hackborn1bd50682013-07-11 11:45:18 -0700734 run_command("CHECKIN USAGESTATS", 30, "dumpsys", "usagestats", "-c", NULL);
Ashish Sharma8b3e1332015-04-28 13:32:54 -0700735 run_command("CHECKIN PACKAGE", 30, "dumpsys", "package", "--checkin", NULL);
Dianne Hackborn02bea972013-06-26 18:59:09 -0700736
737 printf("========================================================\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700738 printf("== Running Application Activities\n");
739 printf("========================================================\n");
740
741 run_command("APP ACTIVITIES", 30, "dumpsys", "activity", "all", NULL);
742
743 printf("========================================================\n");
744 printf("== Running Application Services\n");
745 printf("========================================================\n");
746
747 run_command("APP SERVICES", 30, "dumpsys", "activity", "service", "all", NULL);
748
749 printf("========================================================\n");
750 printf("== Running Application Providers\n");
751 printf("========================================================\n");
752
753 run_command("APP SERVICES", 30, "dumpsys", "activity", "provider", "all", NULL);
754
755
756 printf("========================================================\n");
Felipe Leme608385d2016-02-01 10:35:38 -0800757 printf("== Final progress (pid %d): %d/%d (originally %d)\n",
758 getpid(), progress, weight_total, WEIGHT_TOTAL);
759 printf("========================================================\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700760 printf("== dumpstate: done\n");
761 printf("========================================================\n");
762}
763
764static void usage() {
Felipe Leme809d74e2016-02-02 12:57:00 -0800765 fprintf(stderr, "usage: dumpstate [-b soundfile] [-e soundfile] [-o file [-d] [-p] [-z]] [-s] [-q] [-B] [-P] [-R] [-V version]\n"
Colin Crossf45fa6b2012-03-26 12:38:26 -0700766 " -b: play sound file instead of vibrate, at beginning of job\n"
767 " -e: play sound file instead of vibrate, at end of job\n"
Felipe Leme809d74e2016-02-02 12:57:00 -0800768 " -o: write to file (instead of stdout)\n"
769 " -d: append date to filename (requires -o)\n"
770 " -p: capture screenshot to filename.png (requires -o)\n"
771 " -z: generates zipped file (requires -o)\n"
772 " -s: write output to control socket (for init)\n"
John Michelau1f794c42012-09-17 11:20:19 -0500773 " -q: disable vibrate\n"
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800774 " -B: send broadcast when finished (requires -o)\n"
Felipe Leme71bbfc52015-11-23 14:14:51 -0800775 " -P: send broadacast when started and update system properties on progress (requires -o and -B)\n"
Michal Karpinski4db754f2015-12-11 18:04:32 +0000776 " -R: take bugreport in remote mode (requires -o, -z, -d and -B, shouldn't be used with -P)\n"
Felipe Leme809d74e2016-02-02 12:57:00 -0800777 " -V: sets the bugreport format version (%s or %s)\n",
778 VERSION_DEFAULT.c_str(), VERSION_DUMPSYS_SPLIT.c_str());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700779}
780
John Michelau885f8882013-05-06 16:42:02 -0500781static void sigpipe_handler(int n) {
Andres Morales2e671bb2014-08-21 12:38:22 -0700782 // don't complain to stderr or stdout
783 _exit(EXIT_FAILURE);
John Michelau885f8882013-05-06 16:42:02 -0500784}
785
Felipe Leme1e9edc62015-12-21 16:02:13 -0800786/* adds the temporary report to the existing .zip file, closes the .zip file, and removes the
787 temporary file.
788 */
Felipe Lemee82a27d2016-01-05 13:35:44 -0800789static bool finish_zip_file(const std::string& bugreport_name, const std::string& bugreport_path,
Felipe Leme1e9edc62015-12-21 16:02:13 -0800790 time_t now) {
Felipe Lemee82a27d2016-01-05 13:35:44 -0800791 if (!add_zip_entry(bugreport_name, bugreport_path)) {
Felipe Leme1e9edc62015-12-21 16:02:13 -0800792 ALOGE("Failed to add text entry to .zip file\n");
793 return false;
794 }
Felipe Leme809d74e2016-02-02 12:57:00 -0800795 if (!add_text_zip_entry("main_entry.txt", bugreport_name)) {
796 ALOGE("Failed to add main_entry.txt to .zip file\n");
797 }
Felipe Leme1e9edc62015-12-21 16:02:13 -0800798
Felipe Lemee82a27d2016-01-05 13:35:44 -0800799 int32_t err = zip_writer->Finish();
Felipe Leme1e9edc62015-12-21 16:02:13 -0800800 if (err) {
Felipe Lemee82a27d2016-01-05 13:35:44 -0800801 ALOGE("zip_writer->Finish(): %s\n", ZipWriter::ErrorCodeString(err));
Felipe Leme1e9edc62015-12-21 16:02:13 -0800802 return false;
803 }
804
805 if (remove(bugreport_path.c_str())) {
806 ALOGW("remove(%s): %s\n", bugreport_path.c_str(), strerror(errno));
807 }
808
809 return true;
810}
Felipe Leme6e01fa62015-11-11 19:35:14 -0800811
Michal Karpinski4db754f2015-12-11 18:04:32 +0000812static std::string SHA256_file_hash(std::string filepath) {
Michal Karpinskicbbdf732016-01-07 20:45:02 +0000813 ScopedFd fd(TEMP_FAILURE_RETRY(open(filepath.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC
814 | O_NOFOLLOW)));
Michal Karpinski4db754f2015-12-11 18:04:32 +0000815 if (fd.get() == -1) {
816 ALOGE("open(%s): %s\n", filepath.c_str(), strerror(errno));
817 return NULL;
818 }
819
820 SHA256_CTX ctx;
821 SHA256_init(&ctx);
822
823 std::vector<uint8_t> buffer(65536);
824 while (1) {
825 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd.get(), buffer.data(), buffer.size()));
826 if (bytes_read == 0) {
827 break;
828 } else if (bytes_read == -1) {
829 ALOGE("read(%s): %s\n", filepath.c_str(), strerror(errno));
830 return NULL;
831 }
832
833 SHA256_update(&ctx, buffer.data(), bytes_read);
834 }
835
836 uint8_t hash[SHA256_DIGEST_SIZE];
837 memcpy(hash, SHA256_final(&ctx), SHA256_DIGEST_SIZE);
838 char hash_buffer[SHA256_DIGEST_SIZE * 2 + 1];
Michal Karpinskicbbdf732016-01-07 20:45:02 +0000839 for(size_t i = 0; i < SHA256_DIGEST_SIZE; i++) {
840 sprintf(hash_buffer + (i * 2), "%02x", hash[i]);
Michal Karpinski4db754f2015-12-11 18:04:32 +0000841 }
842 hash_buffer[sizeof(hash_buffer) - 1] = 0;
843 return std::string(hash_buffer);
844}
845
Felipe Leme608385d2016-02-01 10:35:38 -0800846/* switch to non-root user and group */
847bool drop_root() {
848 /* ensure we will keep capabilities when we drop root */
849 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
850 ALOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
851 return false;
852 }
853
854 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
855 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC };
856 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
857 ALOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
858 return false;
859 }
860 if (setgid(AID_SHELL) != 0) {
861 ALOGE("Unable to setgid, aborting: %s\n", strerror(errno));
862 return false;
863 }
864 if (setuid(AID_SHELL) != 0) {
865 ALOGE("Unable to setuid, aborting: %s\n", strerror(errno));
866 return false;
867 }
868
869 struct __user_cap_header_struct capheader;
870 struct __user_cap_data_struct capdata[2];
871 memset(&capheader, 0, sizeof(capheader));
872 memset(&capdata, 0, sizeof(capdata));
873 capheader.version = _LINUX_CAPABILITY_VERSION_3;
874 capheader.pid = 0;
875
876 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
877 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
878 capdata[0].inheritable = 0;
879 capdata[1].inheritable = 0;
880
881 if (capset(&capheader, &capdata[0]) < 0) {
882 ALOGE("capset failed: %s\n", strerror(errno));
883 return false;
884 }
885
886 return true;
887}
Michal Karpinski4db754f2015-12-11 18:04:32 +0000888
Colin Crossf45fa6b2012-03-26 12:38:26 -0700889int main(int argc, char *argv[]) {
John Michelau885f8882013-05-06 16:42:02 -0500890 struct sigaction sigact;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700891 int do_add_date = 0;
Felipe Leme6e01fa62015-11-11 19:35:14 -0800892 int do_zip_file = 0;
John Michelau1f794c42012-09-17 11:20:19 -0500893 int do_vibrate = 1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700894 char* use_outfile = 0;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700895 int use_socket = 0;
896 int do_fb = 0;
Jeff Sharkey27f9e6d2013-03-13 15:45:50 -0700897 int do_broadcast = 0;
Felipe Lemee338bf62015-12-07 14:03:50 -0800898 int do_early_screenshot = 0;
Michal Karpinski4db754f2015-12-11 18:04:32 +0000899 int is_remote_mode = 0;
Felipe Leme809d74e2016-02-02 12:57:00 -0800900 std::string version = VERSION_DEFAULT;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700901
Felipe Lemee82a27d2016-01-05 13:35:44 -0800902 now = time(NULL);
903
Nick Kralevich1e339872012-04-25 13:38:45 -0700904 if (getuid() != 0) {
905 // Old versions of the adb client would call the
906 // dumpstate command directly. Newer clients
907 // call /system/bin/bugreport instead. If we detect
908 // we're being called incorrectly, then exec the
909 // correct program.
910 return execl("/system/bin/bugreport", "/system/bin/bugreport", NULL);
911 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700912
Colin Crossf45fa6b2012-03-26 12:38:26 -0700913 ALOGI("begin\n");
914
Jeff Brown1dc94e32014-09-11 14:15:27 -0700915 /* clear SIGPIPE handler */
John Michelau885f8882013-05-06 16:42:02 -0500916 memset(&sigact, 0, sizeof(sigact));
917 sigact.sa_handler = sigpipe_handler;
918 sigaction(SIGPIPE, &sigact, NULL);
JP Abgrall3e03d3f2012-05-11 14:14:09 -0700919
Colin Crossf45fa6b2012-03-26 12:38:26 -0700920 /* set as high priority, and protect from OOM killer */
921 setpriority(PRIO_PROCESS, 0, -20);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700922 FILE *oom_adj = fopen("/proc/self/oom_adj", "we");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700923 if (oom_adj) {
924 fputs("-17", oom_adj);
925 fclose(oom_adj);
926 }
927
Jeff Brown1dc94e32014-09-11 14:15:27 -0700928 /* parse arguments */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700929 int c;
Felipe Leme809d74e2016-02-02 12:57:00 -0800930 while ((c = getopt(argc, argv, "dho:svqzpPBRV:")) != -1) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700931 switch (c) {
Felipe Leme71bbfc52015-11-23 14:14:51 -0800932 case 'd': do_add_date = 1; break;
933 case 'z': do_zip_file = 1; break;
934 case 'o': use_outfile = optarg; break;
935 case 's': use_socket = 1; break;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700936 case 'v': break; // compatibility no-op
Felipe Leme71bbfc52015-11-23 14:14:51 -0800937 case 'q': do_vibrate = 0; break;
938 case 'p': do_fb = 1; break;
939 case 'P': do_update_progress = 1; break;
Michal Karpinski4db754f2015-12-11 18:04:32 +0000940 case 'R': is_remote_mode = 1; break;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800941 case 'B': do_broadcast = 1; break;
Felipe Leme809d74e2016-02-02 12:57:00 -0800942 case 'V': version = optarg; break;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700943 case '?': printf("\n");
944 case 'h':
945 usage();
946 exit(1);
947 }
948 }
949
Felipe Leme71bbfc52015-11-23 14:14:51 -0800950 if ((do_zip_file || do_add_date || do_update_progress || do_broadcast) && !use_outfile) {
Felipe Leme6e01fa62015-11-11 19:35:14 -0800951 usage();
952 exit(1);
953 }
954
Felipe Leme71bbfc52015-11-23 14:14:51 -0800955 if (do_update_progress && !do_broadcast) {
956 usage();
957 exit(1);
958 }
Felipe Leme6e01fa62015-11-11 19:35:14 -0800959
Michal Karpinski4db754f2015-12-11 18:04:32 +0000960 if (is_remote_mode && (do_update_progress || !do_broadcast || !do_zip_file || !do_add_date)) {
961 usage();
962 exit(1);
963 }
964
Felipe Leme809d74e2016-02-02 12:57:00 -0800965 if (version != VERSION_DEFAULT && version != VERSION_DUMPSYS_SPLIT) {
966 usage();
967 exit(1);
968 }
969
970 ALOGI("bugreport format version: %s\n", version.c_str());
971
Felipe Lemee338bf62015-12-07 14:03:50 -0800972 do_early_screenshot = do_update_progress;
973
Christopher Ferrised9354f2014-10-01 17:35:01 -0700974 // If we are going to use a socket, do it as early as possible
975 // to avoid timeouts from bugreport.
976 if (use_socket) {
977 redirect_to_socket(stdout, "dumpstate");
978 }
979
Felipe Lemead5f6c42015-11-30 14:26:46 -0800980 /* full path of the directory where the bug report files will be written */
981 std::string bugreport_dir;
982
983 /* full path of the temporary file containing the bug report */
984 std::string tmp_path;
985
Felipe Lemee338bf62015-12-07 14:03:50 -0800986 /* full path of the temporary file containing the screenshot (when requested) */
987 std::string screenshot_path;
988
Felipe Lemead5f6c42015-11-30 14:26:46 -0800989 /* base name (without suffix or extensions) of the bug report files */
990 std::string base_name;
991
992 /* suffix of the bug report files - it's typically the date (when invoked with -d),
993 * although it could be changed by the user using a system property */
994 std::string suffix;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800995
996 /* pointer to the actual path, be it zip or text */
997 std::string path;
998
Felipe Leme635ca312016-01-05 14:23:02 -0800999 /* pointer to the zipped file */
Felipe Leme1e9edc62015-12-21 16:02:13 -08001000 std::unique_ptr<FILE, int(*)(FILE*)> zip_file(NULL, fclose);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001001
Felipe Lemead5f6c42015-11-30 14:26:46 -08001002 /* redirect output if needed */
Felipe Leme71bbfc52015-11-23 14:14:51 -08001003 bool is_redirecting = !use_socket && use_outfile;
1004
1005 if (is_redirecting) {
Felipe Lemead5f6c42015-11-30 14:26:46 -08001006 bugreport_dir = dirname(use_outfile);
1007 base_name = basename(use_outfile);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001008 if (do_add_date) {
1009 char date[80];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001010 strftime(date, sizeof(date), "%Y-%m-%d-%H-%M-%S", localtime(&now));
1011 suffix = date;
1012 } else {
1013 suffix = "undated";
Felipe Leme71bbfc52015-11-23 14:14:51 -08001014 }
1015 if (do_fb) {
Felipe Lemead5f6c42015-11-30 14:26:46 -08001016 // TODO: if dumpstate was an object, the paths could be internal variables and then
1017 // we could have a function to calculate the derived values, such as:
1018 // screenshot_path = GetPath(".png");
1019 screenshot_path = bugreport_dir + "/" + base_name + "-" + suffix + ".png";
Felipe Leme71bbfc52015-11-23 14:14:51 -08001020 }
Felipe Lemead5f6c42015-11-30 14:26:46 -08001021 tmp_path = bugreport_dir + "/" + base_name + "-" + suffix + ".tmp";
Felipe Leme71bbfc52015-11-23 14:14:51 -08001022
Felipe Lemead5f6c42015-11-30 14:26:46 -08001023 ALOGD("Bugreport dir: %s\nBase name: %s\nSuffix: %s\nTemporary path: %s\n"
1024 "Screenshot path: %s\n", bugreport_dir.c_str(), base_name.c_str(), suffix.c_str(),
1025 tmp_path.c_str(), screenshot_path.c_str());
Felipe Leme71bbfc52015-11-23 14:14:51 -08001026
Felipe Leme1e9edc62015-12-21 16:02:13 -08001027 if (do_zip_file) {
1028 ALOGD("Creating initial .zip file");
1029 path = bugreport_dir + "/" + base_name + "-" + suffix + ".zip";
1030 zip_file.reset(fopen(path.c_str(), "wb"));
1031 if (!zip_file) {
1032 ALOGE("fopen(%s, 'wb'): %s\n", path.c_str(), strerror(errno));
1033 do_zip_file = 0;
1034 } else {
1035 zip_writer.reset(new ZipWriter(zip_file.get()));
1036 }
Felipe Leme809d74e2016-02-02 12:57:00 -08001037 add_text_zip_entry("version.txt", version);
Felipe Leme1e9edc62015-12-21 16:02:13 -08001038 }
1039
Felipe Leme71bbfc52015-11-23 14:14:51 -08001040 if (do_update_progress) {
Felipe Lemead5f6c42015-11-30 14:26:46 -08001041 std::vector<std::string> am_args = {
1042 "--receiver-permission", "android.permission.DUMP",
1043 "--es", "android.intent.extra.NAME", suffix,
1044 "--ei", "android.intent.extra.PID", std::to_string(getpid()),
1045 "--ei", "android.intent.extra.MAX", std::to_string(WEIGHT_TOTAL),
1046 };
1047 send_broadcast("android.intent.action.BUGREPORT_STARTED", am_args);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001048 }
1049 }
1050
Nick Kralevichf3599b32016-01-25 15:05:16 -08001051 /* read /proc/cmdline before dropping root */
1052 FILE *cmdline = fopen("/proc/cmdline", "re");
1053 if (cmdline) {
1054 fgets(cmdline_buf, sizeof(cmdline_buf), cmdline);
1055 fclose(cmdline);
1056 }
1057
Jeff Brown1dc94e32014-09-11 14:15:27 -07001058 /* open the vibrator before dropping root */
Felipe Leme6e01fa62015-11-11 19:35:14 -08001059 std::unique_ptr<FILE, int(*)(FILE*)> vibrator(NULL, fclose);
John Michelau1f794c42012-09-17 11:20:19 -05001060 if (do_vibrate) {
Felipe Leme6e01fa62015-11-11 19:35:14 -08001061 vibrator.reset(fopen("/sys/class/timed_output/vibrator/enable", "we"));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001062 if (vibrator) {
Felipe Leme6e01fa62015-11-11 19:35:14 -08001063 vibrate(vibrator.get(), 150);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001064 }
John Michelau1f794c42012-09-17 11:20:19 -05001065 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001066
Felipe Leme3634a1e2015-12-09 10:11:47 -08001067 if (do_fb && do_early_screenshot) {
1068 if (screenshot_path.empty()) {
1069 // should not have happened
1070 ALOGE("INTERNAL ERROR: skipping early screenshot because path was not set");
1071 } else {
1072 ALOGI("taking early screenshot\n");
1073 take_screenshot(screenshot_path);
1074 ALOGI("wrote screenshot: %s\n", screenshot_path.c_str());
1075 if (chown(screenshot_path.c_str(), AID_SHELL, AID_SHELL)) {
1076 ALOGE("Unable to change ownership of screenshot file %s: %s\n",
1077 screenshot_path.c_str(), strerror(errno));
1078 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001079 }
1080 }
1081
Felipe Leme1e9edc62015-12-21 16:02:13 -08001082 if (do_zip_file) {
1083 if (chown(path.c_str(), AID_SHELL, AID_SHELL)) {
1084 ALOGE("Unable to change ownership of zip file %s: %s\n", path.c_str(), strerror(errno));
1085 }
1086 }
1087
Jeff Brown1dc94e32014-09-11 14:15:27 -07001088 /* collect stack traces from Dalvik and native processes (needs root) */
1089 dump_traces_path = dump_traces();
1090
Felipe Leme635ca312016-01-05 14:23:02 -08001091 /* Get the tombstone fds, recovery files, and mount info here while we are running as root. */
Jeff Brown1dc94e32014-09-11 14:15:27 -07001092 get_tombstone_fds(tombstone_data);
Felipe Lemee82a27d2016-01-05 13:35:44 -08001093 add_dir(RECOVERY_DIR, true);
Felipe Leme635ca312016-01-05 14:23:02 -08001094 add_mountinfo();
Jeff Brown1dc94e32014-09-11 14:15:27 -07001095
Felipe Leme608385d2016-02-01 10:35:38 -08001096 if (!drop_root()) {
Nick Kralevich1e339872012-04-25 13:38:45 -07001097 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001098 }
1099
Felipe Leme71bbfc52015-11-23 14:14:51 -08001100 if (is_redirecting) {
Felipe Leme6e01fa62015-11-11 19:35:14 -08001101 /* TODO: rather than generating a text file now and zipping it later,
1102 it would be more efficient to redirect stdout to the zip entry
1103 directly, but the libziparchive doesn't support that option yet. */
1104 redirect_to_file(stdout, const_cast<char*>(tmp_path.c_str()));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001105 }
Felipe Leme608385d2016-02-01 10:35:38 -08001106 // NOTE: there should be no stdout output until now, otherwise it would break the header.
1107 // In particular, DurationReport objects should be created passing 'title, NULL', so their
1108 // duration is logged into ALOG instead.
Felipe Leme809d74e2016-02-02 12:57:00 -08001109 print_header(version);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001110
Felipe Leme3634a1e2015-12-09 10:11:47 -08001111 dumpstate(do_early_screenshot ? "": screenshot_path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001112
Jeff Brown1dc94e32014-09-11 14:15:27 -07001113 /* done */
1114 if (vibrator) {
1115 for (int i = 0; i < 3; i++) {
Felipe Leme6e01fa62015-11-11 19:35:14 -08001116 vibrate(vibrator.get(), 75);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001117 usleep((75 + 50) * 1000);
1118 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001119 }
1120
Felipe Leme55b42a62015-11-10 17:39:08 -08001121 /* close output if needed */
Felipe Leme71bbfc52015-11-23 14:14:51 -08001122 if (is_redirecting) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001123 fclose(stdout);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001124 }
1125
Felipe Leme6e01fa62015-11-11 19:35:14 -08001126 /* rename or zip the (now complete) .tmp file to its final location */
1127 if (use_outfile) {
Felipe Lemead5f6c42015-11-30 14:26:46 -08001128
1129 /* check if user changed the suffix using system properties */
1130 char key[PROPERTY_KEY_MAX];
1131 char value[PROPERTY_VALUE_MAX];
1132 sprintf(key, "dumpstate.%d.name", getpid());
1133 property_get(key, value, "");
1134 bool change_suffix= false;
1135 if (value[0]) {
1136 /* must whitelist which characters are allowed, otherwise it could cross directories */
1137 std::regex valid_regex("^[-_a-zA-Z0-9]+$");
1138 if (std::regex_match(value, valid_regex)) {
1139 change_suffix = true;
1140 } else {
1141 ALOGE("invalid suffix provided by user: %s", value);
1142 }
1143 }
1144 if (change_suffix) {
1145 ALOGI("changing suffix from %s to %s", suffix.c_str(), value);
1146 suffix = value;
1147 if (!screenshot_path.empty()) {
1148 std::string new_screenshot_path =
1149 bugreport_dir + "/" + base_name + "-" + suffix + ".png";
1150 if (rename(screenshot_path.c_str(), new_screenshot_path.c_str())) {
1151 ALOGE("rename(%s, %s): %s\n", screenshot_path.c_str(),
1152 new_screenshot_path.c_str(), strerror(errno));
1153 } else {
1154 screenshot_path = new_screenshot_path;
1155 }
1156 }
1157 }
1158
Felipe Leme6e01fa62015-11-11 19:35:14 -08001159 bool do_text_file = true;
1160 if (do_zip_file) {
Felipe Leme1e9edc62015-12-21 16:02:13 -08001161 ALOGD("Adding text entry to .zip bugreport");
Felipe Lemee82a27d2016-01-05 13:35:44 -08001162 if (!finish_zip_file(base_name + "-" + suffix + ".txt", tmp_path, now)) {
Felipe Leme1e9edc62015-12-21 16:02:13 -08001163 ALOGE("Failed to finish zip file; sending text bugreport instead\n");
Felipe Leme6e01fa62015-11-11 19:35:14 -08001164 do_text_file = true;
1165 } else {
1166 do_text_file = false;
1167 }
1168 }
1169 if (do_text_file) {
Felipe Lemead5f6c42015-11-30 14:26:46 -08001170 ALOGD("Generating .txt bugreport");
1171 path = bugreport_dir + "/" + base_name + "-" + suffix + ".txt";
1172 if (rename(tmp_path.c_str(), path.c_str())) {
1173 ALOGE("rename(%s, %s): %s\n", tmp_path.c_str(), path.c_str(), strerror(errno));
Felipe Leme6e01fa62015-11-11 19:35:14 -08001174 path.clear();
1175 }
1176 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001177 }
1178
Jeff Brown1dc94e32014-09-11 14:15:27 -07001179 /* tell activity manager we're done */
Felipe Leme71bbfc52015-11-23 14:14:51 -08001180 if (do_broadcast) {
Felipe Leme6e01fa62015-11-11 19:35:14 -08001181 if (!path.empty()) {
1182 ALOGI("Final bugreport path: %s\n", path.c_str());
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001183 std::vector<std::string> am_args = {
Felipe Leme43fd1bb2016-01-29 09:07:57 -08001184 "--receiver-permission", "android.permission.DUMP", "--receiver-foreground",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001185 "--ei", "android.intent.extra.PID", std::to_string(getpid()),
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001186 "--es", "android.intent.extra.BUGREPORT", path
1187 };
1188 if (do_fb) {
1189 am_args.push_back("--es");
1190 am_args.push_back("android.intent.extra.SCREENSHOT");
1191 am_args.push_back(screenshot_path);
1192 }
Michal Karpinski4db754f2015-12-11 18:04:32 +00001193 if (is_remote_mode) {
1194 am_args.push_back("--es");
1195 am_args.push_back("android.intent.extra.REMOTE_BUGREPORT_HASH");
1196 am_args.push_back(SHA256_file_hash(path));
1197 send_broadcast("android.intent.action.REMOTE_BUGREPORT_FINISHED", am_args);
1198 } else {
1199 send_broadcast("android.intent.action.BUGREPORT_FINISHED", am_args);
1200 }
Felipe Leme6e01fa62015-11-11 19:35:14 -08001201 } else {
Felipe Leme71bbfc52015-11-23 14:14:51 -08001202 ALOGE("Skipping finished broadcast because bugreport could not be generated\n");
Felipe Leme6e01fa62015-11-11 19:35:14 -08001203 }
Jeff Sharkey27f9e6d2013-03-13 15:45:50 -07001204 }
1205
Felipe Lemee338bf62015-12-07 14:03:50 -08001206 ALOGD("Final progress: %d/%d (originally %d)\n", progress, weight_total, WEIGHT_TOTAL);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001207 ALOGI("done\n");
1208
1209 return 0;
1210}