blob: 2903f39eaf5ae634dd97244cd2a4820a6e1c2674 [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
17#include <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <poll.h>
22#include <signal.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080026#include <string>
Colin Crossf45fa6b2012-03-26 12:38:26 -070027#include <string.h>
28#include <sys/inotify.h>
29#include <sys/stat.h>
30#include <sys/time.h>
31#include <sys/wait.h>
32#include <sys/klog.h>
33#include <time.h>
34#include <unistd.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080035#include <vector>
John Michelaue7b6cf12013-03-07 15:35:35 -060036#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070037
Felipe Leme71bbfc52015-11-23 14:14:51 -080038#define LOG_TAG "dumpstate"
Jeff Brownbf7f4922012-06-07 16:40:01 -070039#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080040#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070041#include <cutils/properties.h>
42#include <cutils/sockets.h>
43#include <private/android_filesystem_config.h>
44
Robert Craig95798372013-04-04 06:33:10 -040045#include <selinux/android.h>
46
Colin Crossf45fa6b2012-03-26 12:38:26 -070047#include "dumpstate.h"
48
Jeff Brown1dc94e32014-09-11 14:15:27 -070049static const int64_t NANOS_PER_SEC = 1000000000;
50
Jeff Brownbf7f4922012-06-07 16:40:01 -070051/* list of native processes to include in the native dumps */
52static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080053 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080054 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070055 "/system/bin/drmserver",
Jeff Brownbf7f4922012-06-07 16:40:01 -070056 "/system/bin/mediaserver",
57 "/system/bin/sdcard",
58 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070059 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070060 NULL,
61};
62
Felipe Leme78f2c862015-12-21 09:55:22 -080063DurationReporter::DurationReporter(const char *title) {
64 title_ = title;
65 if (title) {
66 started_ = DurationReporter::nanotime();
67 }
68}
69
70DurationReporter::~DurationReporter() {
71 if (title_) {
72 uint64_t elapsed = DurationReporter::nanotime() - started_;
73 // Use "Yoda grammar" to make it easier to grep|sort sections.
74 printf("------ %.3fs was the duration of '%s' ------\n",
Felipe Leme0c80cf02016-01-05 13:25:34 -080075 (float) elapsed / NANOS_PER_SEC, title_);
Felipe Leme78f2c862015-12-21 09:55:22 -080076 }
77}
78
79uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080080 struct timespec ts;
81 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080082 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080083}
84
John Spurlock5ecd4be2014-01-29 14:14:40 -050085void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -080086 ON_DRY_RUN_RETURN();
John Spurlock5ecd4be2014-01-29 14:14:40 -050087 DIR *d;
88 struct dirent *de;
89
90 if (header) printf("\n------ %s ------\n", header);
91 func(0);
92
93 if (!(d = opendir("/data/system/users"))) {
94 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
95 return;
96 }
97
98 while ((de = readdir(d))) {
99 int userid;
100 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
101 continue;
102 }
103 func(userid);
104 }
105
106 closedir(d);
107}
108
Colin Cross0c22e8b2012-11-02 15:46:56 -0700109static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700110 DIR *d;
111 struct dirent *de;
112
113 if (!(d = opendir("/proc"))) {
114 printf("Failed to open /proc (%s)\n", strerror(errno));
115 return;
116 }
117
Felipe Leme635ca312016-01-05 14:23:02 -0800118 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700119 while ((de = readdir(d))) {
120 int pid;
121 int fd;
122 char cmdpath[255];
123 char cmdline[255];
124
125 if (!(pid = atoi(de->d_name))) {
126 continue;
127 }
128
129 sprintf(cmdpath,"/proc/%d/cmdline", pid);
130 memset(cmdline, 0, sizeof(cmdline));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700131 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700132 strcpy(cmdline, "N/A");
133 } else {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700134 read(fd, cmdline, sizeof(cmdline) - 1);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700135 close(fd);
136 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700137 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700138 }
139
140 closedir(d);
141}
142
Colin Cross0c22e8b2012-11-02 15:46:56 -0700143static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800144 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700145 func(pid, cmdline);
146}
147
148void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800149 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800150 __for_each_pid(for_each_pid_helper, header, (void *)func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700151}
152
153static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
154 DIR *d;
155 struct dirent *de;
156 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800157 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700158
159 sprintf(taskpath, "/proc/%d/task", pid);
160
161 if (!(d = opendir(taskpath))) {
162 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
163 return;
164 }
165
166 func(pid, pid, cmdline);
167
168 while ((de = readdir(d))) {
169 int tid;
170 int fd;
171 char commpath[255];
172 char comm[255];
173
174 if (!(tid = atoi(de->d_name))) {
175 continue;
176 }
177
178 if (tid == pid)
179 continue;
180
181 sprintf(commpath,"/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800182 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700183 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700184 strcpy(comm, "N/A");
185 } else {
186 char *c;
187 read(fd, comm, sizeof(comm) - 1);
188 close(fd);
189
190 c = strrchr(comm, '\n');
191 if (c) {
192 *c = '\0';
193 }
194 }
195 func(pid, tid, comm);
196 }
197
198 closedir(d);
199}
200
201void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800202 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800203 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700204}
205
206void show_wchan(int pid, int tid, const char *name) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800207 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700208 char path[255];
209 char buffer[255];
210 int fd;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700211 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700212
213 memset(buffer, 0, sizeof(buffer));
214
Colin Cross0c22e8b2012-11-02 15:46:56 -0700215 sprintf(path, "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700216 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700217 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
218 return;
219 }
220
221 if (read(fd, buffer, sizeof(buffer)) < 0) {
222 printf("Failed to read '%s' (%s)\n", path, strerror(errno));
223 goto out_close;
224 }
225
Colin Cross0c22e8b2012-11-02 15:46:56 -0700226 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
227 pid == tid ? 0 : 3, "", name);
228
229 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700230
231out_close:
232 close(fd);
233 return;
234}
235
236void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800237 const char *title = "KERNEL LOG (dmesg)";
238 DurationReporter duration_reporter(title);
239 printf("------ %s ------\n", title);
240
Felipe Leme93d705b2015-11-10 20:10:25 -0800241 ON_DRY_RUN_RETURN();
Elliott Hughes5f87b312012-09-17 11:43:40 -0700242 /* Get size of kernel buffer */
243 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700244 if (size <= 0) {
245 printf("Unexpected klogctl return value: %d\n\n", size);
246 return;
247 }
248 char *buf = (char *) malloc(size + 1);
249 if (buf == NULL) {
250 printf("memory allocation failed\n\n");
251 return;
252 }
253 int retval = klogctl(KLOG_READ_ALL, buf, size);
254 if (retval < 0) {
255 printf("klogctl failure\n\n");
256 free(buf);
257 return;
258 }
259 buf[retval] = '\0';
260 printf("%s\n\n", buf);
261 free(buf);
262 return;
263}
264
265void do_showmap(int pid, const char *name) {
266 char title[255];
267 char arg[255];
268
269 sprintf(title, "SHOW MAP %d (%s)", pid, name);
270 sprintf(arg, "%d", pid);
271 run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL);
272}
273
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800274static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700275 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800276 printf("------ %s (%s", title, path);
277
Colin Crossf45fa6b2012-03-26 12:38:26 -0700278 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800279 // Only show the modification time of non-device files.
280 size_t path_len = strlen(path);
281 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
282 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
283 (path_len < 3 || memcmp(path, "/d/", 3)) &&
284 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700285 char stamp[80];
286 time_t mtime = st.st_mtime;
287 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
288 printf(": %s", stamp);
289 }
290 printf(") ------\n");
291 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800292 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
Colin Crossf45fa6b2012-03-26 12:38:26 -0700293
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800294 bool newline = false;
295 fd_set read_set;
296 struct timeval tm;
297 while (1) {
298 FD_ZERO(&read_set);
299 FD_SET(fd, &read_set);
300 /* Timeout if no data is read for 30 seconds. */
301 tm.tv_sec = 30;
302 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800303 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800304 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
305 if (ret == -1) {
306 printf("*** %s: select failed: %s\n", path, strerror(errno));
307 newline = true;
308 break;
309 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800310 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800311 printf("*** %s: Timed out after %.3fs\n", path,
312 (float) elapsed / NANOS_PER_SEC);
313 newline = true;
314 break;
315 } else {
316 char buffer[65536];
317 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
318 if (bytes_read > 0) {
319 fwrite(buffer, bytes_read, 1, stdout);
320 newline = (buffer[bytes_read-1] == '\n');
321 } else {
322 if (bytes_read == -1) {
323 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
324 newline = true;
325 }
326 break;
327 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700328 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700329 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800330 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700331 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700332
Colin Crossf45fa6b2012-03-26 12:38:26 -0700333 if (!newline) printf("\n");
334 if (title) printf("\n");
335 return 0;
336}
337
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800338/* prints the contents of a file */
339int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800340 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800341 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
342 if (fd < 0) {
343 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800344 printf("*** %s: %s\n", path, strerror(err));
345 if (title) printf("\n");
346 return -1;
347 }
348 return _dump_file_from_fd(title, path, fd);
349}
350
Mark Salyzyn326842f2015-04-30 09:49:41 -0700351/* calls skip to gate calling dump_from_fd recursively
352 * in the specified directory. dump_from_fd defaults to
353 * dump_file_from_fd above when set to NULL. skip defaults
354 * to false when set to NULL. dump_from_fd will always be
355 * called with title NULL.
356 */
357int dump_files(const char *title, const char *dir,
358 bool (*skip)(const char *path),
359 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800360 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700361 DIR *dirp;
362 struct dirent *d;
363 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800364 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700365 int fd, retval = 0;
366
367 if (title) {
368 printf("------ %s (%s) ------\n", title, dir);
369 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800370 ON_DRY_RUN_RETURN(0);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700371
372 if (dir[strlen(dir) - 1] == '/') {
373 ++slash;
374 }
375 dirp = opendir(dir);
376 if (dirp == NULL) {
377 retval = -errno;
378 fprintf(stderr, "%s: %s\n", dir, strerror(errno));
379 return retval;
380 }
381
382 if (!dump_from_fd) {
383 dump_from_fd = dump_file_from_fd;
384 }
385 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
386 if ((d->d_name[0] == '.')
387 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
388 || (d->d_name[1] == '\0'))) {
389 continue;
390 }
391 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
392 (d->d_type == DT_DIR) ? "/" : "");
393 if (!newpath) {
394 retval = -errno;
395 continue;
396 }
397 if (skip && (*skip)(newpath)) {
398 continue;
399 }
400 if (d->d_type == DT_DIR) {
401 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
402 if (ret < 0) {
403 retval = ret;
404 }
405 continue;
406 }
407 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
408 if (fd < 0) {
409 retval = fd;
410 printf("*** %s: %s\n", newpath, strerror(errno));
411 continue;
412 }
413 (*dump_from_fd)(NULL, newpath, fd);
414 }
415 closedir(dirp);
416 if (title) {
417 printf("\n");
418 }
419 return retval;
420}
421
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800422/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
423 * it's possible to avoid issues where opening the file itself can get
424 * stuck.
425 */
426int dump_file_from_fd(const char *title, const char *path, int fd) {
427 int flags = fcntl(fd, F_GETFL);
428 if (flags == -1) {
429 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800430 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800431 return -1;
432 } else if (!(flags & O_NONBLOCK)) {
433 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800434 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800435 return -1;
436 }
437 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700438}
439
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800440bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
441 sigset_t child_mask, old_mask;
442 sigemptyset(&child_mask);
443 sigaddset(&child_mask, SIGCHLD);
444
445 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
446 printf("*** sigprocmask failed: %s\n", strerror(errno));
447 return false;
448 }
449
450 struct timespec ts;
451 ts.tv_sec = timeout_seconds;
452 ts.tv_nsec = 0;
453 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
454 int saved_errno = errno;
455 // Set the signals back the way they were.
456 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
457 printf("*** sigprocmask failed: %s\n", strerror(errno));
458 if (ret == 0) {
459 return false;
460 }
461 }
462 if (ret == -1) {
463 errno = saved_errno;
464 if (errno == EAGAIN) {
465 errno = ETIMEDOUT;
466 } else {
467 printf("*** sigtimedwait failed: %s\n", strerror(errno));
468 }
469 return false;
470 }
471
472 pid_t child_pid = waitpid(pid, status, WNOHANG);
473 if (child_pid != pid) {
474 if (child_pid != -1) {
475 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
476 } else {
477 printf("*** waitpid failed: %s\n", strerror(errno));
478 }
479 return false;
480 }
481 return true;
482}
483
Colin Crossf45fa6b2012-03-26 12:38:26 -0700484int run_command(const char *title, int timeout_seconds, const char *command, ...) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800485 DurationReporter duration_reporter(title);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700486 fflush(stdout);
Felipe Leme93d705b2015-11-10 20:10:25 -0800487
488 const char *args[1024] = {command};
489 size_t arg;
490 va_list ap;
491 va_start(ap, command);
492 if (title) printf("------ %s (%s", title, command);
493 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
494 args[arg] = va_arg(ap, const char *);
495 if (args[arg] == NULL) break;
496 if (title) printf(" %s", args[arg]);
497 }
498 if (title) printf(") ------\n");
499 fflush(stdout);
500
Felipe Leme71bbfc52015-11-23 14:14:51 -0800501 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
Felipe Leme93d705b2015-11-10 20:10:25 -0800502
Felipe Leme71bbfc52015-11-23 14:14:51 -0800503 int status = run_command_always(title, timeout_seconds, args);
504 va_end(ap);
505 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800506}
507
508/* forks a command and waits for it to finish */
509int run_command_always(const char *title, int timeout_seconds, const char *args[]) {
Felipe Leme71bbfc52015-11-23 14:14:51 -0800510 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
511 * It's a good approximation for most cases, except when calling dumpsys, where its weight
512 * should be much higher proportionally to its timeout. */
513 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800514
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800515 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800516 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700517 pid_t pid = fork();
518
519 /* handle error case */
520 if (pid < 0) {
521 printf("*** fork: %s\n", strerror(errno));
522 return pid;
523 }
524
525 /* handle child case */
526 if (pid == 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700527
John Michelaue7b6cf12013-03-07 15:35:35 -0600528 /* make sure the child dies when dumpstate dies */
529 prctl(PR_SET_PDEATHSIG, SIGKILL);
530
Andres Morales2e671bb2014-08-21 12:38:22 -0700531 /* just ignore SIGPIPE, will go down with parent's */
532 struct sigaction sigact;
533 memset(&sigact, 0, sizeof(sigact));
534 sigact.sa_handler = SIG_IGN;
535 sigaction(SIGPIPE, &sigact, NULL);
536
Colin Crossf45fa6b2012-03-26 12:38:26 -0700537 execvp(command, (char**) args);
538 printf("*** exec(%s): %s\n", command, strerror(errno));
539 fflush(stdout);
540 _exit(-1);
541 }
542
543 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800544 int status;
545 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800546 uint64_t elapsed = DurationReporter::nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800547 if (!ret) {
548 if (errno == ETIMEDOUT) {
549 printf("*** %s: Timed out after %.3fs (killing pid %d)\n", command,
550 (float) elapsed / NANOS_PER_SEC, pid);
551 } else {
552 printf("*** %s: Error after %.4fs (killing pid %d)\n", command,
553 (float) elapsed / NANOS_PER_SEC, pid);
554 }
555 kill(pid, SIGTERM);
556 if (!waitpid_with_timeout(pid, 5, NULL)) {
557 kill(pid, SIGKILL);
558 if (!waitpid_with_timeout(pid, 5, NULL)) {
559 printf("*** %s: Cannot kill %d even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700560 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700561 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800562 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700563 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800564
565 if (WIFSIGNALED(status)) {
566 printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
567 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
568 printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
569 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800570
Felipe Leme71bbfc52015-11-23 14:14:51 -0800571 if (weight > 0) {
572 update_progress(weight);
573 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800574 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700575}
576
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800577void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
578 if (args.size() > 1000) {
Felipe Lemead5f6c42015-11-30 14:26:46 -0800579 fprintf(stderr, "send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800580 return;
581 }
Felipe Lemeedb0b0c2016-01-27 11:27:28 -0800582 const char *am_args[1024] = { "/system/bin/am", "broadcast", "--receiver-foreground",
583 "--user", "0", "-a", action.c_str() };
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800584 size_t am_index = 5; // Starts at the index of last initial value above.
585 for (const std::string& arg : args) {
586 am_args[++am_index] = arg.c_str();
587 }
588 // Always terminate with NULL.
589 am_args[am_index + 1] = NULL;
590 run_command_always(NULL, 5, am_args);
591}
592
Colin Crossf45fa6b2012-03-26 12:38:26 -0700593size_t num_props = 0;
594static char* props[2000];
595
596static void print_prop(const char *key, const char *name, void *user) {
597 (void) user;
598 if (num_props < sizeof(props) / sizeof(props[0])) {
599 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
600 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
601 props[num_props++] = strdup(buf);
602 }
603}
604
605static int compare_prop(const void *a, const void *b) {
606 return strcmp(*(char * const *) a, *(char * const *) b);
607}
608
609/* prints all the system properties */
610void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800611 const char* title = "SYSTEM PROPERTIES";
612 DurationReporter duration_reporter(title);
613 printf("------ %s ------\n", title);
Felipe Leme93d705b2015-11-10 20:10:25 -0800614 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700615 size_t i;
616 num_props = 0;
617 property_list(print_prop, NULL);
618 qsort(&props, num_props, sizeof(props[0]), compare_prop);
619
Colin Crossf45fa6b2012-03-26 12:38:26 -0700620 for (i = 0; i < num_props; ++i) {
621 fputs(props[i], stdout);
622 free(props[i]);
623 }
624 printf("\n");
625}
626
627/* redirect output to a service control socket */
628void redirect_to_socket(FILE *redirect, const char *service) {
629 int s = android_get_control_socket(service);
630 if (s < 0) {
631 fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
632 exit(1);
633 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700634 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700635 if (listen(s, 4) < 0) {
636 fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
637 exit(1);
638 }
639
640 struct sockaddr addr;
641 socklen_t alen = sizeof(addr);
642 int fd = accept(s, &addr, &alen);
643 if (fd < 0) {
644 fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
645 exit(1);
646 }
647
648 fflush(redirect);
649 dup2(fd, fileno(redirect));
650 close(fd);
651}
652
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800653/* redirect output to a file */
654void redirect_to_file(FILE *redirect, char *path) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700655 char *chp = path;
656
657 /* skip initial slash */
658 if (chp[0] == '/')
659 chp++;
660
661 /* create leading directories, if necessary */
662 while (chp && chp[0]) {
663 chp = strchr(chp, '/');
664 if (chp) {
665 *chp = 0;
Jeff Sharkey27f9e6d2013-03-13 15:45:50 -0700666 mkdir(path, 0770); /* drwxrwx--- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700667 *chp++ = '/';
668 }
669 }
670
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700671 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800672 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700673 if (fd < 0) {
674 fprintf(stderr, "%s: %s\n", path, strerror(errno));
675 exit(1);
676 }
677
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800678 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700679 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700680}
681
Jeff Brownbf7f4922012-06-07 16:40:01 -0700682static bool should_dump_native_traces(const char* path) {
683 for (const char** p = native_processes_to_dump; *p; p++) {
684 if (!strcmp(*p, path)) {
685 return true;
686 }
687 }
688 return false;
689}
690
691/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
692const char *dump_traces() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800693 DurationReporter duration_reporter("DUMP TRACES");
Felipe Leme93d705b2015-11-10 20:10:25 -0800694 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700695 const char* result = NULL;
696
Colin Crossf45fa6b2012-03-26 12:38:26 -0700697 char traces_path[PROPERTY_VALUE_MAX] = "";
698 property_get("dalvik.vm.stack-trace-file", traces_path, "");
699 if (!traces_path[0]) return NULL;
700
701 /* move the old traces.txt (if any) out of the way temporarily */
702 char anr_traces_path[PATH_MAX];
703 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
704 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
705 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
706 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
707 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
708 }
709
Colin Crossf45fa6b2012-03-26 12:38:26 -0700710 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700711 int fd = TEMP_FAILURE_RETRY(open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800712 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700713 if (fd < 0) {
714 fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
715 return NULL;
716 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700717 int chmod_ret = fchmod(fd, 0666);
718 if (chmod_ret < 0) {
719 fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
720 close(fd);
721 return NULL;
722 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700723
Felipe Leme8620bb42015-11-10 11:04:45 -0800724 /* Variables below must be initialized before 'goto' statements */
725 int dalvik_found = 0;
726 int ifd, wfd = -1;
727
Colin Crossf45fa6b2012-03-26 12:38:26 -0700728 /* walk /proc and kill -QUIT all Dalvik processes */
729 DIR *proc = opendir("/proc");
730 if (proc == NULL) {
731 fprintf(stderr, "/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700732 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700733 }
734
735 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -0800736 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700737 if (ifd < 0) {
738 fprintf(stderr, "inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700739 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700740 }
741
Felipe Leme8620bb42015-11-10 11:04:45 -0800742 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700743 if (wfd < 0) {
744 fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700745 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700746 }
747
748 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700749 while ((d = readdir(proc))) {
750 int pid = atoi(d->d_name);
751 if (pid <= 0) continue;
752
Jeff Brownbf7f4922012-06-07 16:40:01 -0700753 char path[PATH_MAX];
754 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700755 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700756 ssize_t len = readlink(path, data, sizeof(data) - 1);
757 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700758 continue;
759 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700760 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700761
Colin Cross0d6180f2014-07-16 19:00:46 -0700762 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700763 /* skip zygote -- it won't dump its stack anyway */
764 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700765 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700766 len = read(cfd, data, sizeof(data) - 1);
767 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700768 if (len <= 0) {
769 continue;
770 }
771 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700772 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700773 continue;
774 }
775
776 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -0800777 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700778 if (kill(pid, SIGQUIT)) {
779 fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
780 continue;
781 }
782
783 /* wait for the writable-close notification from inotify */
784 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -0700785 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -0700786 if (ret < 0) {
787 fprintf(stderr, "poll: %s\n", strerror(errno));
788 } else if (ret == 0) {
789 fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
790 } else {
791 struct inotify_event ie;
792 read(ifd, &ie, sizeof(ie));
793 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700794
795 if (lseek(fd, 0, SEEK_END) < 0) {
796 fprintf(stderr, "lseek: %s\n", strerror(errno));
797 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800798 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -0800799 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700800 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700801 } else if (should_dump_native_traces(data)) {
802 /* dump native process if appropriate */
803 if (lseek(fd, 0, SEEK_END) < 0) {
804 fprintf(stderr, "lseek: %s\n", strerror(errno));
805 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800806 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800807 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800808
809 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
810 if (timeout_failures == 3) {
811 dprintf(fd, "too many stack dump failures, skipping...\n");
812 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
813 dprintf(fd, "dumping failed, likely due to a timeout\n");
814 timeout_failures++;
815 } else {
816 timeout_failures = 0;
817 }
818 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -0800819 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700820 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700821 }
822 }
823
Colin Crossf45fa6b2012-03-26 12:38:26 -0700824 if (dalvik_found == 0) {
825 fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
826 }
827
828 static char dump_traces_path[PATH_MAX];
829 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
830 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
831 if (rename(traces_path, dump_traces_path)) {
832 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700833 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700834 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700835 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700836
837 /* replace the saved [ANR] traces.txt file */
838 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700839
840error_close_ifd:
841 close(ifd);
842error_close_fd:
843 close(fd);
844 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700845}
846
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700847void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800848 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -0800849 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700850 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
851 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700852 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700853 if (!fp) {
854 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
855 return;
856 }
857 char table[16];
858 // Each line has an integer (the table number), a space, and a string (the table name). We only
859 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
860 // Add a fixed max limit so this doesn't go awry.
861 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
862 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
863 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
864 }
865 fclose(fp);
866}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800867
868/* overall progress */
869int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -0800870int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -0800871int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800872
873// TODO: make this function thread safe if sections are generated in parallel.
874void update_progress(int delta) {
875 if (!do_update_progress) return;
876
877 progress += delta;
878
879 char key[PROPERTY_KEY_MAX];
880 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -0800881
882 // adjusts max on the fly
883 if (progress > weight_total) {
884 int new_total = weight_total * 1.2;
885 fprintf(stderr, "Adjusting total weight from %d to %d\n", weight_total, new_total);
886 weight_total = new_total;
887 sprintf(key, "dumpstate.%d.max", getpid());
888 sprintf(value, "%d", weight_total);
889 int status = property_set(key, value);
890 if (status) {
891 ALOGW("Could not update max weight by setting system property %s to %s: %d\n",
892 key, value, status);
893 }
894 }
895
Felipe Leme71bbfc52015-11-23 14:14:51 -0800896 sprintf(key, "dumpstate.%d.progress", getpid());
897 sprintf(value, "%d", progress);
898
899 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
900 // directly for debuggging.
Felipe Lemead5f6c42015-11-30 14:26:46 -0800901 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800902
903 int status = property_set(key, value);
904 if (status) {
905 ALOGW("Could not update progress by setting system property %s to %s: %d\n",
906 key, value, status);
907 }
908}
Felipe Lemee338bf62015-12-07 14:03:50 -0800909
Felipe Leme3634a1e2015-12-09 10:11:47 -0800910void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -0800911 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
912 run_command_always(NULL, 10, args);
913}
Mark Salyzynf55d4022015-12-11 07:32:31 -0800914
Felipe Leme0c80cf02016-01-05 13:25:34 -0800915void vibrate(FILE* vibrator, int ms) {
916 fprintf(vibrator, "%d\n", ms);
917 fflush(vibrator);
918}
919
920bool is_dir(const char* pathname) {
921 struct stat info;
922 if (stat(pathname, &info) == -1) {
923 return false;
924 }
925 return S_ISDIR(info.st_mode);
926}
927
928time_t get_mtime(int fd, time_t default_mtime) {
929 struct stat info;
930 if (fstat(fd, &info) == -1) {
931 return default_mtime;
932 }
933 return info.st_mtime;
934}
935
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800936void dump_emmc_ecsd(const char *ext_csd_path) {
937 static const size_t EXT_CSD_REV = 192;
938 static const size_t EXT_PRE_EOL_INFO = 267;
939 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
940 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
941 struct hex {
942 char str[2];
943 } buffer[512];
944 int fd, ext_csd_rev, ext_pre_eol_info;
945 ssize_t bytes_read;
946 static const char *ver_str[] = {
947 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
948 };
949 static const char *eol_str[] = {
950 "Undefined",
951 "Normal",
952 "Warning (consumed 80% of reserve)",
Mark Salyzyn4b45d672015-12-11 10:41:52 -0800953 "Urgent (consumed 90% of reserve)"
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800954 };
955
956 printf("------ %s Extended CSD ------\n", ext_csd_path);
957
958 fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
959 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
960 if (fd < 0) {
961 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
962 return;
963 }
964
965 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
966 close(fd);
967 if (bytes_read < 0) {
968 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
969 return;
970 }
Mark Salyzyn4b45d672015-12-11 10:41:52 -0800971 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800972 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
973 return;
974 }
975
976 ext_csd_rev = 0;
977 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
978 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
979 ext_csd_path, buffer[EXT_CSD_REV].str);
980 return;
981 }
982
983 printf("rev 1.%d (MMC %s)\n",
984 ext_csd_rev,
985 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
986 ver_str[ext_csd_rev] :
987 "Unknown");
988 if (ext_csd_rev < 7) {
989 printf("\n");
990 return;
991 }
992
Mark Salyzyn4b45d672015-12-11 10:41:52 -0800993 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800994 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
995 return;
996 }
997
998 ext_pre_eol_info = 0;
999 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1000 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1001 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1002 return;
1003 }
1004 printf("PRE_EOL_INFO %d (MMC %s)\n",
1005 ext_pre_eol_info,
1006 eol_str[(ext_pre_eol_info < (int)
1007 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1008 ext_pre_eol_info : 0]);
1009
1010 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1011 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1012 ++lifetime) {
1013 int ext_device_life_time_est;
1014 static const char *est_str[] = {
1015 "Undefined",
1016 "0-10% of device lifetime used",
1017 "10-20% of device lifetime used",
1018 "20-30% of device lifetime used",
1019 "30-40% of device lifetime used",
1020 "40-50% of device lifetime used",
1021 "50-60% of device lifetime used",
1022 "60-70% of device lifetime used",
1023 "70-80% of device lifetime used",
1024 "80-90% of device lifetime used",
1025 "90-100% of device lifetime used",
1026 "Exceeded the maximum estimated device lifetime",
1027 };
1028
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001029 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001030 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1031 break;
1032 }
1033
1034 ext_device_life_time_est = 0;
1035 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1036 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1037 ext_csd_path,
1038 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1039 buffer[lifetime].str);
1040 continue;
1041 }
1042 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1043 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1044 ext_device_life_time_est,
1045 est_str[(ext_device_life_time_est < (int)
1046 (sizeof(est_str) / sizeof(est_str[0]))) ?
1047 ext_device_life_time_est : 0]);
1048 }
1049
1050 printf("\n");
1051}