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