blob: da4b5add3e225a286cce3cd1c20ccdacfff414fa [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>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080028#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070029#include <sys/inotify.h>
30#include <sys/stat.h>
Mark Salyzyna297c322016-02-05 15:33:17 -080031#include <sys/sysconf.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/time.h>
33#include <sys/wait.h>
34#include <sys/klog.h>
35#include <time.h>
36#include <unistd.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080037#include <vector>
John Michelaue7b6cf12013-03-07 15:35:35 -060038#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070039
Felipe Leme71bbfc52015-11-23 14:14:51 -080040#define LOG_TAG "dumpstate"
Jeff Brownbf7f4922012-06-07 16:40:01 -070041#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080042#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070043#include <cutils/properties.h>
44#include <cutils/sockets.h>
45#include <private/android_filesystem_config.h>
46
Robert Craig95798372013-04-04 06:33:10 -040047#include <selinux/android.h>
48
Colin Crossf45fa6b2012-03-26 12:38:26 -070049#include "dumpstate.h"
50
Jeff Brown1dc94e32014-09-11 14:15:27 -070051static const int64_t NANOS_PER_SEC = 1000000000;
52
Jeff Brownbf7f4922012-06-07 16:40:01 -070053/* list of native processes to include in the native dumps */
54static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080055 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080056 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070057 "/system/bin/drmserver",
Jeff Brownbf7f4922012-06-07 16:40:01 -070058 "/system/bin/mediaserver",
59 "/system/bin/sdcard",
60 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070061 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070062 NULL,
63};
64
Felipe Leme608385d2016-02-01 10:35:38 -080065DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
66
67DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme78f2c862015-12-21 09:55:22 -080068 title_ = title;
69 if (title) {
70 started_ = DurationReporter::nanotime();
71 }
Felipe Leme608385d2016-02-01 10:35:38 -080072 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -080073}
74
75DurationReporter::~DurationReporter() {
76 if (title_) {
77 uint64_t elapsed = DurationReporter::nanotime() - started_;
78 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme608385d2016-02-01 10:35:38 -080079 if (out_) {
80 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
81 (float) elapsed / NANOS_PER_SEC, title_);
82 } else {
Felipe Lemecbce55d2016-02-08 09:53:18 -080083 MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -080084 }
Felipe Leme78f2c862015-12-21 09:55:22 -080085 }
86}
87
88uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080089 struct timespec ts;
90 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080091 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080092}
93
John Spurlock5ecd4be2014-01-29 14:14:40 -050094void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -080095 ON_DRY_RUN_RETURN();
John Spurlock5ecd4be2014-01-29 14:14:40 -050096 DIR *d;
97 struct dirent *de;
98
99 if (header) printf("\n------ %s ------\n", header);
100 func(0);
101
102 if (!(d = opendir("/data/system/users"))) {
103 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
104 return;
105 }
106
107 while ((de = readdir(d))) {
108 int userid;
109 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
110 continue;
111 }
112 func(userid);
113 }
114
115 closedir(d);
116}
117
Colin Cross0c22e8b2012-11-02 15:46:56 -0700118static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700119 DIR *d;
120 struct dirent *de;
121
122 if (!(d = opendir("/proc"))) {
123 printf("Failed to open /proc (%s)\n", strerror(errno));
124 return;
125 }
126
Felipe Leme635ca312016-01-05 14:23:02 -0800127 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700128 while ((de = readdir(d))) {
129 int pid;
130 int fd;
131 char cmdpath[255];
132 char cmdline[255];
133
134 if (!(pid = atoi(de->d_name))) {
135 continue;
136 }
137
Colin Crossf45fa6b2012-03-26 12:38:26 -0700138 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyna297c322016-02-05 15:33:17 -0800139
140 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
141 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
142 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700143 close(fd);
Mark Salyzyna297c322016-02-05 15:33:17 -0800144 if (cmdline[0]) {
145 helper(pid, cmdline, arg);
146 continue;
147 }
148 }
149
150 // if no cmdline, a kernel thread has comm
151 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
152 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
153 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
154 close(fd);
155 if (cmdline[1]) {
156 cmdline[0] = '[';
157 size_t len = strcspn(cmdline, "\f\b\r\n");
158 cmdline[len] = ']';
159 cmdline[len+1] = '\0';
160 }
161 }
162 if (!cmdline[0]) {
163 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700164 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700165 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700166 }
167
168 closedir(d);
169}
170
Colin Cross0c22e8b2012-11-02 15:46:56 -0700171static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800172 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700173 func(pid, cmdline);
174}
175
176void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800177 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800178 __for_each_pid(for_each_pid_helper, header, (void *)func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700179}
180
181static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
182 DIR *d;
183 struct dirent *de;
184 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800185 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700186
187 sprintf(taskpath, "/proc/%d/task", pid);
188
189 if (!(d = opendir(taskpath))) {
190 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
191 return;
192 }
193
194 func(pid, pid, cmdline);
195
196 while ((de = readdir(d))) {
197 int tid;
198 int fd;
199 char commpath[255];
200 char comm[255];
201
202 if (!(tid = atoi(de->d_name))) {
203 continue;
204 }
205
206 if (tid == pid)
207 continue;
208
209 sprintf(commpath,"/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800210 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700211 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700212 strcpy(comm, "N/A");
213 } else {
214 char *c;
Mark Salyzyna297c322016-02-05 15:33:17 -0800215 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700216 close(fd);
217
218 c = strrchr(comm, '\n');
219 if (c) {
220 *c = '\0';
221 }
222 }
223 func(pid, tid, comm);
224 }
225
226 closedir(d);
227}
228
229void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800230 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800231 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700232}
233
234void show_wchan(int pid, int tid, const char *name) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800235 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700236 char path[255];
237 char buffer[255];
Mark Salyzyna297c322016-02-05 15:33:17 -0800238 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700239 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700240
241 memset(buffer, 0, sizeof(buffer));
242
Colin Cross0c22e8b2012-11-02 15:46:56 -0700243 sprintf(path, "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700244 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700245 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
246 return;
247 }
248
Mark Salyzyna297c322016-02-05 15:33:17 -0800249 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
250 save_errno = errno;
251 close(fd);
252
253 if (ret < 0) {
254 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
255 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700256 }
257
Colin Cross0c22e8b2012-11-02 15:46:56 -0700258 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
259 pid == tid ? 0 : 3, "", name);
260
261 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700262
Mark Salyzyna297c322016-02-05 15:33:17 -0800263 return;
264}
265
266// print time in centiseconds
267static void snprcent(char *buffer, size_t len, size_t spc,
268 unsigned long long time) {
269 static long hz; // cache discovered hz
270
271 if (hz <= 0) {
272 hz = sysconf(_SC_CLK_TCK);
273 if (hz <= 0) {
274 hz = 1000;
275 }
276 }
277
278 // convert to centiseconds
279 time = (time * 100 + (hz / 2)) / hz;
280
281 char str[16];
282
283 snprintf(str, sizeof(str), " %llu.%02u",
284 time / 100, (unsigned)(time % 100));
285 size_t offset = strlen(buffer);
286 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
287 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
288}
289
290// print permille as a percent
291static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
292 char str[16];
293
294 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
295 size_t offset = strlen(buffer);
296 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
297 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
298}
299
300void show_showtime(int pid, const char *name) {
301 ON_DRY_RUN_RETURN();
302 char path[255];
303 char buffer[1023];
304 int fd, ret, save_errno;
305
306 memset(buffer, 0, sizeof(buffer));
307
308 sprintf(path, "/proc/%d/stat", pid);
309 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
310 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
311 return;
312 }
313
314 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
315 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700316 close(fd);
Mark Salyzyna297c322016-02-05 15:33:17 -0800317
318 if (ret < 0) {
319 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
320 return;
321 }
322
323 // field 14 is utime
324 // field 15 is stime
325 // field 42 is iotime
326 unsigned long long utime = 0, stime = 0, iotime = 0;
327 if (sscanf(buffer,
Xia Yang60292e52016-02-16 03:05:18 -0800328 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
329 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
330 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
331 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyna297c322016-02-05 15:33:17 -0800332 &utime, &stime, &iotime) != 3) {
333 return;
334 }
335
336 unsigned long long total = utime + stime;
337 if (!total) {
338 return;
339 }
340
341 unsigned permille = (iotime * 1000 + (total / 2)) / total;
342 if (permille > 1000) {
343 permille = 1000;
344 }
345
346 // try to beautify and stabilize columns at <80 characters
347 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
348 if ((name[0] != '[') || utime) {
349 snprcent(buffer, sizeof(buffer), 57, utime);
350 }
351 snprcent(buffer, sizeof(buffer), 65, stime);
352 if ((name[0] != '[') || iotime) {
353 snprcent(buffer, sizeof(buffer), 73, iotime);
354 }
355 if (iotime) {
356 snprdec(buffer, sizeof(buffer), 79, permille);
357 }
358 puts(buffer); // adds a trailing newline
359
Colin Crossf45fa6b2012-03-26 12:38:26 -0700360 return;
361}
362
363void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800364 const char *title = "KERNEL LOG (dmesg)";
365 DurationReporter duration_reporter(title);
366 printf("------ %s ------\n", title);
367
Felipe Leme93d705b2015-11-10 20:10:25 -0800368 ON_DRY_RUN_RETURN();
Elliott Hughes5f87b312012-09-17 11:43:40 -0700369 /* Get size of kernel buffer */
370 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700371 if (size <= 0) {
372 printf("Unexpected klogctl return value: %d\n\n", size);
373 return;
374 }
375 char *buf = (char *) malloc(size + 1);
376 if (buf == NULL) {
377 printf("memory allocation failed\n\n");
378 return;
379 }
380 int retval = klogctl(KLOG_READ_ALL, buf, size);
381 if (retval < 0) {
382 printf("klogctl failure\n\n");
383 free(buf);
384 return;
385 }
386 buf[retval] = '\0';
387 printf("%s\n\n", buf);
388 free(buf);
389 return;
390}
391
392void do_showmap(int pid, const char *name) {
393 char title[255];
394 char arg[255];
395
396 sprintf(title, "SHOW MAP %d (%s)", pid, name);
397 sprintf(arg, "%d", pid);
Felipe Leme3dba69a2016-03-17 14:59:13 -0700398 run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700399}
400
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800401static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700402 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800403 printf("------ %s (%s", title, path);
404
Colin Crossf45fa6b2012-03-26 12:38:26 -0700405 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800406 // Only show the modification time of non-device files.
407 size_t path_len = strlen(path);
408 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
409 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
410 (path_len < 3 || memcmp(path, "/d/", 3)) &&
411 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700412 char stamp[80];
413 time_t mtime = st.st_mtime;
414 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
415 printf(": %s", stamp);
416 }
417 printf(") ------\n");
418 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800419 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
Colin Crossf45fa6b2012-03-26 12:38:26 -0700420
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800421 bool newline = false;
422 fd_set read_set;
423 struct timeval tm;
424 while (1) {
425 FD_ZERO(&read_set);
426 FD_SET(fd, &read_set);
427 /* Timeout if no data is read for 30 seconds. */
428 tm.tv_sec = 30;
429 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800430 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800431 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
432 if (ret == -1) {
433 printf("*** %s: select failed: %s\n", path, strerror(errno));
434 newline = true;
435 break;
436 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800437 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800438 printf("*** %s: Timed out after %.3fs\n", path,
439 (float) elapsed / NANOS_PER_SEC);
440 newline = true;
441 break;
442 } else {
443 char buffer[65536];
444 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
445 if (bytes_read > 0) {
446 fwrite(buffer, bytes_read, 1, stdout);
447 newline = (buffer[bytes_read-1] == '\n');
448 } else {
449 if (bytes_read == -1) {
450 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
451 newline = true;
452 }
453 break;
454 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700455 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700456 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800457 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700458 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700459
Colin Crossf45fa6b2012-03-26 12:38:26 -0700460 if (!newline) printf("\n");
461 if (title) printf("\n");
462 return 0;
463}
464
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800465/* prints the contents of a file */
466int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800467 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800468 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
469 if (fd < 0) {
470 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800471 printf("*** %s: %s\n", path, strerror(err));
472 if (title) printf("\n");
473 return -1;
474 }
475 return _dump_file_from_fd(title, path, fd);
476}
477
Felipe Leme71a74ac2016-03-17 15:43:25 -0700478int read_file_as_long(const char *path, long int *output) {
479 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
480 if (fd < 0) {
481 int err = errno;
482 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
483 return -1;
484 }
485 char buffer[50];
486 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
487 if (bytes_read == -1) {
488 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
489 return -2;
490 }
491 if (bytes_read == 0) {
492 MYLOGE("File %s is empty\n", path);
493 return -3;
494 }
495 *output = atoi(buffer);
496 return 0;
497}
498
Mark Salyzyn326842f2015-04-30 09:49:41 -0700499/* calls skip to gate calling dump_from_fd recursively
500 * in the specified directory. dump_from_fd defaults to
501 * dump_file_from_fd above when set to NULL. skip defaults
502 * to false when set to NULL. dump_from_fd will always be
503 * called with title NULL.
504 */
505int dump_files(const char *title, const char *dir,
506 bool (*skip)(const char *path),
507 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800508 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700509 DIR *dirp;
510 struct dirent *d;
511 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800512 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700513 int fd, retval = 0;
514
515 if (title) {
516 printf("------ %s (%s) ------\n", title, dir);
517 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800518 ON_DRY_RUN_RETURN(0);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700519
520 if (dir[strlen(dir) - 1] == '/') {
521 ++slash;
522 }
523 dirp = opendir(dir);
524 if (dirp == NULL) {
525 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800526 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700527 return retval;
528 }
529
530 if (!dump_from_fd) {
531 dump_from_fd = dump_file_from_fd;
532 }
533 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
534 if ((d->d_name[0] == '.')
535 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
536 || (d->d_name[1] == '\0'))) {
537 continue;
538 }
539 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
540 (d->d_type == DT_DIR) ? "/" : "");
541 if (!newpath) {
542 retval = -errno;
543 continue;
544 }
545 if (skip && (*skip)(newpath)) {
546 continue;
547 }
548 if (d->d_type == DT_DIR) {
549 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
550 if (ret < 0) {
551 retval = ret;
552 }
553 continue;
554 }
555 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
556 if (fd < 0) {
557 retval = fd;
558 printf("*** %s: %s\n", newpath, strerror(errno));
559 continue;
560 }
561 (*dump_from_fd)(NULL, newpath, fd);
562 }
563 closedir(dirp);
564 if (title) {
565 printf("\n");
566 }
567 return retval;
568}
569
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800570/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
571 * it's possible to avoid issues where opening the file itself can get
572 * stuck.
573 */
574int dump_file_from_fd(const char *title, const char *path, int fd) {
575 int flags = fcntl(fd, F_GETFL);
576 if (flags == -1) {
577 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800578 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800579 return -1;
580 } else if (!(flags & O_NONBLOCK)) {
581 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800582 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800583 return -1;
584 }
585 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700586}
587
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800588bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
589 sigset_t child_mask, old_mask;
590 sigemptyset(&child_mask);
591 sigaddset(&child_mask, SIGCHLD);
592
593 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
594 printf("*** sigprocmask failed: %s\n", strerror(errno));
595 return false;
596 }
597
598 struct timespec ts;
599 ts.tv_sec = timeout_seconds;
600 ts.tv_nsec = 0;
601 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
602 int saved_errno = errno;
603 // Set the signals back the way they were.
604 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
605 printf("*** sigprocmask failed: %s\n", strerror(errno));
606 if (ret == 0) {
607 return false;
608 }
609 }
610 if (ret == -1) {
611 errno = saved_errno;
612 if (errno == EAGAIN) {
613 errno = ETIMEDOUT;
614 } else {
615 printf("*** sigtimedwait failed: %s\n", strerror(errno));
616 }
617 return false;
618 }
619
620 pid_t child_pid = waitpid(pid, status, WNOHANG);
621 if (child_pid != pid) {
622 if (child_pid != -1) {
623 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
624 } else {
625 printf("*** waitpid failed: %s\n", strerror(errno));
626 }
627 return false;
628 }
629 return true;
630}
631
Felipe Lemea34efb72016-03-11 09:33:32 -0800632// TODO: refactor all those commands that convert args
633void format_args(const char* command, const char *args[], std::string *string);
634
Colin Crossf45fa6b2012-03-26 12:38:26 -0700635int run_command(const char *title, int timeout_seconds, const char *command, ...) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800636 DurationReporter duration_reporter(title);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700637 fflush(stdout);
Felipe Leme93d705b2015-11-10 20:10:25 -0800638
639 const char *args[1024] = {command};
640 size_t arg;
641 va_list ap;
642 va_start(ap, command);
643 if (title) printf("------ %s (%s", title, command);
Felipe Lemea34efb72016-03-11 09:33:32 -0800644 bool null_terminated = false;
Felipe Leme93d705b2015-11-10 20:10:25 -0800645 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
646 args[arg] = va_arg(ap, const char *);
Felipe Lemea34efb72016-03-11 09:33:32 -0800647 if (args[arg] == nullptr) {
648 null_terminated = true;
649 break;
650 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700651 // TODO: null_terminated check is not really working; line below would crash dumpstate if
652 // nullptr is missing
Felipe Leme93d705b2015-11-10 20:10:25 -0800653 if (title) printf(" %s", args[arg]);
654 }
655 if (title) printf(") ------\n");
656 fflush(stdout);
Felipe Lemea34efb72016-03-11 09:33:32 -0800657 if (!null_terminated) {
658 // Fail now, otherwise execvp() call on run_command_always() might hang.
659 std::string cmd;
660 format_args(command, args, &cmd);
661 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
662 return -1;
663 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800664
Felipe Leme71bbfc52015-11-23 14:14:51 -0800665 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
Felipe Leme93d705b2015-11-10 20:10:25 -0800666
Felipe Leme29c39712016-04-01 10:02:00 -0700667 int status = run_command_always(title, DONT_DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800668 va_end(ap);
669 return status;
670}
671
672int run_command_as_shell(const char *title, int timeout_seconds, const char *command, ...) {
673 DurationReporter duration_reporter(title);
674 fflush(stdout);
675
676 const char *args[1024] = {command};
677 size_t arg;
678 va_list ap;
679 va_start(ap, command);
680 if (title) printf("------ %s (%s", title, command);
681 bool null_terminated = false;
682 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
683 args[arg] = va_arg(ap, const char *);
684 if (args[arg] == nullptr) {
685 null_terminated = true;
686 break;
687 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700688 // TODO: null_terminated check is not really working; line below would crash dumpstate if
689 // nullptr is missing
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800690 if (title) printf(" %s", args[arg]);
691 }
692 if (title) printf(") ------\n");
693 fflush(stdout);
694 if (!null_terminated) {
695 // Fail now, otherwise execvp() call on run_command_always() might hang.
696 std::string cmd;
697 format_args(command, args, &cmd);
698 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
699 return -1;
700 }
701
702 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
703
Felipe Leme29c39712016-04-01 10:02:00 -0700704 int status = run_command_always(title, DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800705 va_end(ap);
706 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800707}
708
709/* forks a command and waits for it to finish */
Felipe Leme29c39712016-04-01 10:02:00 -0700710int run_command_always(const char *title, RootMode root_mode, StdoutMode stdout_mode,
711 int timeout_seconds, const char *args[]) {
712 bool silent = (stdout_mode == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700713 // TODO: need to check if args is null-terminated, otherwise execvp will crash dumpstate
714
Felipe Leme71bbfc52015-11-23 14:14:51 -0800715 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
716 * It's a good approximation for most cases, except when calling dumpsys, where its weight
717 * should be much higher proportionally to its timeout. */
718 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800719
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800720 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800721 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700722 pid_t pid = fork();
723
724 /* handle error case */
725 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700726 if (!silent) printf("*** fork: %s\n", strerror(errno));
727 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700728 return pid;
729 }
730
731 /* handle child case */
732 if (pid == 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700733 if (root_mode == DROP_ROOT && !drop_root_user()) {
734 if (!silent) printf("*** fail todrop root before running %s: %s\n", command,
735 strerror(errno));
736 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700737 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800738 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700739
Felipe Leme29c39712016-04-01 10:02:00 -0700740 if (silent) {
741 // Redirect stderr to stdout
742 dup2(STDERR_FILENO, STDOUT_FILENO);
743 }
744
John Michelaue7b6cf12013-03-07 15:35:35 -0600745 /* make sure the child dies when dumpstate dies */
746 prctl(PR_SET_PDEATHSIG, SIGKILL);
747
Andres Morales2e671bb2014-08-21 12:38:22 -0700748 /* just ignore SIGPIPE, will go down with parent's */
749 struct sigaction sigact;
750 memset(&sigact, 0, sizeof(sigact));
751 sigact.sa_handler = SIG_IGN;
752 sigaction(SIGPIPE, &sigact, NULL);
753
Colin Crossf45fa6b2012-03-26 12:38:26 -0700754 execvp(command, (char**) args);
Felipe Lemeea160d12016-03-24 11:29:44 -0700755 // execvp's result will be handled after waitpid_with_timeout() below, but if it failed,
756 // it's safer to exit dumpstate.
757 MYLOGD("execvp on command '%s' failed (error: %s)", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700758 fflush(stdout);
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700759 // Must call _exit (instead of exit), otherwise it will corrupt the zip file.
760 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700761 }
762
763 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800764 int status;
765 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800766 uint64_t elapsed = DurationReporter::nanotime() - start;
Felipe Lemea34efb72016-03-11 09:33:32 -0800767 std::string cmd; // used to log command and its args
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800768 if (!ret) {
769 if (errno == ETIMEDOUT) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800770 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700771 if (!silent) printf("*** command '%s' timed out after %.3fs (killing pid %d)\n",
772 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800773 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800774 (float) elapsed / NANOS_PER_SEC, pid);
775 } else {
Felipe Lemea34efb72016-03-11 09:33:32 -0800776 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700777 if (!silent) printf("*** command '%s': Error after %.4fs (killing pid %d)\n",
778 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800779 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800780 (float) elapsed / NANOS_PER_SEC, pid);
781 }
782 kill(pid, SIGTERM);
783 if (!waitpid_with_timeout(pid, 5, NULL)) {
784 kill(pid, SIGKILL);
785 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700786 if (!silent) printf("could not kill command '%s' (pid %d) even with SIGKILL.\n",
787 command, pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700788 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700789 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700790 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800791 return -1;
Felipe Lemea34efb72016-03-11 09:33:32 -0800792 } else if (status) {
793 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700794 if (!silent) printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
Felipe Lemea34efb72016-03-11 09:33:32 -0800795 MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
796 return -2;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700797 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800798
799 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700800 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
801 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800802 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700803 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
804 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800805 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800806
Felipe Leme71bbfc52015-11-23 14:14:51 -0800807 if (weight > 0) {
808 update_progress(weight);
809 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800810 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700811}
812
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800813bool drop_root_user() {
814 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
815 MYLOGD("drop_root_user(): already running as Shell");
816 return true;
817 }
818 /* ensure we will keep capabilities when we drop root */
819 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
820 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
821 return false;
822 }
823
824 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
825 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC };
826 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
827 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
828 return false;
829 }
830 if (setgid(AID_SHELL) != 0) {
831 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
832 return false;
833 }
834 if (setuid(AID_SHELL) != 0) {
835 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
836 return false;
837 }
838
839 struct __user_cap_header_struct capheader;
840 struct __user_cap_data_struct capdata[2];
841 memset(&capheader, 0, sizeof(capheader));
842 memset(&capdata, 0, sizeof(capdata));
843 capheader.version = _LINUX_CAPABILITY_VERSION_3;
844 capheader.pid = 0;
845
846 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
847 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
848 capdata[0].inheritable = 0;
849 capdata[1].inheritable = 0;
850
851 if (capset(&capheader, &capdata[0]) < 0) {
852 MYLOGE("capset failed: %s\n", strerror(errno));
853 return false;
854 }
855
856 return true;
857}
858
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800859void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
860 if (args.size() > 1000) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800861 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800862 return;
863 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800864 const char *am_args[1024] = { "/system/bin/am", "broadcast", "--user", "0", "-a",
865 action.c_str() };
866 size_t am_index = 5; // Starts at the index of last initial value above.
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800867 for (const std::string& arg : args) {
868 am_args[++am_index] = arg.c_str();
869 }
870 // Always terminate with NULL.
871 am_args[am_index + 1] = NULL;
Felipe Lemea34efb72016-03-11 09:33:32 -0800872 std::string args_string;
873 format_args(am_index + 1, am_args, &args_string);
874 MYLOGD("send_broadcast command: %s\n", args_string.c_str());
Felipe Leme29c39712016-04-01 10:02:00 -0700875 run_command_always(NULL, DROP_ROOT, REDIRECT_TO_STDERR, 20, am_args);
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800876}
877
Colin Crossf45fa6b2012-03-26 12:38:26 -0700878size_t num_props = 0;
879static char* props[2000];
880
881static void print_prop(const char *key, const char *name, void *user) {
882 (void) user;
883 if (num_props < sizeof(props) / sizeof(props[0])) {
884 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
885 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
886 props[num_props++] = strdup(buf);
887 }
888}
889
890static int compare_prop(const void *a, const void *b) {
891 return strcmp(*(char * const *) a, *(char * const *) b);
892}
893
894/* prints all the system properties */
895void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800896 const char* title = "SYSTEM PROPERTIES";
897 DurationReporter duration_reporter(title);
898 printf("------ %s ------\n", title);
Felipe Leme93d705b2015-11-10 20:10:25 -0800899 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700900 size_t i;
901 num_props = 0;
902 property_list(print_prop, NULL);
903 qsort(&props, num_props, sizeof(props[0]), compare_prop);
904
Colin Crossf45fa6b2012-03-26 12:38:26 -0700905 for (i = 0; i < num_props; ++i) {
906 fputs(props[i], stdout);
907 free(props[i]);
908 }
909 printf("\n");
910}
911
Felipe Leme2628e9e2016-04-12 16:36:51 -0700912int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700913 int s = android_get_control_socket(service);
914 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800915 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700916 exit(1);
917 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700918 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700919 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800920 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700921 exit(1);
922 }
923
924 struct sockaddr addr;
925 socklen_t alen = sizeof(addr);
926 int fd = accept(s, &addr, &alen);
927 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800928 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700929 exit(1);
930 }
931
Felipe Leme2628e9e2016-04-12 16:36:51 -0700932 return fd;
933}
934
935/* redirect output to a service control socket */
936void redirect_to_socket(FILE *redirect, const char *service) {
937 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700938 fflush(redirect);
939 dup2(fd, fileno(redirect));
940 close(fd);
941}
942
Felipe Leme2628e9e2016-04-12 16:36:51 -0700943// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800944void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800945 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700946
947 /* skip initial slash */
948 if (chp[0] == '/')
949 chp++;
950
951 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800952 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700953 while (chp && chp[0]) {
954 chp = strchr(chp, '/');
955 if (chp) {
956 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800957 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800958 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800959 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800960 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800961 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800962 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800963 }
964 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700965 *chp++ = '/';
966 }
967 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800968}
969
970/* redirect output to a file */
971void redirect_to_file(FILE *redirect, char *path) {
972 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700973
Felipe Leme608385d2016-02-01 10:35:38 -0800974 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800975 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700976 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800977 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700978 exit(1);
979 }
980
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800981 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700982 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700983}
984
Jeff Brownbf7f4922012-06-07 16:40:01 -0700985static bool should_dump_native_traces(const char* path) {
986 for (const char** p = native_processes_to_dump; *p; p++) {
987 if (!strcmp(*p, path)) {
988 return true;
989 }
990 }
991 return false;
992}
993
994/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
995const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -0800996 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Leme93d705b2015-11-10 20:10:25 -0800997 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700998 const char* result = NULL;
999
Colin Crossf45fa6b2012-03-26 12:38:26 -07001000 char traces_path[PROPERTY_VALUE_MAX] = "";
1001 property_get("dalvik.vm.stack-trace-file", traces_path, "");
1002 if (!traces_path[0]) return NULL;
1003
1004 /* move the old traces.txt (if any) out of the way temporarily */
1005 char anr_traces_path[PATH_MAX];
1006 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
1007 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
1008 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001009 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001010 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
1011 }
1012
Colin Crossf45fa6b2012-03-26 12:38:26 -07001013 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001014 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 -08001015 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001016 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001017 MYLOGE("%s: %s\n", traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001018 return NULL;
1019 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001020 int chmod_ret = fchmod(fd, 0666);
1021 if (chmod_ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001022 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001023 close(fd);
1024 return NULL;
1025 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026
Felipe Leme8620bb42015-11-10 11:04:45 -08001027 /* Variables below must be initialized before 'goto' statements */
1028 int dalvik_found = 0;
1029 int ifd, wfd = -1;
1030
Colin Crossf45fa6b2012-03-26 12:38:26 -07001031 /* walk /proc and kill -QUIT all Dalvik processes */
1032 DIR *proc = opendir("/proc");
1033 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001034 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001035 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001036 }
1037
1038 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001039 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001040 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001041 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001042 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001043 }
1044
Felipe Leme8620bb42015-11-10 11:04:45 -08001045 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001046 if (wfd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001047 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001048 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001049 }
1050
1051 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001052 while ((d = readdir(proc))) {
1053 int pid = atoi(d->d_name);
1054 if (pid <= 0) continue;
1055
Jeff Brownbf7f4922012-06-07 16:40:01 -07001056 char path[PATH_MAX];
1057 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001058 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001059 ssize_t len = readlink(path, data, sizeof(data) - 1);
1060 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001061 continue;
1062 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001063 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001064
Colin Cross0d6180f2014-07-16 19:00:46 -07001065 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001066 /* skip zygote -- it won't dump its stack anyway */
1067 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001068 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001069 len = read(cfd, data, sizeof(data) - 1);
1070 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001071 if (len <= 0) {
1072 continue;
1073 }
1074 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001075 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001076 continue;
1077 }
1078
1079 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -08001080 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001081 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001082 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001083 continue;
1084 }
1085
1086 /* wait for the writable-close notification from inotify */
1087 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -07001088 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -07001089 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001090 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001091 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001092 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001093 } else {
1094 struct inotify_event ie;
1095 read(ifd, &ie, sizeof(ie));
1096 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001097
1098 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001099 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001100 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001101 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001102 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001103 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001104 } else if (should_dump_native_traces(data)) {
1105 /* dump native process if appropriate */
1106 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001107 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001108 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001109 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -08001110 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001111
1112 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1113 if (timeout_failures == 3) {
1114 dprintf(fd, "too many stack dump failures, skipping...\n");
1115 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1116 dprintf(fd, "dumping failed, likely due to a timeout\n");
1117 timeout_failures++;
1118 } else {
1119 timeout_failures = 0;
1120 }
1121 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001122 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001123 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001124 }
1125 }
1126
Colin Crossf45fa6b2012-03-26 12:38:26 -07001127 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001128 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001129 }
1130
1131 static char dump_traces_path[PATH_MAX];
1132 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
1133 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
1134 if (rename(traces_path, dump_traces_path)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001135 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001136 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001137 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001138 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001139
1140 /* replace the saved [ANR] traces.txt file */
1141 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001142
1143error_close_ifd:
1144 close(ifd);
1145error_close_fd:
1146 close(fd);
1147 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001148}
1149
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001150void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001151 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -08001152 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001153 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1154 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001155 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001156 if (!fp) {
1157 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1158 return;
1159 }
1160 char table[16];
1161 // Each line has an integer (the table number), a space, and a string (the table name). We only
1162 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1163 // Add a fixed max limit so this doesn't go awry.
1164 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
1165 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
1166 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
1167 }
1168 fclose(fp);
1169}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001170
1171/* overall progress */
1172int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001173int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001174int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001175
1176// TODO: make this function thread safe if sections are generated in parallel.
1177void update_progress(int delta) {
1178 if (!do_update_progress) return;
1179
1180 progress += delta;
1181
1182 char key[PROPERTY_KEY_MAX];
1183 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001184
1185 // adjusts max on the fly
1186 if (progress > weight_total) {
1187 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001188 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001189 weight_total = new_total;
1190 sprintf(key, "dumpstate.%d.max", getpid());
1191 sprintf(value, "%d", weight_total);
1192 int status = property_set(key, value);
1193 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001194 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001195 key, value, status);
1196 }
1197 }
1198
Felipe Leme71bbfc52015-11-23 14:14:51 -08001199 sprintf(key, "dumpstate.%d.progress", getpid());
1200 sprintf(value, "%d", progress);
1201
Felipe Leme107a05f2016-03-08 15:11:15 -08001202 if (progress % 100 == 0) {
1203 // We don't want to spam logcat, so only log multiples of 100.
1204 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1205 } else {
1206 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1207 // directly for debuggging.
1208 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1209 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001210
1211 int status = property_set(key, value);
1212 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001213 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001214 key, value, status);
1215 }
1216}
Felipe Lemee338bf62015-12-07 14:03:50 -08001217
Felipe Leme3634a1e2015-12-09 10:11:47 -08001218void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -08001219 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
Felipe Leme29c39712016-04-01 10:02:00 -07001220 run_command_always(NULL, DONT_DROP_ROOT, REDIRECT_TO_STDERR, 10, args);
Felipe Lemee338bf62015-12-07 14:03:50 -08001221}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001222
Felipe Leme0c80cf02016-01-05 13:25:34 -08001223void vibrate(FILE* vibrator, int ms) {
1224 fprintf(vibrator, "%d\n", ms);
1225 fflush(vibrator);
1226}
1227
1228bool is_dir(const char* pathname) {
1229 struct stat info;
1230 if (stat(pathname, &info) == -1) {
1231 return false;
1232 }
1233 return S_ISDIR(info.st_mode);
1234}
1235
1236time_t get_mtime(int fd, time_t default_mtime) {
1237 struct stat info;
1238 if (fstat(fd, &info) == -1) {
1239 return default_mtime;
1240 }
1241 return info.st_mtime;
1242}
1243
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001244void dump_emmc_ecsd(const char *ext_csd_path) {
1245 static const size_t EXT_CSD_REV = 192;
1246 static const size_t EXT_PRE_EOL_INFO = 267;
1247 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
1248 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
1249 struct hex {
1250 char str[2];
1251 } buffer[512];
1252 int fd, ext_csd_rev, ext_pre_eol_info;
1253 ssize_t bytes_read;
1254 static const char *ver_str[] = {
1255 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1256 };
1257 static const char *eol_str[] = {
1258 "Undefined",
1259 "Normal",
1260 "Warning (consumed 80% of reserve)",
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001261 "Urgent (consumed 90% of reserve)"
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001262 };
1263
1264 printf("------ %s Extended CSD ------\n", ext_csd_path);
1265
1266 fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
1267 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
1268 if (fd < 0) {
1269 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1270 return;
1271 }
1272
1273 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
1274 close(fd);
1275 if (bytes_read < 0) {
1276 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1277 return;
1278 }
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001279 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001280 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1281 return;
1282 }
1283
1284 ext_csd_rev = 0;
1285 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
1286 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
1287 ext_csd_path, buffer[EXT_CSD_REV].str);
1288 return;
1289 }
1290
1291 printf("rev 1.%d (MMC %s)\n",
1292 ext_csd_rev,
1293 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1294 ver_str[ext_csd_rev] :
1295 "Unknown");
1296 if (ext_csd_rev < 7) {
1297 printf("\n");
1298 return;
1299 }
1300
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001301 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001302 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1303 return;
1304 }
1305
1306 ext_pre_eol_info = 0;
1307 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1308 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1309 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1310 return;
1311 }
1312 printf("PRE_EOL_INFO %d (MMC %s)\n",
1313 ext_pre_eol_info,
1314 eol_str[(ext_pre_eol_info < (int)
1315 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1316 ext_pre_eol_info : 0]);
1317
1318 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1319 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1320 ++lifetime) {
1321 int ext_device_life_time_est;
1322 static const char *est_str[] = {
1323 "Undefined",
1324 "0-10% of device lifetime used",
1325 "10-20% of device lifetime used",
1326 "20-30% of device lifetime used",
1327 "30-40% of device lifetime used",
1328 "40-50% of device lifetime used",
1329 "50-60% of device lifetime used",
1330 "60-70% of device lifetime used",
1331 "70-80% of device lifetime used",
1332 "80-90% of device lifetime used",
1333 "90-100% of device lifetime used",
1334 "Exceeded the maximum estimated device lifetime",
1335 };
1336
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001337 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001338 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1339 break;
1340 }
1341
1342 ext_device_life_time_est = 0;
1343 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1344 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1345 ext_csd_path,
1346 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1347 buffer[lifetime].str);
1348 continue;
1349 }
1350 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1351 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1352 ext_device_life_time_est,
1353 est_str[(ext_device_life_time_est < (int)
1354 (sizeof(est_str) / sizeof(est_str[0]))) ?
1355 ext_device_life_time_est : 0]);
1356 }
1357
1358 printf("\n");
1359}
Felipe Leme88c79332016-02-22 11:06:49 -08001360
Felipe Lemea34efb72016-03-11 09:33:32 -08001361// TODO: refactor all those commands that convert args
1362void format_args(int argc, const char *argv[], std::string *args) {
1363 LOG_ALWAYS_FATAL_IF(args == nullptr);
Felipe Leme88c79332016-02-22 11:06:49 -08001364 for (int i = 0; i < argc; i++) {
Felipe Lemea34efb72016-03-11 09:33:32 -08001365 args->append(argv[i]);
1366 if (i < argc -1) {
1367 args->append(" ");
1368 }
Felipe Leme88c79332016-02-22 11:06:49 -08001369 }
Felipe Lemea34efb72016-03-11 09:33:32 -08001370}
1371void format_args(const char* command, const char *args[], std::string *string) {
1372 LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr);
1373 string->append(command);
1374 if (args[0] == nullptr) return;
1375 string->append(" ");
1376
1377 for (int arg = 1; arg <= 1000; ++arg) {
1378 if (args[arg] == nullptr) return;
1379 string->append(args[arg]);
1380 if (args[arg+1] != nullptr) {
1381 string->append(" ");
1382 }
1383 }
Felipe Lemeea160d12016-03-24 11:29:44 -07001384 // TODO: not really working: if NULL is missing, it will crash dumpstate.
Felipe Lemea34efb72016-03-11 09:33:32 -08001385 MYLOGE("internal error: missing NULL entry on %s", string->c_str());
Felipe Leme88c79332016-02-22 11:06:49 -08001386}