blob: 0c35430881d9fff8eb93aa10fa771c1c26d9e375 [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
Felipe Leme111b9d02016-02-03 09:28:24 -0800660void create_parent_dirs(const char *path) {
661 char *chp = (char*) path;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700662
663 /* skip initial slash */
664 if (chp[0] == '/')
665 chp++;
666
667 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800668 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700669 while (chp && chp[0]) {
670 chp = strchr(chp, '/');
671 if (chp) {
672 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800673 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
674 ALOGI("Creating directory %s\n", path);
675 if (mkdir(path, 0770)) { /* drwxrwx--- */
676 ALOGE("Unable to create directory %s: %s\n", path, strerror(errno));
677 } else if (chown(path, AID_SHELL, AID_SHELL)) {
678 ALOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
679 }
680 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700681 *chp++ = '/';
682 }
683 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800684}
685
686/* redirect output to a file */
687void redirect_to_file(FILE *redirect, char *path) {
688 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700689
Felipe Leme608385d2016-02-01 10:35:38 -0800690 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800691 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700692 if (fd < 0) {
693 fprintf(stderr, "%s: %s\n", path, strerror(errno));
694 exit(1);
695 }
696
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800697 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700698 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700699}
700
Jeff Brownbf7f4922012-06-07 16:40:01 -0700701static bool should_dump_native_traces(const char* path) {
702 for (const char** p = native_processes_to_dump; *p; p++) {
703 if (!strcmp(*p, path)) {
704 return true;
705 }
706 }
707 return false;
708}
709
710/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
711const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -0800712 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Leme93d705b2015-11-10 20:10:25 -0800713 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700714 const char* result = NULL;
715
Colin Crossf45fa6b2012-03-26 12:38:26 -0700716 char traces_path[PROPERTY_VALUE_MAX] = "";
717 property_get("dalvik.vm.stack-trace-file", traces_path, "");
718 if (!traces_path[0]) return NULL;
719
720 /* move the old traces.txt (if any) out of the way temporarily */
721 char anr_traces_path[PATH_MAX];
722 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
723 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
724 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
725 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
726 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
727 }
728
Colin Crossf45fa6b2012-03-26 12:38:26 -0700729 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700730 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 -0800731 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700732 if (fd < 0) {
733 fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
734 return NULL;
735 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700736 int chmod_ret = fchmod(fd, 0666);
737 if (chmod_ret < 0) {
738 fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
739 close(fd);
740 return NULL;
741 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700742
Felipe Leme8620bb42015-11-10 11:04:45 -0800743 /* Variables below must be initialized before 'goto' statements */
744 int dalvik_found = 0;
745 int ifd, wfd = -1;
746
Colin Crossf45fa6b2012-03-26 12:38:26 -0700747 /* walk /proc and kill -QUIT all Dalvik processes */
748 DIR *proc = opendir("/proc");
749 if (proc == NULL) {
750 fprintf(stderr, "/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700751 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700752 }
753
754 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -0800755 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700756 if (ifd < 0) {
757 fprintf(stderr, "inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700758 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700759 }
760
Felipe Leme8620bb42015-11-10 11:04:45 -0800761 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700762 if (wfd < 0) {
763 fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700764 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700765 }
766
767 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700768 while ((d = readdir(proc))) {
769 int pid = atoi(d->d_name);
770 if (pid <= 0) continue;
771
Jeff Brownbf7f4922012-06-07 16:40:01 -0700772 char path[PATH_MAX];
773 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700774 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700775 ssize_t len = readlink(path, data, sizeof(data) - 1);
776 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700777 continue;
778 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700779 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700780
Colin Cross0d6180f2014-07-16 19:00:46 -0700781 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700782 /* skip zygote -- it won't dump its stack anyway */
783 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700784 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700785 len = read(cfd, data, sizeof(data) - 1);
786 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700787 if (len <= 0) {
788 continue;
789 }
790 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700791 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700792 continue;
793 }
794
795 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -0800796 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700797 if (kill(pid, SIGQUIT)) {
798 fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
799 continue;
800 }
801
802 /* wait for the writable-close notification from inotify */
803 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -0700804 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -0700805 if (ret < 0) {
806 fprintf(stderr, "poll: %s\n", strerror(errno));
807 } else if (ret == 0) {
808 fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
809 } else {
810 struct inotify_event ie;
811 read(ifd, &ie, sizeof(ie));
812 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700813
814 if (lseek(fd, 0, SEEK_END) < 0) {
815 fprintf(stderr, "lseek: %s\n", strerror(errno));
816 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800817 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -0800818 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700819 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700820 } else if (should_dump_native_traces(data)) {
821 /* dump native process if appropriate */
822 if (lseek(fd, 0, SEEK_END) < 0) {
823 fprintf(stderr, "lseek: %s\n", strerror(errno));
824 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800825 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800826 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800827
828 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
829 if (timeout_failures == 3) {
830 dprintf(fd, "too many stack dump failures, skipping...\n");
831 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
832 dprintf(fd, "dumping failed, likely due to a timeout\n");
833 timeout_failures++;
834 } else {
835 timeout_failures = 0;
836 }
837 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -0800838 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700839 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700840 }
841 }
842
Colin Crossf45fa6b2012-03-26 12:38:26 -0700843 if (dalvik_found == 0) {
844 fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
845 }
846
847 static char dump_traces_path[PATH_MAX];
848 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
849 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
850 if (rename(traces_path, dump_traces_path)) {
851 fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700852 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700853 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700854 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700855
856 /* replace the saved [ANR] traces.txt file */
857 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700858
859error_close_ifd:
860 close(ifd);
861error_close_fd:
862 close(fd);
863 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700864}
865
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700866void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800867 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -0800868 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700869 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
870 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700871 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700872 if (!fp) {
873 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
874 return;
875 }
876 char table[16];
877 // Each line has an integer (the table number), a space, and a string (the table name). We only
878 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
879 // Add a fixed max limit so this doesn't go awry.
880 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
881 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
882 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
883 }
884 fclose(fp);
885}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800886
887/* overall progress */
888int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -0800889int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -0800890int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800891
892// TODO: make this function thread safe if sections are generated in parallel.
893void update_progress(int delta) {
894 if (!do_update_progress) return;
895
896 progress += delta;
897
898 char key[PROPERTY_KEY_MAX];
899 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -0800900
901 // adjusts max on the fly
902 if (progress > weight_total) {
903 int new_total = weight_total * 1.2;
904 fprintf(stderr, "Adjusting total weight from %d to %d\n", weight_total, new_total);
905 weight_total = new_total;
906 sprintf(key, "dumpstate.%d.max", getpid());
907 sprintf(value, "%d", weight_total);
908 int status = property_set(key, value);
909 if (status) {
910 ALOGW("Could not update max weight by setting system property %s to %s: %d\n",
911 key, value, status);
912 }
913 }
914
Felipe Leme71bbfc52015-11-23 14:14:51 -0800915 sprintf(key, "dumpstate.%d.progress", getpid());
916 sprintf(value, "%d", progress);
917
918 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
919 // directly for debuggging.
Felipe Lemead5f6c42015-11-30 14:26:46 -0800920 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800921
922 int status = property_set(key, value);
923 if (status) {
924 ALOGW("Could not update progress by setting system property %s to %s: %d\n",
925 key, value, status);
926 }
927}
Felipe Lemee338bf62015-12-07 14:03:50 -0800928
Felipe Leme3634a1e2015-12-09 10:11:47 -0800929void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -0800930 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
931 run_command_always(NULL, 10, args);
932}
Mark Salyzynf55d4022015-12-11 07:32:31 -0800933
Felipe Leme0c80cf02016-01-05 13:25:34 -0800934void vibrate(FILE* vibrator, int ms) {
935 fprintf(vibrator, "%d\n", ms);
936 fflush(vibrator);
937}
938
939bool is_dir(const char* pathname) {
940 struct stat info;
941 if (stat(pathname, &info) == -1) {
942 return false;
943 }
944 return S_ISDIR(info.st_mode);
945}
946
947time_t get_mtime(int fd, time_t default_mtime) {
948 struct stat info;
949 if (fstat(fd, &info) == -1) {
950 return default_mtime;
951 }
952 return info.st_mtime;
953}
954
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800955void dump_emmc_ecsd(const char *ext_csd_path) {
956 static const size_t EXT_CSD_REV = 192;
957 static const size_t EXT_PRE_EOL_INFO = 267;
958 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
959 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
960 struct hex {
961 char str[2];
962 } buffer[512];
963 int fd, ext_csd_rev, ext_pre_eol_info;
964 ssize_t bytes_read;
965 static const char *ver_str[] = {
966 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
967 };
968 static const char *eol_str[] = {
969 "Undefined",
970 "Normal",
971 "Warning (consumed 80% of reserve)",
Mark Salyzyn4b45d672015-12-11 10:41:52 -0800972 "Urgent (consumed 90% of reserve)"
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800973 };
974
975 printf("------ %s Extended CSD ------\n", ext_csd_path);
976
977 fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
978 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
979 if (fd < 0) {
980 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
981 return;
982 }
983
984 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
985 close(fd);
986 if (bytes_read < 0) {
987 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
988 return;
989 }
Mark Salyzyn4b45d672015-12-11 10:41:52 -0800990 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800991 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
992 return;
993 }
994
995 ext_csd_rev = 0;
996 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
997 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
998 ext_csd_path, buffer[EXT_CSD_REV].str);
999 return;
1000 }
1001
1002 printf("rev 1.%d (MMC %s)\n",
1003 ext_csd_rev,
1004 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1005 ver_str[ext_csd_rev] :
1006 "Unknown");
1007 if (ext_csd_rev < 7) {
1008 printf("\n");
1009 return;
1010 }
1011
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001012 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001013 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1014 return;
1015 }
1016
1017 ext_pre_eol_info = 0;
1018 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1019 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1020 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1021 return;
1022 }
1023 printf("PRE_EOL_INFO %d (MMC %s)\n",
1024 ext_pre_eol_info,
1025 eol_str[(ext_pre_eol_info < (int)
1026 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1027 ext_pre_eol_info : 0]);
1028
1029 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1030 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1031 ++lifetime) {
1032 int ext_device_life_time_est;
1033 static const char *est_str[] = {
1034 "Undefined",
1035 "0-10% of device lifetime used",
1036 "10-20% of device lifetime used",
1037 "20-30% of device lifetime used",
1038 "30-40% of device lifetime used",
1039 "40-50% of device lifetime used",
1040 "50-60% of device lifetime used",
1041 "60-70% of device lifetime used",
1042 "70-80% of device lifetime used",
1043 "80-90% of device lifetime used",
1044 "90-100% of device lifetime used",
1045 "Exceeded the maximum estimated device lifetime",
1046 };
1047
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001048 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001049 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1050 break;
1051 }
1052
1053 ext_device_life_time_est = 0;
1054 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1055 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1056 ext_csd_path,
1057 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1058 buffer[lifetime].str);
1059 continue;
1060 }
1061 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1062 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1063 ext_device_life_time_est,
1064 est_str[(ext_device_life_time_est < (int)
1065 (sizeof(est_str) / sizeof(est_str[0]))) ?
1066 ext_device_life_time_est : 0]);
1067 }
1068
1069 printf("\n");
1070}