blob: ee60f57f8352a2aa8512f3d1410a2a036022c35a [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 Leme608385d2016-02-01 10:35:38 -080063DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
64
65DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme78f2c862015-12-21 09:55:22 -080066 title_ = title;
67 if (title) {
68 started_ = DurationReporter::nanotime();
69 }
Felipe Leme608385d2016-02-01 10:35:38 -080070 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -080071}
72
73DurationReporter::~DurationReporter() {
74 if (title_) {
75 uint64_t elapsed = DurationReporter::nanotime() - started_;
76 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme608385d2016-02-01 10:35:38 -080077 if (out_) {
78 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
79 (float) elapsed / NANOS_PER_SEC, title_);
80 } else {
81 ALOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
82 }
Felipe Leme78f2c862015-12-21 09:55:22 -080083 }
84}
85
86uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080087 struct timespec ts;
88 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080089 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080090}
91
John Spurlock5ecd4be2014-01-29 14:14:40 -050092void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -080093 ON_DRY_RUN_RETURN();
John Spurlock5ecd4be2014-01-29 14:14:40 -050094 DIR *d;
95 struct dirent *de;
96
97 if (header) printf("\n------ %s ------\n", header);
98 func(0);
99
100 if (!(d = opendir("/data/system/users"))) {
101 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
102 return;
103 }
104
105 while ((de = readdir(d))) {
106 int userid;
107 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
108 continue;
109 }
110 func(userid);
111 }
112
113 closedir(d);
114}
115
Colin Cross0c22e8b2012-11-02 15:46:56 -0700116static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700117 DIR *d;
118 struct dirent *de;
119
120 if (!(d = opendir("/proc"))) {
121 printf("Failed to open /proc (%s)\n", strerror(errno));
122 return;
123 }
124
Felipe Leme635ca312016-01-05 14:23:02 -0800125 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700126 while ((de = readdir(d))) {
127 int pid;
128 int fd;
129 char cmdpath[255];
130 char cmdline[255];
131
132 if (!(pid = atoi(de->d_name))) {
133 continue;
134 }
135
136 sprintf(cmdpath,"/proc/%d/cmdline", pid);
137 memset(cmdline, 0, sizeof(cmdline));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700138 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700139 strcpy(cmdline, "N/A");
140 } else {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700141 read(fd, cmdline, sizeof(cmdline) - 1);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700142 close(fd);
143 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700144 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700145 }
146
147 closedir(d);
148}
149
Colin Cross0c22e8b2012-11-02 15:46:56 -0700150static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800151 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700152 func(pid, cmdline);
153}
154
155void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800156 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800157 __for_each_pid(for_each_pid_helper, header, (void *)func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700158}
159
160static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
161 DIR *d;
162 struct dirent *de;
163 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800164 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700165
166 sprintf(taskpath, "/proc/%d/task", pid);
167
168 if (!(d = opendir(taskpath))) {
169 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
170 return;
171 }
172
173 func(pid, pid, cmdline);
174
175 while ((de = readdir(d))) {
176 int tid;
177 int fd;
178 char commpath[255];
179 char comm[255];
180
181 if (!(tid = atoi(de->d_name))) {
182 continue;
183 }
184
185 if (tid == pid)
186 continue;
187
188 sprintf(commpath,"/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800189 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700190 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700191 strcpy(comm, "N/A");
192 } else {
193 char *c;
194 read(fd, comm, sizeof(comm) - 1);
195 close(fd);
196
197 c = strrchr(comm, '\n');
198 if (c) {
199 *c = '\0';
200 }
201 }
202 func(pid, tid, comm);
203 }
204
205 closedir(d);
206}
207
208void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800209 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800210 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700211}
212
213void show_wchan(int pid, int tid, const char *name) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800214 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700215 char path[255];
216 char buffer[255];
217 int fd;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700218 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700219
220 memset(buffer, 0, sizeof(buffer));
221
Colin Cross0c22e8b2012-11-02 15:46:56 -0700222 sprintf(path, "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700223 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700224 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
225 return;
226 }
227
228 if (read(fd, buffer, sizeof(buffer)) < 0) {
229 printf("Failed to read '%s' (%s)\n", path, strerror(errno));
230 goto out_close;
231 }
232
Colin Cross0c22e8b2012-11-02 15:46:56 -0700233 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
234 pid == tid ? 0 : 3, "", name);
235
236 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700237
238out_close:
239 close(fd);
240 return;
241}
242
243void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800244 const char *title = "KERNEL LOG (dmesg)";
245 DurationReporter duration_reporter(title);
246 printf("------ %s ------\n", title);
247
Felipe Leme93d705b2015-11-10 20:10:25 -0800248 ON_DRY_RUN_RETURN();
Elliott Hughes5f87b312012-09-17 11:43:40 -0700249 /* Get size of kernel buffer */
250 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700251 if (size <= 0) {
252 printf("Unexpected klogctl return value: %d\n\n", size);
253 return;
254 }
255 char *buf = (char *) malloc(size + 1);
256 if (buf == NULL) {
257 printf("memory allocation failed\n\n");
258 return;
259 }
260 int retval = klogctl(KLOG_READ_ALL, buf, size);
261 if (retval < 0) {
262 printf("klogctl failure\n\n");
263 free(buf);
264 return;
265 }
266 buf[retval] = '\0';
267 printf("%s\n\n", buf);
268 free(buf);
269 return;
270}
271
272void do_showmap(int pid, const char *name) {
273 char title[255];
274 char arg[255];
275
276 sprintf(title, "SHOW MAP %d (%s)", pid, name);
277 sprintf(arg, "%d", pid);
278 run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL);
279}
280
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800281static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700282 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800283 printf("------ %s (%s", title, path);
284
Colin Crossf45fa6b2012-03-26 12:38:26 -0700285 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800286 // Only show the modification time of non-device files.
287 size_t path_len = strlen(path);
288 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
289 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
290 (path_len < 3 || memcmp(path, "/d/", 3)) &&
291 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700292 char stamp[80];
293 time_t mtime = st.st_mtime;
294 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
295 printf(": %s", stamp);
296 }
297 printf(") ------\n");
298 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800299 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
Colin Crossf45fa6b2012-03-26 12:38:26 -0700300
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800301 bool newline = false;
302 fd_set read_set;
303 struct timeval tm;
304 while (1) {
305 FD_ZERO(&read_set);
306 FD_SET(fd, &read_set);
307 /* Timeout if no data is read for 30 seconds. */
308 tm.tv_sec = 30;
309 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800310 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800311 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
312 if (ret == -1) {
313 printf("*** %s: select failed: %s\n", path, strerror(errno));
314 newline = true;
315 break;
316 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800317 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800318 printf("*** %s: Timed out after %.3fs\n", path,
319 (float) elapsed / NANOS_PER_SEC);
320 newline = true;
321 break;
322 } else {
323 char buffer[65536];
324 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
325 if (bytes_read > 0) {
326 fwrite(buffer, bytes_read, 1, stdout);
327 newline = (buffer[bytes_read-1] == '\n');
328 } else {
329 if (bytes_read == -1) {
330 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
331 newline = true;
332 }
333 break;
334 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700335 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700336 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800337 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700338 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700339
Colin Crossf45fa6b2012-03-26 12:38:26 -0700340 if (!newline) printf("\n");
341 if (title) printf("\n");
342 return 0;
343}
344
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800345/* prints the contents of a file */
346int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800347 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800348 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
349 if (fd < 0) {
350 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800351 printf("*** %s: %s\n", path, strerror(err));
352 if (title) printf("\n");
353 return -1;
354 }
355 return _dump_file_from_fd(title, path, fd);
356}
357
Mark Salyzyn326842f2015-04-30 09:49:41 -0700358/* calls skip to gate calling dump_from_fd recursively
359 * in the specified directory. dump_from_fd defaults to
360 * dump_file_from_fd above when set to NULL. skip defaults
361 * to false when set to NULL. dump_from_fd will always be
362 * called with title NULL.
363 */
364int dump_files(const char *title, const char *dir,
365 bool (*skip)(const char *path),
366 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800367 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700368 DIR *dirp;
369 struct dirent *d;
370 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800371 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700372 int fd, retval = 0;
373
374 if (title) {
375 printf("------ %s (%s) ------\n", title, dir);
376 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800377 ON_DRY_RUN_RETURN(0);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700378
379 if (dir[strlen(dir) - 1] == '/') {
380 ++slash;
381 }
382 dirp = opendir(dir);
383 if (dirp == NULL) {
384 retval = -errno;
385 fprintf(stderr, "%s: %s\n", dir, strerror(errno));
386 return retval;
387 }
388
389 if (!dump_from_fd) {
390 dump_from_fd = dump_file_from_fd;
391 }
392 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
393 if ((d->d_name[0] == '.')
394 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
395 || (d->d_name[1] == '\0'))) {
396 continue;
397 }
398 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
399 (d->d_type == DT_DIR) ? "/" : "");
400 if (!newpath) {
401 retval = -errno;
402 continue;
403 }
404 if (skip && (*skip)(newpath)) {
405 continue;
406 }
407 if (d->d_type == DT_DIR) {
408 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
409 if (ret < 0) {
410 retval = ret;
411 }
412 continue;
413 }
414 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
415 if (fd < 0) {
416 retval = fd;
417 printf("*** %s: %s\n", newpath, strerror(errno));
418 continue;
419 }
420 (*dump_from_fd)(NULL, newpath, fd);
421 }
422 closedir(dirp);
423 if (title) {
424 printf("\n");
425 }
426 return retval;
427}
428
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800429/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
430 * it's possible to avoid issues where opening the file itself can get
431 * stuck.
432 */
433int dump_file_from_fd(const char *title, const char *path, int fd) {
434 int flags = fcntl(fd, F_GETFL);
435 if (flags == -1) {
436 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800437 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800438 return -1;
439 } else if (!(flags & O_NONBLOCK)) {
440 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800441 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800442 return -1;
443 }
444 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700445}
446
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800447bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
448 sigset_t child_mask, old_mask;
449 sigemptyset(&child_mask);
450 sigaddset(&child_mask, SIGCHLD);
451
452 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
453 printf("*** sigprocmask failed: %s\n", strerror(errno));
454 return false;
455 }
456
457 struct timespec ts;
458 ts.tv_sec = timeout_seconds;
459 ts.tv_nsec = 0;
460 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
461 int saved_errno = errno;
462 // Set the signals back the way they were.
463 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
464 printf("*** sigprocmask failed: %s\n", strerror(errno));
465 if (ret == 0) {
466 return false;
467 }
468 }
469 if (ret == -1) {
470 errno = saved_errno;
471 if (errno == EAGAIN) {
472 errno = ETIMEDOUT;
473 } else {
474 printf("*** sigtimedwait failed: %s\n", strerror(errno));
475 }
476 return false;
477 }
478
479 pid_t child_pid = waitpid(pid, status, WNOHANG);
480 if (child_pid != pid) {
481 if (child_pid != -1) {
482 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
483 } else {
484 printf("*** waitpid failed: %s\n", strerror(errno));
485 }
486 return false;
487 }
488 return true;
489}
490
Colin Crossf45fa6b2012-03-26 12:38:26 -0700491int run_command(const char *title, int timeout_seconds, const char *command, ...) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800492 DurationReporter duration_reporter(title);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700493 fflush(stdout);
Felipe Leme93d705b2015-11-10 20:10:25 -0800494
495 const char *args[1024] = {command};
496 size_t arg;
497 va_list ap;
498 va_start(ap, command);
499 if (title) printf("------ %s (%s", title, command);
500 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
501 args[arg] = va_arg(ap, const char *);
502 if (args[arg] == NULL) break;
503 if (title) printf(" %s", args[arg]);
504 }
505 if (title) printf(") ------\n");
506 fflush(stdout);
507
Felipe Leme71bbfc52015-11-23 14:14:51 -0800508 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
Felipe Leme93d705b2015-11-10 20:10:25 -0800509
Felipe Leme71bbfc52015-11-23 14:14:51 -0800510 int status = run_command_always(title, timeout_seconds, args);
511 va_end(ap);
512 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800513}
514
515/* forks a command and waits for it to finish */
516int run_command_always(const char *title, int timeout_seconds, const char *args[]) {
Felipe Leme71bbfc52015-11-23 14:14:51 -0800517 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
518 * It's a good approximation for most cases, except when calling dumpsys, where its weight
519 * should be much higher proportionally to its timeout. */
520 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800521
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800522 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800523 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700524 pid_t pid = fork();
525
526 /* handle error case */
527 if (pid < 0) {
528 printf("*** fork: %s\n", strerror(errno));
529 return pid;
530 }
531
532 /* handle child case */
533 if (pid == 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700534
John Michelaue7b6cf12013-03-07 15:35:35 -0600535 /* make sure the child dies when dumpstate dies */
536 prctl(PR_SET_PDEATHSIG, SIGKILL);
537
Andres Morales2e671bb2014-08-21 12:38:22 -0700538 /* just ignore SIGPIPE, will go down with parent's */
539 struct sigaction sigact;
540 memset(&sigact, 0, sizeof(sigact));
541 sigact.sa_handler = SIG_IGN;
542 sigaction(SIGPIPE, &sigact, NULL);
543
Colin Crossf45fa6b2012-03-26 12:38:26 -0700544 execvp(command, (char**) args);
545 printf("*** exec(%s): %s\n", command, strerror(errno));
546 fflush(stdout);
547 _exit(-1);
548 }
549
550 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800551 int status;
552 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800553 uint64_t elapsed = DurationReporter::nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800554 if (!ret) {
555 if (errno == ETIMEDOUT) {
556 printf("*** %s: Timed out after %.3fs (killing pid %d)\n", command,
557 (float) elapsed / NANOS_PER_SEC, pid);
558 } else {
559 printf("*** %s: Error after %.4fs (killing pid %d)\n", command,
560 (float) elapsed / NANOS_PER_SEC, pid);
561 }
562 kill(pid, SIGTERM);
563 if (!waitpid_with_timeout(pid, 5, NULL)) {
564 kill(pid, SIGKILL);
565 if (!waitpid_with_timeout(pid, 5, NULL)) {
566 printf("*** %s: Cannot kill %d even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700567 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700568 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800569 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700570 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800571
572 if (WIFSIGNALED(status)) {
573 printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
574 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
575 printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
576 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800577
Felipe Leme71bbfc52015-11-23 14:14:51 -0800578 if (weight > 0) {
579 update_progress(weight);
580 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800581 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700582}
583
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800584void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
585 if (args.size() > 1000) {
Felipe Lemead5f6c42015-11-30 14:26:46 -0800586 fprintf(stderr, "send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800587 return;
588 }
Felipe Lemeb0b4aa22016-01-29 08:46:27 -0800589 const char *am_args[1024] = { "/system/bin/am", "broadcast",
Felipe Lemeedb0b0c2016-01-27 11:27:28 -0800590 "--user", "0", "-a", action.c_str() };
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800591 size_t am_index = 5; // Starts at the index of last initial value above.
592 for (const std::string& arg : args) {
593 am_args[++am_index] = arg.c_str();
594 }
595 // Always terminate with NULL.
596 am_args[am_index + 1] = NULL;
597 run_command_always(NULL, 5, am_args);
598}
599
Colin Crossf45fa6b2012-03-26 12:38:26 -0700600size_t num_props = 0;
601static char* props[2000];
602
603static void print_prop(const char *key, const char *name, void *user) {
604 (void) user;
605 if (num_props < sizeof(props) / sizeof(props[0])) {
606 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
607 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
608 props[num_props++] = strdup(buf);
609 }
610}
611
612static int compare_prop(const void *a, const void *b) {
613 return strcmp(*(char * const *) a, *(char * const *) b);
614}
615
616/* prints all the system properties */
617void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800618 const char* title = "SYSTEM PROPERTIES";
619 DurationReporter duration_reporter(title);
620 printf("------ %s ------\n", title);
Felipe Leme93d705b2015-11-10 20:10:25 -0800621 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700622 size_t i;
623 num_props = 0;
624 property_list(print_prop, NULL);
625 qsort(&props, num_props, sizeof(props[0]), compare_prop);
626
Colin Crossf45fa6b2012-03-26 12:38:26 -0700627 for (i = 0; i < num_props; ++i) {
628 fputs(props[i], stdout);
629 free(props[i]);
630 }
631 printf("\n");
632}
633
634/* redirect output to a service control socket */
635void redirect_to_socket(FILE *redirect, const char *service) {
636 int s = android_get_control_socket(service);
637 if (s < 0) {
638 fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
639 exit(1);
640 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700641 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700642 if (listen(s, 4) < 0) {
643 fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
644 exit(1);
645 }
646
647 struct sockaddr addr;
648 socklen_t alen = sizeof(addr);
649 int fd = accept(s, &addr, &alen);
650 if (fd < 0) {
651 fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
652 exit(1);
653 }
654
655 fflush(redirect);
656 dup2(fd, fileno(redirect));
657 close(fd);
658}
659
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800660/* redirect output to a file */
661void redirect_to_file(FILE *redirect, char *path) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700662 char *chp = path;
663
664 /* skip initial slash */
665 if (chp[0] == '/')
666 chp++;
667
668 /* create leading directories, if necessary */
669 while (chp && chp[0]) {
670 chp = strchr(chp, '/');
671 if (chp) {
672 *chp = 0;
Jeff Sharkey27f9e6d2013-03-13 15:45:50 -0700673 mkdir(path, 0770); /* drwxrwx--- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700674 *chp++ = '/';
675 }
676 }
677
Felipe Leme608385d2016-02-01 10:35:38 -0800678 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800679 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700680 if (fd < 0) {
681 fprintf(stderr, "%s: %s\n", path, strerror(errno));
682 exit(1);
683 }
684
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800685 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700686 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700687}
688
Jeff Brownbf7f4922012-06-07 16:40:01 -0700689static bool should_dump_native_traces(const char* path) {
690 for (const char** p = native_processes_to_dump; *p; p++) {
691 if (!strcmp(*p, path)) {
692 return true;
693 }
694 }
695 return false;
696}
697
698/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
699const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -0800700 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Leme93d705b2015-11-10 20:10:25 -0800701 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700702 const char* result = NULL;
703
Colin Crossf45fa6b2012-03-26 12:38:26 -0700704 char traces_path[PROPERTY_VALUE_MAX] = "";
705 property_get("dalvik.vm.stack-trace-file", traces_path, "");
706 if (!traces_path[0]) return NULL;
707
708 /* move the old traces.txt (if any) out of the way temporarily */
709 char anr_traces_path[PATH_MAX];
710 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
711 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
712 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
713 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
714 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
715 }
716
Colin Crossf45fa6b2012-03-26 12:38:26 -0700717 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700718 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 -0800719 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700720 if (fd < 0) {
721 fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
722 return NULL;
723 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700724 int chmod_ret = fchmod(fd, 0666);
725 if (chmod_ret < 0) {
726 fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
727 close(fd);
728 return NULL;
729 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700730
Felipe Leme8620bb42015-11-10 11:04:45 -0800731 /* Variables below must be initialized before 'goto' statements */
732 int dalvik_found = 0;
733 int ifd, wfd = -1;
734
Colin Crossf45fa6b2012-03-26 12:38:26 -0700735 /* walk /proc and kill -QUIT all Dalvik processes */
736 DIR *proc = opendir("/proc");
737 if (proc == NULL) {
738 fprintf(stderr, "/proc: %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
742 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -0800743 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700744 if (ifd < 0) {
745 fprintf(stderr, "inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700746 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700747 }
748
Felipe Leme8620bb42015-11-10 11:04:45 -0800749 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700750 if (wfd < 0) {
751 fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700752 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700753 }
754
755 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700756 while ((d = readdir(proc))) {
757 int pid = atoi(d->d_name);
758 if (pid <= 0) continue;
759
Jeff Brownbf7f4922012-06-07 16:40:01 -0700760 char path[PATH_MAX];
761 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700762 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700763 ssize_t len = readlink(path, data, sizeof(data) - 1);
764 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700765 continue;
766 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700767 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700768
Colin Cross0d6180f2014-07-16 19:00:46 -0700769 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700770 /* skip zygote -- it won't dump its stack anyway */
771 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700772 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700773 len = read(cfd, data, sizeof(data) - 1);
774 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700775 if (len <= 0) {
776 continue;
777 }
778 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700779 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700780 continue;
781 }
782
783 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -0800784 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700785 if (kill(pid, SIGQUIT)) {
786 fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
787 continue;
788 }
789
790 /* wait for the writable-close notification from inotify */
791 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -0700792 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -0700793 if (ret < 0) {
794 fprintf(stderr, "poll: %s\n", strerror(errno));
795 } else if (ret == 0) {
796 fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
797 } else {
798 struct inotify_event ie;
799 read(ifd, &ie, sizeof(ie));
800 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700801
802 if (lseek(fd, 0, SEEK_END) < 0) {
803 fprintf(stderr, "lseek: %s\n", strerror(errno));
804 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800805 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -0800806 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700807 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700808 } else if (should_dump_native_traces(data)) {
809 /* dump native process if appropriate */
810 if (lseek(fd, 0, SEEK_END) < 0) {
811 fprintf(stderr, "lseek: %s\n", strerror(errno));
812 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800813 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800814 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800815
816 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
817 if (timeout_failures == 3) {
818 dprintf(fd, "too many stack dump failures, skipping...\n");
819 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
820 dprintf(fd, "dumping failed, likely due to a timeout\n");
821 timeout_failures++;
822 } else {
823 timeout_failures = 0;
824 }
825 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -0800826 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700827 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700828 }
829 }
830
Colin Crossf45fa6b2012-03-26 12:38:26 -0700831 if (dalvik_found == 0) {
832 fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
833 }
834
835 static char dump_traces_path[PATH_MAX];
836 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
837 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
838 if (rename(traces_path, dump_traces_path)) {
839 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700840 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700841 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700842 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700843
844 /* replace the saved [ANR] traces.txt file */
845 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700846
847error_close_ifd:
848 close(ifd);
849error_close_fd:
850 close(fd);
851 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700852}
853
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700854void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800855 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -0800856 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700857 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
858 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700859 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700860 if (!fp) {
861 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
862 return;
863 }
864 char table[16];
865 // Each line has an integer (the table number), a space, and a string (the table name). We only
866 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
867 // Add a fixed max limit so this doesn't go awry.
868 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
869 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
870 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
871 }
872 fclose(fp);
873}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800874
875/* overall progress */
876int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -0800877int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -0800878int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800879
880// TODO: make this function thread safe if sections are generated in parallel.
881void update_progress(int delta) {
882 if (!do_update_progress) return;
883
884 progress += delta;
885
886 char key[PROPERTY_KEY_MAX];
887 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -0800888
889 // adjusts max on the fly
890 if (progress > weight_total) {
891 int new_total = weight_total * 1.2;
892 fprintf(stderr, "Adjusting total weight from %d to %d\n", weight_total, new_total);
893 weight_total = new_total;
894 sprintf(key, "dumpstate.%d.max", getpid());
895 sprintf(value, "%d", weight_total);
896 int status = property_set(key, value);
897 if (status) {
898 ALOGW("Could not update max weight by setting system property %s to %s: %d\n",
899 key, value, status);
900 }
901 }
902
Felipe Leme71bbfc52015-11-23 14:14:51 -0800903 sprintf(key, "dumpstate.%d.progress", getpid());
904 sprintf(value, "%d", progress);
905
906 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
907 // directly for debuggging.
Felipe Lemead5f6c42015-11-30 14:26:46 -0800908 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800909
910 int status = property_set(key, value);
911 if (status) {
912 ALOGW("Could not update progress by setting system property %s to %s: %d\n",
913 key, value, status);
914 }
915}
Felipe Lemee338bf62015-12-07 14:03:50 -0800916
Felipe Leme3634a1e2015-12-09 10:11:47 -0800917void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -0800918 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
919 run_command_always(NULL, 10, args);
920}
Mark Salyzynf55d4022015-12-11 07:32:31 -0800921
Felipe Leme0c80cf02016-01-05 13:25:34 -0800922void vibrate(FILE* vibrator, int ms) {
923 fprintf(vibrator, "%d\n", ms);
924 fflush(vibrator);
925}
926
927bool is_dir(const char* pathname) {
928 struct stat info;
929 if (stat(pathname, &info) == -1) {
930 return false;
931 }
932 return S_ISDIR(info.st_mode);
933}
934
935time_t get_mtime(int fd, time_t default_mtime) {
936 struct stat info;
937 if (fstat(fd, &info) == -1) {
938 return default_mtime;
939 }
940 return info.st_mtime;
941}
942
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800943void dump_emmc_ecsd(const char *ext_csd_path) {
944 static const size_t EXT_CSD_REV = 192;
945 static const size_t EXT_PRE_EOL_INFO = 267;
946 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
947 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
948 struct hex {
949 char str[2];
950 } buffer[512];
951 int fd, ext_csd_rev, ext_pre_eol_info;
952 ssize_t bytes_read;
953 static const char *ver_str[] = {
954 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
955 };
956 static const char *eol_str[] = {
957 "Undefined",
958 "Normal",
959 "Warning (consumed 80% of reserve)",
Mark Salyzyn4b45d672015-12-11 10:41:52 -0800960 "Urgent (consumed 90% of reserve)"
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800961 };
962
963 printf("------ %s Extended CSD ------\n", ext_csd_path);
964
965 fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
966 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
967 if (fd < 0) {
968 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
969 return;
970 }
971
972 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
973 close(fd);
974 if (bytes_read < 0) {
975 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
976 return;
977 }
Mark Salyzyn4b45d672015-12-11 10:41:52 -0800978 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800979 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
980 return;
981 }
982
983 ext_csd_rev = 0;
984 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
985 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
986 ext_csd_path, buffer[EXT_CSD_REV].str);
987 return;
988 }
989
990 printf("rev 1.%d (MMC %s)\n",
991 ext_csd_rev,
992 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
993 ver_str[ext_csd_rev] :
994 "Unknown");
995 if (ext_csd_rev < 7) {
996 printf("\n");
997 return;
998 }
999
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001000 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001001 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1002 return;
1003 }
1004
1005 ext_pre_eol_info = 0;
1006 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1007 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1008 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1009 return;
1010 }
1011 printf("PRE_EOL_INFO %d (MMC %s)\n",
1012 ext_pre_eol_info,
1013 eol_str[(ext_pre_eol_info < (int)
1014 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1015 ext_pre_eol_info : 0]);
1016
1017 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1018 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1019 ++lifetime) {
1020 int ext_device_life_time_est;
1021 static const char *est_str[] = {
1022 "Undefined",
1023 "0-10% of device lifetime used",
1024 "10-20% of device lifetime used",
1025 "20-30% of device lifetime used",
1026 "30-40% of device lifetime used",
1027 "40-50% of device lifetime used",
1028 "50-60% of device lifetime used",
1029 "60-70% of device lifetime used",
1030 "70-80% of device lifetime used",
1031 "80-90% of device lifetime used",
1032 "90-100% of device lifetime used",
1033 "Exceeded the maximum estimated device lifetime",
1034 };
1035
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001036 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001037 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1038 break;
1039 }
1040
1041 ext_device_life_time_est = 0;
1042 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1043 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1044 ext_csd_path,
1045 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1046 buffer[lifetime].str);
1047 continue;
1048 }
1049 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1050 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1051 ext_device_life_time_est,
1052 est_str[(ext_device_life_time_est < (int)
1053 (sizeof(est_str) / sizeof(est_str[0]))) ?
1054 ext_device_life_time_est : 0]);
1055 }
1056
1057 printf("\n");
1058}