blob: 5396e18dae2a673ebaedf226a9d59c7cfd286237 [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>
31#include <sys/time.h>
32#include <sys/wait.h>
33#include <sys/klog.h>
34#include <time.h>
35#include <unistd.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080036#include <vector>
John Michelaue7b6cf12013-03-07 15:35:35 -060037#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038
Felipe Leme71bbfc52015-11-23 14:14:51 -080039#define LOG_TAG "dumpstate"
Jeff Brownbf7f4922012-06-07 16:40:01 -070040#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080041#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070042#include <cutils/properties.h>
43#include <cutils/sockets.h>
44#include <private/android_filesystem_config.h>
45
Robert Craig95798372013-04-04 06:33:10 -040046#include <selinux/android.h>
47
Colin Crossf45fa6b2012-03-26 12:38:26 -070048#include "dumpstate.h"
49
Jeff Brown1dc94e32014-09-11 14:15:27 -070050static const int64_t NANOS_PER_SEC = 1000000000;
51
Jeff Brownbf7f4922012-06-07 16:40:01 -070052/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070053// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070054static 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",
Andy Hung5c04e742016-04-13 19:35:34 -070058 "/system/bin/mediacodec", // media.codec
59 "/system/bin/mediadrmserver",
60 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070061 "/system/bin/mediaserver",
62 "/system/bin/sdcard",
63 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070064 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070065 NULL,
66};
67
Felipe Leme608385d2016-02-01 10:35:38 -080068DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
69
70DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme78f2c862015-12-21 09:55:22 -080071 title_ = title;
72 if (title) {
73 started_ = DurationReporter::nanotime();
74 }
Felipe Leme608385d2016-02-01 10:35:38 -080075 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -080076}
77
78DurationReporter::~DurationReporter() {
79 if (title_) {
80 uint64_t elapsed = DurationReporter::nanotime() - started_;
81 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme608385d2016-02-01 10:35:38 -080082 if (out_) {
83 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
84 (float) elapsed / NANOS_PER_SEC, title_);
85 } else {
Felipe Lemecbce55d2016-02-08 09:53:18 -080086 MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -080087 }
Felipe Leme78f2c862015-12-21 09:55:22 -080088 }
89}
90
91uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080092 struct timespec ts;
93 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080094 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080095}
96
John Spurlock5ecd4be2014-01-29 14:14:40 -050097void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -080098 ON_DRY_RUN_RETURN();
John Spurlock5ecd4be2014-01-29 14:14:40 -050099 DIR *d;
100 struct dirent *de;
101
102 if (header) printf("\n------ %s ------\n", header);
103 func(0);
104
105 if (!(d = opendir("/data/system/users"))) {
106 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
107 return;
108 }
109
110 while ((de = readdir(d))) {
111 int userid;
112 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
113 continue;
114 }
115 func(userid);
116 }
117
118 closedir(d);
119}
120
Colin Cross0c22e8b2012-11-02 15:46:56 -0700121static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700122 DIR *d;
123 struct dirent *de;
124
125 if (!(d = opendir("/proc"))) {
126 printf("Failed to open /proc (%s)\n", strerror(errno));
127 return;
128 }
129
Felipe Leme635ca312016-01-05 14:23:02 -0800130 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700131 while ((de = readdir(d))) {
132 int pid;
133 int fd;
134 char cmdpath[255];
135 char cmdline[255];
136
137 if (!(pid = atoi(de->d_name))) {
138 continue;
139 }
140
Colin Crossf45fa6b2012-03-26 12:38:26 -0700141 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800142
143 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
144 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
145 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700146 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800147 if (cmdline[0]) {
148 helper(pid, cmdline, arg);
149 continue;
150 }
151 }
152
153 // if no cmdline, a kernel thread has comm
154 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
155 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
156 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
157 close(fd);
158 if (cmdline[1]) {
159 cmdline[0] = '[';
160 size_t len = strcspn(cmdline, "\f\b\r\n");
161 cmdline[len] = ']';
162 cmdline[len+1] = '\0';
163 }
164 }
165 if (!cmdline[0]) {
166 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700167 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700168 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700169 }
170
171 closedir(d);
172}
173
Colin Cross0c22e8b2012-11-02 15:46:56 -0700174static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800175 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700176 func(pid, cmdline);
177}
178
179void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800180 ON_DRY_RUN_RETURN();
Felipe Leme515eb0d2015-12-14 15:09:56 -0800181 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700182}
183
184static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
185 DIR *d;
186 struct dirent *de;
187 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800188 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700189
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700190 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700191
192 if (!(d = opendir(taskpath))) {
193 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
194 return;
195 }
196
197 func(pid, pid, cmdline);
198
199 while ((de = readdir(d))) {
200 int tid;
201 int fd;
202 char commpath[255];
203 char comm[255];
204
205 if (!(tid = atoi(de->d_name))) {
206 continue;
207 }
208
209 if (tid == pid)
210 continue;
211
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700212 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800213 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700214 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700215 strcpy(comm, "N/A");
216 } else {
217 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800218 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700219 close(fd);
220
221 c = strrchr(comm, '\n');
222 if (c) {
223 *c = '\0';
224 }
225 }
226 func(pid, tid, comm);
227 }
228
229 closedir(d);
230}
231
232void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800233 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800234 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700235}
236
237void show_wchan(int pid, int tid, const char *name) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800238 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700239 char path[255];
240 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800241 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700242 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700243
244 memset(buffer, 0, sizeof(buffer));
245
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700246 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700247 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700248 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
249 return;
250 }
251
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800252 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
253 save_errno = errno;
254 close(fd);
255
256 if (ret < 0) {
257 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
258 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700259 }
260
Colin Cross0c22e8b2012-11-02 15:46:56 -0700261 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
262 pid == tid ? 0 : 3, "", name);
263
264 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700265
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800266 return;
267}
268
269// print time in centiseconds
270static void snprcent(char *buffer, size_t len, size_t spc,
271 unsigned long long time) {
272 static long hz; // cache discovered hz
273
274 if (hz <= 0) {
275 hz = sysconf(_SC_CLK_TCK);
276 if (hz <= 0) {
277 hz = 1000;
278 }
279 }
280
281 // convert to centiseconds
282 time = (time * 100 + (hz / 2)) / hz;
283
284 char str[16];
285
286 snprintf(str, sizeof(str), " %llu.%02u",
287 time / 100, (unsigned)(time % 100));
288 size_t offset = strlen(buffer);
289 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
290 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
291}
292
293// print permille as a percent
294static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
295 char str[16];
296
297 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
298 size_t offset = strlen(buffer);
299 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
300 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
301}
302
303void show_showtime(int pid, const char *name) {
304 ON_DRY_RUN_RETURN();
305 char path[255];
306 char buffer[1023];
307 int fd, ret, save_errno;
308
309 memset(buffer, 0, sizeof(buffer));
310
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700311 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800312 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
313 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
314 return;
315 }
316
317 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
318 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700319 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800320
321 if (ret < 0) {
322 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
323 return;
324 }
325
326 // field 14 is utime
327 // field 15 is stime
328 // field 42 is iotime
329 unsigned long long utime = 0, stime = 0, iotime = 0;
330 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800331 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
332 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
333 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
334 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800335 &utime, &stime, &iotime) != 3) {
336 return;
337 }
338
339 unsigned long long total = utime + stime;
340 if (!total) {
341 return;
342 }
343
344 unsigned permille = (iotime * 1000 + (total / 2)) / total;
345 if (permille > 1000) {
346 permille = 1000;
347 }
348
349 // try to beautify and stabilize columns at <80 characters
350 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
351 if ((name[0] != '[') || utime) {
352 snprcent(buffer, sizeof(buffer), 57, utime);
353 }
354 snprcent(buffer, sizeof(buffer), 65, stime);
355 if ((name[0] != '[') || iotime) {
356 snprcent(buffer, sizeof(buffer), 73, iotime);
357 }
358 if (iotime) {
359 snprdec(buffer, sizeof(buffer), 79, permille);
360 }
361 puts(buffer); // adds a trailing newline
362
Colin Crossf45fa6b2012-03-26 12:38:26 -0700363 return;
364}
365
366void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800367 const char *title = "KERNEL LOG (dmesg)";
368 DurationReporter duration_reporter(title);
369 printf("------ %s ------\n", title);
370
Felipe Leme93d705b2015-11-10 20:10:25 -0800371 ON_DRY_RUN_RETURN();
Elliott Hughes5f87b312012-09-17 11:43:40 -0700372 /* Get size of kernel buffer */
373 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700374 if (size <= 0) {
375 printf("Unexpected klogctl return value: %d\n\n", size);
376 return;
377 }
378 char *buf = (char *) malloc(size + 1);
379 if (buf == NULL) {
380 printf("memory allocation failed\n\n");
381 return;
382 }
383 int retval = klogctl(KLOG_READ_ALL, buf, size);
384 if (retval < 0) {
385 printf("klogctl failure\n\n");
386 free(buf);
387 return;
388 }
389 buf[retval] = '\0';
390 printf("%s\n\n", buf);
391 free(buf);
392 return;
393}
394
395void do_showmap(int pid, const char *name) {
396 char title[255];
397 char arg[255];
398
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700399 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
400 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Leme3dba69a2016-03-17 14:59:13 -0700401 run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700402}
403
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800404static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700405 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800406 printf("------ %s (%s", title, path);
407
Colin Crossf45fa6b2012-03-26 12:38:26 -0700408 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800409 // Only show the modification time of non-device files.
410 size_t path_len = strlen(path);
411 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
412 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
413 (path_len < 3 || memcmp(path, "/d/", 3)) &&
414 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700415 char stamp[80];
416 time_t mtime = st.st_mtime;
417 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
418 printf(": %s", stamp);
419 }
420 printf(") ------\n");
421 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800422 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
Colin Crossf45fa6b2012-03-26 12:38:26 -0700423
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800424 bool newline = false;
425 fd_set read_set;
426 struct timeval tm;
427 while (1) {
428 FD_ZERO(&read_set);
429 FD_SET(fd, &read_set);
430 /* Timeout if no data is read for 30 seconds. */
431 tm.tv_sec = 30;
432 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800433 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800434 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
435 if (ret == -1) {
436 printf("*** %s: select failed: %s\n", path, strerror(errno));
437 newline = true;
438 break;
439 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800440 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800441 printf("*** %s: Timed out after %.3fs\n", path,
442 (float) elapsed / NANOS_PER_SEC);
443 newline = true;
444 break;
445 } else {
446 char buffer[65536];
447 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
448 if (bytes_read > 0) {
449 fwrite(buffer, bytes_read, 1, stdout);
450 newline = (buffer[bytes_read-1] == '\n');
451 } else {
452 if (bytes_read == -1) {
453 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
454 newline = true;
455 }
456 break;
457 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700458 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700459 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800460 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700461 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700462
Colin Crossf45fa6b2012-03-26 12:38:26 -0700463 if (!newline) printf("\n");
464 if (title) printf("\n");
465 return 0;
466}
467
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800468/* prints the contents of a file */
469int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800470 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800471 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
472 if (fd < 0) {
473 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800474 printf("*** %s: %s\n", path, strerror(err));
475 if (title) printf("\n");
476 return -1;
477 }
478 return _dump_file_from_fd(title, path, fd);
479}
480
Felipe Leme71a74ac2016-03-17 15:43:25 -0700481int read_file_as_long(const char *path, long int *output) {
482 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
483 if (fd < 0) {
484 int err = errno;
485 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
486 return -1;
487 }
488 char buffer[50];
489 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
490 if (bytes_read == -1) {
491 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
492 return -2;
493 }
494 if (bytes_read == 0) {
495 MYLOGE("File %s is empty\n", path);
496 return -3;
497 }
498 *output = atoi(buffer);
499 return 0;
500}
501
Mark Salyzyn326842f2015-04-30 09:49:41 -0700502/* calls skip to gate calling dump_from_fd recursively
503 * in the specified directory. dump_from_fd defaults to
504 * dump_file_from_fd above when set to NULL. skip defaults
505 * to false when set to NULL. dump_from_fd will always be
506 * called with title NULL.
507 */
508int dump_files(const char *title, const char *dir,
509 bool (*skip)(const char *path),
510 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800511 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700512 DIR *dirp;
513 struct dirent *d;
514 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800515 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700516 int fd, retval = 0;
517
518 if (title) {
519 printf("------ %s (%s) ------\n", title, dir);
520 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800521 ON_DRY_RUN_RETURN(0);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700522
523 if (dir[strlen(dir) - 1] == '/') {
524 ++slash;
525 }
526 dirp = opendir(dir);
527 if (dirp == NULL) {
528 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800529 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700530 return retval;
531 }
532
533 if (!dump_from_fd) {
534 dump_from_fd = dump_file_from_fd;
535 }
536 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
537 if ((d->d_name[0] == '.')
538 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
539 || (d->d_name[1] == '\0'))) {
540 continue;
541 }
542 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
543 (d->d_type == DT_DIR) ? "/" : "");
544 if (!newpath) {
545 retval = -errno;
546 continue;
547 }
548 if (skip && (*skip)(newpath)) {
549 continue;
550 }
551 if (d->d_type == DT_DIR) {
552 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
553 if (ret < 0) {
554 retval = ret;
555 }
556 continue;
557 }
558 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
559 if (fd < 0) {
560 retval = fd;
561 printf("*** %s: %s\n", newpath, strerror(errno));
562 continue;
563 }
564 (*dump_from_fd)(NULL, newpath, fd);
565 }
566 closedir(dirp);
567 if (title) {
568 printf("\n");
569 }
570 return retval;
571}
572
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800573/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
574 * it's possible to avoid issues where opening the file itself can get
575 * stuck.
576 */
577int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme68116162015-11-10 20:10:25 -0800578 ON_DRY_RUN_RETURN(0);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800579 int flags = fcntl(fd, F_GETFL);
580 if (flags == -1) {
581 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800582 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800583 return -1;
584 } else if (!(flags & O_NONBLOCK)) {
585 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800586 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800587 return -1;
588 }
589 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700590}
591
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800592bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
593 sigset_t child_mask, old_mask;
594 sigemptyset(&child_mask);
595 sigaddset(&child_mask, SIGCHLD);
596
597 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
598 printf("*** sigprocmask failed: %s\n", strerror(errno));
599 return false;
600 }
601
602 struct timespec ts;
603 ts.tv_sec = timeout_seconds;
604 ts.tv_nsec = 0;
605 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
606 int saved_errno = errno;
607 // Set the signals back the way they were.
608 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
609 printf("*** sigprocmask failed: %s\n", strerror(errno));
610 if (ret == 0) {
611 return false;
612 }
613 }
614 if (ret == -1) {
615 errno = saved_errno;
616 if (errno == EAGAIN) {
617 errno = ETIMEDOUT;
618 } else {
619 printf("*** sigtimedwait failed: %s\n", strerror(errno));
620 }
621 return false;
622 }
623
624 pid_t child_pid = waitpid(pid, status, WNOHANG);
625 if (child_pid != pid) {
626 if (child_pid != -1) {
627 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
628 } else {
629 printf("*** waitpid failed: %s\n", strerror(errno));
630 }
631 return false;
632 }
633 return true;
634}
635
Felipe Lemea34efb72016-03-11 09:33:32 -0800636// TODO: refactor all those commands that convert args
637void format_args(const char* command, const char *args[], std::string *string);
638
Colin Crossf45fa6b2012-03-26 12:38:26 -0700639int run_command(const char *title, int timeout_seconds, const char *command, ...) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800640 DurationReporter duration_reporter(title);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700641 fflush(stdout);
Felipe Leme93d705b2015-11-10 20:10:25 -0800642
643 const char *args[1024] = {command};
644 size_t arg;
645 va_list ap;
646 va_start(ap, command);
647 if (title) printf("------ %s (%s", title, command);
Felipe Lemea34efb72016-03-11 09:33:32 -0800648 bool null_terminated = false;
Felipe Leme93d705b2015-11-10 20:10:25 -0800649 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
650 args[arg] = va_arg(ap, const char *);
Felipe Lemea34efb72016-03-11 09:33:32 -0800651 if (args[arg] == nullptr) {
652 null_terminated = true;
653 break;
654 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700655 // TODO: null_terminated check is not really working; line below would crash dumpstate if
656 // nullptr is missing
Felipe Leme93d705b2015-11-10 20:10:25 -0800657 if (title) printf(" %s", args[arg]);
658 }
659 if (title) printf(") ------\n");
660 fflush(stdout);
Felipe Lemea34efb72016-03-11 09:33:32 -0800661 if (!null_terminated) {
662 // Fail now, otherwise execvp() call on run_command_always() might hang.
663 std::string cmd;
664 format_args(command, args, &cmd);
665 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
Adam Buchbinder8ede5472016-05-23 13:18:52 -0700666 va_end(ap);
Felipe Lemea34efb72016-03-11 09:33:32 -0800667 return -1;
668 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800669
Felipe Leme71bbfc52015-11-23 14:14:51 -0800670 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
Felipe Leme93d705b2015-11-10 20:10:25 -0800671
Felipe Leme29c39712016-04-01 10:02:00 -0700672 int status = run_command_always(title, DONT_DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800673 va_end(ap);
674 return status;
675}
676
677int run_command_as_shell(const char *title, int timeout_seconds, const char *command, ...) {
678 DurationReporter duration_reporter(title);
679 fflush(stdout);
680
681 const char *args[1024] = {command};
682 size_t arg;
683 va_list ap;
684 va_start(ap, command);
685 if (title) printf("------ %s (%s", title, command);
686 bool null_terminated = false;
687 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
688 args[arg] = va_arg(ap, const char *);
689 if (args[arg] == nullptr) {
690 null_terminated = true;
691 break;
692 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700693 // TODO: null_terminated check is not really working; line below would crash dumpstate if
694 // nullptr is missing
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800695 if (title) printf(" %s", args[arg]);
696 }
697 if (title) printf(") ------\n");
698 fflush(stdout);
699 if (!null_terminated) {
700 // Fail now, otherwise execvp() call on run_command_always() might hang.
701 std::string cmd;
702 format_args(command, args, &cmd);
703 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
Adam Buchbinder8ede5472016-05-23 13:18:52 -0700704 va_end(ap);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800705 return -1;
706 }
707
708 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
709
Felipe Leme29c39712016-04-01 10:02:00 -0700710 int status = run_command_always(title, DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800711 va_end(ap);
712 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800713}
714
715/* forks a command and waits for it to finish */
Felipe Leme29c39712016-04-01 10:02:00 -0700716int run_command_always(const char *title, RootMode root_mode, StdoutMode stdout_mode,
717 int timeout_seconds, const char *args[]) {
718 bool silent = (stdout_mode == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700719 // TODO: need to check if args is null-terminated, otherwise execvp will crash dumpstate
720
Felipe Leme71bbfc52015-11-23 14:14:51 -0800721 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
722 * It's a good approximation for most cases, except when calling dumpsys, where its weight
723 * should be much higher proportionally to its timeout. */
724 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800725
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800726 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800727 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700728 pid_t pid = fork();
729
730 /* handle error case */
731 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700732 if (!silent) printf("*** fork: %s\n", strerror(errno));
733 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700734 return pid;
735 }
736
737 /* handle child case */
738 if (pid == 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700739 if (root_mode == DROP_ROOT && !drop_root_user()) {
740 if (!silent) printf("*** fail todrop root before running %s: %s\n", command,
741 strerror(errno));
742 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700743 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800744 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700745
Felipe Leme29c39712016-04-01 10:02:00 -0700746 if (silent) {
747 // Redirect stderr to stdout
748 dup2(STDERR_FILENO, STDOUT_FILENO);
749 }
750
John Michelaue7b6cf12013-03-07 15:35:35 -0600751 /* make sure the child dies when dumpstate dies */
752 prctl(PR_SET_PDEATHSIG, SIGKILL);
753
Andres Morales2e671bb2014-08-21 12:38:22 -0700754 /* just ignore SIGPIPE, will go down with parent's */
755 struct sigaction sigact;
756 memset(&sigact, 0, sizeof(sigact));
757 sigact.sa_handler = SIG_IGN;
758 sigaction(SIGPIPE, &sigact, NULL);
759
Colin Crossf45fa6b2012-03-26 12:38:26 -0700760 execvp(command, (char**) args);
Felipe Lemeea160d12016-03-24 11:29:44 -0700761 // execvp's result will be handled after waitpid_with_timeout() below, but if it failed,
762 // it's safer to exit dumpstate.
763 MYLOGD("execvp on command '%s' failed (error: %s)", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700764 fflush(stdout);
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700765 // Must call _exit (instead of exit), otherwise it will corrupt the zip file.
766 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700767 }
768
769 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800770 int status;
771 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800772 uint64_t elapsed = DurationReporter::nanotime() - start;
Felipe Lemea34efb72016-03-11 09:33:32 -0800773 std::string cmd; // used to log command and its args
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800774 if (!ret) {
775 if (errno == ETIMEDOUT) {
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' timed out after %.3fs (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' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800780 (float) elapsed / NANOS_PER_SEC, pid);
781 } else {
Felipe Lemea34efb72016-03-11 09:33:32 -0800782 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700783 if (!silent) printf("*** command '%s': Error after %.4fs (killing pid %d)\n",
784 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800785 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800786 (float) elapsed / NANOS_PER_SEC, pid);
787 }
788 kill(pid, SIGTERM);
789 if (!waitpid_with_timeout(pid, 5, NULL)) {
790 kill(pid, SIGKILL);
791 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700792 if (!silent) printf("could not kill command '%s' (pid %d) even with SIGKILL.\n",
793 command, pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700794 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700795 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700796 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800797 return -1;
Felipe Lemea34efb72016-03-11 09:33:32 -0800798 } else if (status) {
799 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700800 if (!silent) printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
Felipe Lemea34efb72016-03-11 09:33:32 -0800801 MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
802 return -2;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700803 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800804
805 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700806 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
807 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800808 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700809 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
810 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800811 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800812
Felipe Leme71bbfc52015-11-23 14:14:51 -0800813 if (weight > 0) {
814 update_progress(weight);
815 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800816 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700817}
818
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800819bool drop_root_user() {
820 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
821 MYLOGD("drop_root_user(): already running as Shell");
822 return true;
823 }
824 /* ensure we will keep capabilities when we drop root */
825 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
826 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
827 return false;
828 }
829
830 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
831 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC };
832 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
833 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
834 return false;
835 }
836 if (setgid(AID_SHELL) != 0) {
837 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
838 return false;
839 }
840 if (setuid(AID_SHELL) != 0) {
841 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
842 return false;
843 }
844
845 struct __user_cap_header_struct capheader;
846 struct __user_cap_data_struct capdata[2];
847 memset(&capheader, 0, sizeof(capheader));
848 memset(&capdata, 0, sizeof(capdata));
849 capheader.version = _LINUX_CAPABILITY_VERSION_3;
850 capheader.pid = 0;
851
852 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
853 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
854 capdata[0].inheritable = 0;
855 capdata[1].inheritable = 0;
856
857 if (capset(&capheader, &capdata[0]) < 0) {
858 MYLOGE("capset failed: %s\n", strerror(errno));
859 return false;
860 }
861
862 return true;
863}
864
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800865void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
866 if (args.size() > 1000) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800867 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800868 return;
869 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800870 const char *am_args[1024] = { "/system/bin/am", "broadcast", "--user", "0", "-a",
871 action.c_str() };
872 size_t am_index = 5; // Starts at the index of last initial value above.
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800873 for (const std::string& arg : args) {
874 am_args[++am_index] = arg.c_str();
875 }
876 // Always terminate with NULL.
877 am_args[am_index + 1] = NULL;
Felipe Lemea34efb72016-03-11 09:33:32 -0800878 std::string args_string;
879 format_args(am_index + 1, am_args, &args_string);
880 MYLOGD("send_broadcast command: %s\n", args_string.c_str());
Felipe Leme29c39712016-04-01 10:02:00 -0700881 run_command_always(NULL, DROP_ROOT, REDIRECT_TO_STDERR, 20, am_args);
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800882}
883
Colin Crossf45fa6b2012-03-26 12:38:26 -0700884size_t num_props = 0;
885static char* props[2000];
886
887static void print_prop(const char *key, const char *name, void *user) {
888 (void) user;
889 if (num_props < sizeof(props) / sizeof(props[0])) {
890 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
891 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
892 props[num_props++] = strdup(buf);
893 }
894}
895
896static int compare_prop(const void *a, const void *b) {
897 return strcmp(*(char * const *) a, *(char * const *) b);
898}
899
900/* prints all the system properties */
901void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800902 const char* title = "SYSTEM PROPERTIES";
903 DurationReporter duration_reporter(title);
904 printf("------ %s ------\n", title);
Felipe Leme93d705b2015-11-10 20:10:25 -0800905 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700906 size_t i;
907 num_props = 0;
908 property_list(print_prop, NULL);
909 qsort(&props, num_props, sizeof(props[0]), compare_prop);
910
Colin Crossf45fa6b2012-03-26 12:38:26 -0700911 for (i = 0; i < num_props; ++i) {
912 fputs(props[i], stdout);
913 free(props[i]);
914 }
915 printf("\n");
916}
917
Felipe Leme2628e9e2016-04-12 16:36:51 -0700918int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700919 int s = android_get_control_socket(service);
920 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800921 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700922 exit(1);
923 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700924 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700925 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800926 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700927 exit(1);
928 }
929
930 struct sockaddr addr;
931 socklen_t alen = sizeof(addr);
932 int fd = accept(s, &addr, &alen);
933 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800934 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700935 exit(1);
936 }
937
Felipe Leme2628e9e2016-04-12 16:36:51 -0700938 return fd;
939}
940
941/* redirect output to a service control socket */
942void redirect_to_socket(FILE *redirect, const char *service) {
943 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700944 fflush(redirect);
945 dup2(fd, fileno(redirect));
946 close(fd);
947}
948
Felipe Leme2628e9e2016-04-12 16:36:51 -0700949// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800950void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800951 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700952
953 /* skip initial slash */
954 if (chp[0] == '/')
955 chp++;
956
957 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800958 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700959 while (chp && chp[0]) {
960 chp = strchr(chp, '/');
961 if (chp) {
962 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800963 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800964 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800965 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800966 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800967 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800968 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800969 }
970 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700971 *chp++ = '/';
972 }
973 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800974}
975
976/* redirect output to a file */
977void redirect_to_file(FILE *redirect, char *path) {
978 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700979
Felipe Leme608385d2016-02-01 10:35:38 -0800980 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800981 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700982 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800983 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700984 exit(1);
985 }
986
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800987 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700988 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700989}
990
Jeff Brownbf7f4922012-06-07 16:40:01 -0700991static bool should_dump_native_traces(const char* path) {
992 for (const char** p = native_processes_to_dump; *p; p++) {
993 if (!strcmp(*p, path)) {
994 return true;
995 }
996 }
997 return false;
998}
999
1000/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1001const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -08001002 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Leme93d705b2015-11-10 20:10:25 -08001003 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001004 const char* result = NULL;
1005
Colin Crossf45fa6b2012-03-26 12:38:26 -07001006 char traces_path[PROPERTY_VALUE_MAX] = "";
1007 property_get("dalvik.vm.stack-trace-file", traces_path, "");
1008 if (!traces_path[0]) return NULL;
1009
1010 /* move the old traces.txt (if any) out of the way temporarily */
1011 char anr_traces_path[PATH_MAX];
1012 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
1013 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
1014 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001015 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001016 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
1017 }
1018
Colin Crossf45fa6b2012-03-26 12:38:26 -07001019 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001020 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 -08001021 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001022 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001023 MYLOGE("%s: %s\n", traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001024 return NULL;
1025 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001026 int chmod_ret = fchmod(fd, 0666);
1027 if (chmod_ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001028 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001029 close(fd);
1030 return NULL;
1031 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001032
Felipe Leme8620bb42015-11-10 11:04:45 -08001033 /* Variables below must be initialized before 'goto' statements */
1034 int dalvik_found = 0;
1035 int ifd, wfd = -1;
1036
Colin Crossf45fa6b2012-03-26 12:38:26 -07001037 /* walk /proc and kill -QUIT all Dalvik processes */
1038 DIR *proc = opendir("/proc");
1039 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001040 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001041 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001042 }
1043
1044 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001045 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001046 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001047 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001048 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001049 }
1050
Felipe Leme8620bb42015-11-10 11:04:45 -08001051 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001052 if (wfd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001053 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001054 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001055 }
1056
1057 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001058 while ((d = readdir(proc))) {
1059 int pid = atoi(d->d_name);
1060 if (pid <= 0) continue;
1061
Jeff Brownbf7f4922012-06-07 16:40:01 -07001062 char path[PATH_MAX];
1063 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001064 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001065 ssize_t len = readlink(path, data, sizeof(data) - 1);
1066 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001067 continue;
1068 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001069 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001070
Colin Cross0d6180f2014-07-16 19:00:46 -07001071 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001072 /* skip zygote -- it won't dump its stack anyway */
1073 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001074 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001075 len = read(cfd, data, sizeof(data) - 1);
1076 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001077 if (len <= 0) {
1078 continue;
1079 }
1080 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001081 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001082 continue;
1083 }
1084
1085 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -08001086 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001087 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001088 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001089 continue;
1090 }
1091
1092 /* wait for the writable-close notification from inotify */
1093 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -07001094 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -07001095 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001096 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001097 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001098 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001099 } else {
1100 struct inotify_event ie;
1101 read(ifd, &ie, sizeof(ie));
1102 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001103
1104 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001105 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001106 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001107 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001108 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001109 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001110 } else if (should_dump_native_traces(data)) {
1111 /* dump native process if appropriate */
1112 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001113 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001114 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001115 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -08001116 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001117
1118 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1119 if (timeout_failures == 3) {
1120 dprintf(fd, "too many stack dump failures, skipping...\n");
1121 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1122 dprintf(fd, "dumping failed, likely due to a timeout\n");
1123 timeout_failures++;
1124 } else {
1125 timeout_failures = 0;
1126 }
1127 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001128 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001129 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001130 }
1131 }
1132
Colin Crossf45fa6b2012-03-26 12:38:26 -07001133 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001134 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001135 }
1136
1137 static char dump_traces_path[PATH_MAX];
1138 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
1139 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
1140 if (rename(traces_path, dump_traces_path)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001141 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001142 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001143 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001144 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001145
1146 /* replace the saved [ANR] traces.txt file */
1147 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001148
1149error_close_ifd:
1150 close(ifd);
1151error_close_fd:
1152 close(fd);
1153 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001154}
1155
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001156void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001157 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -08001158 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001159 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1160 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001161 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001162 if (!fp) {
1163 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1164 return;
1165 }
1166 char table[16];
1167 // Each line has an integer (the table number), a space, and a string (the table name). We only
1168 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1169 // Add a fixed max limit so this doesn't go awry.
1170 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
1171 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
1172 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
1173 }
1174 fclose(fp);
1175}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001176
1177/* overall progress */
1178int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001179int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001180int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001181
1182// TODO: make this function thread safe if sections are generated in parallel.
1183void update_progress(int delta) {
1184 if (!do_update_progress) return;
1185
1186 progress += delta;
1187
1188 char key[PROPERTY_KEY_MAX];
1189 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001190
1191 // adjusts max on the fly
1192 if (progress > weight_total) {
1193 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001194 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001195 weight_total = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001196 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
1197 snprintf(value, sizeof(value), "%d", weight_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001198 int status = property_set(key, value);
1199 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001200 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001201 key, value, status);
1202 }
1203 }
1204
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001205 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
1206 snprintf(value, sizeof(value), "%d", progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001207
Felipe Leme107a05f2016-03-08 15:11:15 -08001208 if (progress % 100 == 0) {
1209 // We don't want to spam logcat, so only log multiples of 100.
1210 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1211 } else {
1212 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1213 // directly for debuggging.
1214 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1215 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001216
1217 int status = property_set(key, value);
1218 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001219 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001220 key, value, status);
1221 }
1222}
Felipe Lemee338bf62015-12-07 14:03:50 -08001223
Felipe Leme3634a1e2015-12-09 10:11:47 -08001224void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -08001225 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
Felipe Leme29c39712016-04-01 10:02:00 -07001226 run_command_always(NULL, DONT_DROP_ROOT, REDIRECT_TO_STDERR, 10, args);
Felipe Lemee338bf62015-12-07 14:03:50 -08001227}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001228
Felipe Leme0c80cf02016-01-05 13:25:34 -08001229void vibrate(FILE* vibrator, int ms) {
1230 fprintf(vibrator, "%d\n", ms);
1231 fflush(vibrator);
1232}
1233
1234bool is_dir(const char* pathname) {
1235 struct stat info;
1236 if (stat(pathname, &info) == -1) {
1237 return false;
1238 }
1239 return S_ISDIR(info.st_mode);
1240}
1241
1242time_t get_mtime(int fd, time_t default_mtime) {
1243 struct stat info;
1244 if (fstat(fd, &info) == -1) {
1245 return default_mtime;
1246 }
1247 return info.st_mtime;
1248}
1249
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001250void dump_emmc_ecsd(const char *ext_csd_path) {
1251 static const size_t EXT_CSD_REV = 192;
1252 static const size_t EXT_PRE_EOL_INFO = 267;
1253 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
1254 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
1255 struct hex {
1256 char str[2];
1257 } buffer[512];
1258 int fd, ext_csd_rev, ext_pre_eol_info;
1259 ssize_t bytes_read;
1260 static const char *ver_str[] = {
1261 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1262 };
1263 static const char *eol_str[] = {
1264 "Undefined",
1265 "Normal",
1266 "Warning (consumed 80% of reserve)",
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001267 "Urgent (consumed 90% of reserve)"
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001268 };
1269
1270 printf("------ %s Extended CSD ------\n", ext_csd_path);
1271
1272 fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
1273 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
1274 if (fd < 0) {
1275 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1276 return;
1277 }
1278
1279 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
1280 close(fd);
1281 if (bytes_read < 0) {
1282 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1283 return;
1284 }
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001285 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001286 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1287 return;
1288 }
1289
1290 ext_csd_rev = 0;
1291 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
1292 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
1293 ext_csd_path, buffer[EXT_CSD_REV].str);
1294 return;
1295 }
1296
1297 printf("rev 1.%d (MMC %s)\n",
1298 ext_csd_rev,
1299 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1300 ver_str[ext_csd_rev] :
1301 "Unknown");
1302 if (ext_csd_rev < 7) {
1303 printf("\n");
1304 return;
1305 }
1306
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001307 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001308 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1309 return;
1310 }
1311
1312 ext_pre_eol_info = 0;
1313 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1314 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1315 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1316 return;
1317 }
1318 printf("PRE_EOL_INFO %d (MMC %s)\n",
1319 ext_pre_eol_info,
1320 eol_str[(ext_pre_eol_info < (int)
1321 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1322 ext_pre_eol_info : 0]);
1323
1324 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1325 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1326 ++lifetime) {
1327 int ext_device_life_time_est;
1328 static const char *est_str[] = {
1329 "Undefined",
1330 "0-10% of device lifetime used",
1331 "10-20% of device lifetime used",
1332 "20-30% of device lifetime used",
1333 "30-40% of device lifetime used",
1334 "40-50% of device lifetime used",
1335 "50-60% of device lifetime used",
1336 "60-70% of device lifetime used",
1337 "70-80% of device lifetime used",
1338 "80-90% of device lifetime used",
1339 "90-100% of device lifetime used",
1340 "Exceeded the maximum estimated device lifetime",
1341 };
1342
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001343 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001344 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1345 break;
1346 }
1347
1348 ext_device_life_time_est = 0;
1349 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1350 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1351 ext_csd_path,
1352 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1353 buffer[lifetime].str);
1354 continue;
1355 }
1356 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1357 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1358 ext_device_life_time_est,
1359 est_str[(ext_device_life_time_est < (int)
1360 (sizeof(est_str) / sizeof(est_str[0]))) ?
1361 ext_device_life_time_est : 0]);
1362 }
1363
1364 printf("\n");
1365}
Felipe Leme88c79332016-02-22 11:06:49 -08001366
Felipe Lemea34efb72016-03-11 09:33:32 -08001367// TODO: refactor all those commands that convert args
1368void format_args(int argc, const char *argv[], std::string *args) {
1369 LOG_ALWAYS_FATAL_IF(args == nullptr);
Felipe Leme88c79332016-02-22 11:06:49 -08001370 for (int i = 0; i < argc; i++) {
Felipe Lemea34efb72016-03-11 09:33:32 -08001371 args->append(argv[i]);
1372 if (i < argc -1) {
1373 args->append(" ");
1374 }
Felipe Leme88c79332016-02-22 11:06:49 -08001375 }
Felipe Lemea34efb72016-03-11 09:33:32 -08001376}
1377void format_args(const char* command, const char *args[], std::string *string) {
1378 LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr);
1379 string->append(command);
1380 if (args[0] == nullptr) return;
1381 string->append(" ");
1382
1383 for (int arg = 1; arg <= 1000; ++arg) {
1384 if (args[arg] == nullptr) return;
1385 string->append(args[arg]);
1386 if (args[arg+1] != nullptr) {
1387 string->append(" ");
1388 }
1389 }
Felipe Lemeea160d12016-03-24 11:29:44 -07001390 // TODO: not really working: if NULL is missing, it will crash dumpstate.
Felipe Lemea34efb72016-03-11 09:33:32 -08001391 MYLOGE("internal error: missing NULL entry on %s", string->c_str());
Felipe Leme88c79332016-02-22 11:06:49 -08001392}