blob: 139231cdc9794d57e3fdf8d442beccde7e88dd64 [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
Mark Salyzyna5e161b2016-09-29 08:08:05 -070017#define LOG_TAG "dumpstate"
18
Colin Crossf45fa6b2012-03-26 12:38:26 -070019#include <dirent.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <limits.h>
23#include <poll.h>
24#include <signal.h>
25#include <stdarg.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080029#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070030#include <sys/inotify.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070031#include <sys/klog.h>
32#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070033#include <sys/stat.h>
34#include <sys/time.h>
35#include <sys/wait.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070036#include <time.h>
37#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070038
39#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080040#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070041
Mark Salyzyn290f4b92016-05-16 08:33:59 -070042#include <android-base/file.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070043#include <cutils/properties.h>
44#include <cutils/sockets.h>
Josh Gaod2db0242017-01-05 18:27:33 -080045#include <debuggerd/client.h>
Mark Salyzyn4eb13822017-01-12 13:57:51 -080046#include <log/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070047#include <private/android_filesystem_config.h>
48
Robert Craig95798372013-04-04 06:33:10 -040049#include <selinux/android.h>
50
Colin Crossf45fa6b2012-03-26 12:38:26 -070051#include "dumpstate.h"
52
Jeff Brown1dc94e32014-09-11 14:15:27 -070053static const int64_t NANOS_PER_SEC = 1000000000;
54
Jeff Brownbf7f4922012-06-07 16:40:01 -070055/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070056// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070057static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080058 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080059 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070060 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070061 "/system/bin/mediacodec", // media.codec
62 "/system/bin/mediadrmserver",
63 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070064 "/system/bin/mediaserver",
65 "/system/bin/sdcard",
66 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070067 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070068 NULL,
69};
70
Felipe Leme608385d2016-02-01 10:35:38 -080071DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
72
73DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme78f2c862015-12-21 09:55:22 -080074 title_ = title;
75 if (title) {
76 started_ = DurationReporter::nanotime();
77 }
Felipe Leme608385d2016-02-01 10:35:38 -080078 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -080079}
80
81DurationReporter::~DurationReporter() {
82 if (title_) {
83 uint64_t elapsed = DurationReporter::nanotime() - started_;
84 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme608385d2016-02-01 10:35:38 -080085 if (out_) {
86 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
87 (float) elapsed / NANOS_PER_SEC, title_);
88 } else {
Felipe Lemecbce55d2016-02-08 09:53:18 -080089 MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -080090 }
Felipe Leme78f2c862015-12-21 09:55:22 -080091 }
92}
93
94uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080095 struct timespec ts;
96 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080097 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080098}
99
John Spurlock5ecd4be2014-01-29 14:14:40 -0500100void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800101 ON_DRY_RUN_RETURN();
John Spurlock5ecd4be2014-01-29 14:14:40 -0500102 DIR *d;
103 struct dirent *de;
104
105 if (header) printf("\n------ %s ------\n", header);
106 func(0);
107
108 if (!(d = opendir("/data/system/users"))) {
109 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
110 return;
111 }
112
113 while ((de = readdir(d))) {
114 int userid;
115 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
116 continue;
117 }
118 func(userid);
119 }
120
121 closedir(d);
122}
123
Colin Cross0c22e8b2012-11-02 15:46:56 -0700124static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700125 DIR *d;
126 struct dirent *de;
127
128 if (!(d = opendir("/proc"))) {
129 printf("Failed to open /proc (%s)\n", strerror(errno));
130 return;
131 }
132
Felipe Leme635ca312016-01-05 14:23:02 -0800133 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700134 while ((de = readdir(d))) {
135 int pid;
136 int fd;
137 char cmdpath[255];
138 char cmdline[255];
139
140 if (!(pid = atoi(de->d_name))) {
141 continue;
142 }
143
Colin Crossf45fa6b2012-03-26 12:38:26 -0700144 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800145
146 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
147 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
148 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700149 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800150 if (cmdline[0]) {
151 helper(pid, cmdline, arg);
152 continue;
153 }
154 }
155
156 // if no cmdline, a kernel thread has comm
157 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
158 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
159 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
160 close(fd);
161 if (cmdline[1]) {
162 cmdline[0] = '[';
163 size_t len = strcspn(cmdline, "\f\b\r\n");
164 cmdline[len] = ']';
165 cmdline[len+1] = '\0';
166 }
167 }
168 if (!cmdline[0]) {
169 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700170 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700171 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700172 }
173
174 closedir(d);
175}
176
Colin Cross0c22e8b2012-11-02 15:46:56 -0700177static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800178 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700179 func(pid, cmdline);
180}
181
182void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800183 ON_DRY_RUN_RETURN();
Felipe Leme515eb0d2015-12-14 15:09:56 -0800184 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700185}
186
187static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
188 DIR *d;
189 struct dirent *de;
190 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800191 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700192
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700193 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700194
195 if (!(d = opendir(taskpath))) {
196 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
197 return;
198 }
199
200 func(pid, pid, cmdline);
201
202 while ((de = readdir(d))) {
203 int tid;
204 int fd;
205 char commpath[255];
206 char comm[255];
207
208 if (!(tid = atoi(de->d_name))) {
209 continue;
210 }
211
212 if (tid == pid)
213 continue;
214
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700215 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800216 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700217 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700218 strcpy(comm, "N/A");
219 } else {
220 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800221 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700222 close(fd);
223
224 c = strrchr(comm, '\n');
225 if (c) {
226 *c = '\0';
227 }
228 }
229 func(pid, tid, comm);
230 }
231
232 closedir(d);
233}
234
235void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800236 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800237 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700238}
239
240void show_wchan(int pid, int tid, const char *name) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800241 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700242 char path[255];
243 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800244 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700245 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700246
247 memset(buffer, 0, sizeof(buffer));
248
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700249 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700250 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700251 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
252 return;
253 }
254
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800255 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
256 save_errno = errno;
257 close(fd);
258
259 if (ret < 0) {
260 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
261 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700262 }
263
Colin Cross0c22e8b2012-11-02 15:46:56 -0700264 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
265 pid == tid ? 0 : 3, "", name);
266
267 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700268
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800269 return;
270}
271
272// print time in centiseconds
273static void snprcent(char *buffer, size_t len, size_t spc,
274 unsigned long long time) {
275 static long hz; // cache discovered hz
276
277 if (hz <= 0) {
278 hz = sysconf(_SC_CLK_TCK);
279 if (hz <= 0) {
280 hz = 1000;
281 }
282 }
283
284 // convert to centiseconds
285 time = (time * 100 + (hz / 2)) / hz;
286
287 char str[16];
288
289 snprintf(str, sizeof(str), " %llu.%02u",
290 time / 100, (unsigned)(time % 100));
291 size_t offset = strlen(buffer);
292 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
293 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
294}
295
296// print permille as a percent
297static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
298 char str[16];
299
300 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
301 size_t offset = strlen(buffer);
302 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
303 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
304}
305
306void show_showtime(int pid, const char *name) {
307 ON_DRY_RUN_RETURN();
308 char path[255];
309 char buffer[1023];
310 int fd, ret, save_errno;
311
312 memset(buffer, 0, sizeof(buffer));
313
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700314 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800315 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
316 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
317 return;
318 }
319
320 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
321 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700322 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800323
324 if (ret < 0) {
325 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
326 return;
327 }
328
329 // field 14 is utime
330 // field 15 is stime
331 // field 42 is iotime
332 unsigned long long utime = 0, stime = 0, iotime = 0;
333 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800334 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
335 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
336 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
337 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800338 &utime, &stime, &iotime) != 3) {
339 return;
340 }
341
342 unsigned long long total = utime + stime;
343 if (!total) {
344 return;
345 }
346
347 unsigned permille = (iotime * 1000 + (total / 2)) / total;
348 if (permille > 1000) {
349 permille = 1000;
350 }
351
352 // try to beautify and stabilize columns at <80 characters
353 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
354 if ((name[0] != '[') || utime) {
355 snprcent(buffer, sizeof(buffer), 57, utime);
356 }
357 snprcent(buffer, sizeof(buffer), 65, stime);
358 if ((name[0] != '[') || iotime) {
359 snprcent(buffer, sizeof(buffer), 73, iotime);
360 }
361 if (iotime) {
362 snprdec(buffer, sizeof(buffer), 79, permille);
363 }
364 puts(buffer); // adds a trailing newline
365
Colin Crossf45fa6b2012-03-26 12:38:26 -0700366 return;
367}
368
369void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800370 const char *title = "KERNEL LOG (dmesg)";
371 DurationReporter duration_reporter(title);
372 printf("------ %s ------\n", title);
373
Felipe Leme93d705b2015-11-10 20:10:25 -0800374 ON_DRY_RUN_RETURN();
Elliott Hughes5f87b312012-09-17 11:43:40 -0700375 /* Get size of kernel buffer */
376 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700377 if (size <= 0) {
378 printf("Unexpected klogctl return value: %d\n\n", size);
379 return;
380 }
381 char *buf = (char *) malloc(size + 1);
382 if (buf == NULL) {
383 printf("memory allocation failed\n\n");
384 return;
385 }
386 int retval = klogctl(KLOG_READ_ALL, buf, size);
387 if (retval < 0) {
388 printf("klogctl failure\n\n");
389 free(buf);
390 return;
391 }
392 buf[retval] = '\0';
393 printf("%s\n\n", buf);
394 free(buf);
395 return;
396}
397
398void do_showmap(int pid, const char *name) {
399 char title[255];
400 char arg[255];
401
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700402 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
403 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Leme3dba69a2016-03-17 14:59:13 -0700404 run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700405}
406
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800407static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700408 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800409 printf("------ %s (%s", title, path);
410
Colin Crossf45fa6b2012-03-26 12:38:26 -0700411 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800412 // Only show the modification time of non-device files.
413 size_t path_len = strlen(path);
414 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
415 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
416 (path_len < 3 || memcmp(path, "/d/", 3)) &&
417 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700418 char stamp[80];
419 time_t mtime = st.st_mtime;
420 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
421 printf(": %s", stamp);
422 }
423 printf(") ------\n");
424 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800425 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
Colin Crossf45fa6b2012-03-26 12:38:26 -0700426
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800427 bool newline = false;
428 fd_set read_set;
429 struct timeval tm;
430 while (1) {
431 FD_ZERO(&read_set);
432 FD_SET(fd, &read_set);
433 /* Timeout if no data is read for 30 seconds. */
434 tm.tv_sec = 30;
435 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800436 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800437 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
438 if (ret == -1) {
439 printf("*** %s: select failed: %s\n", path, strerror(errno));
440 newline = true;
441 break;
442 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800443 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800444 printf("*** %s: Timed out after %.3fs\n", path,
445 (float) elapsed / NANOS_PER_SEC);
446 newline = true;
447 break;
448 } else {
449 char buffer[65536];
450 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
451 if (bytes_read > 0) {
452 fwrite(buffer, bytes_read, 1, stdout);
453 newline = (buffer[bytes_read-1] == '\n');
454 } else {
455 if (bytes_read == -1) {
456 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
457 newline = true;
458 }
459 break;
460 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700461 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700462 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800463 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700464 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700465
Colin Crossf45fa6b2012-03-26 12:38:26 -0700466 if (!newline) printf("\n");
467 if (title) printf("\n");
468 return 0;
469}
470
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800471/* prints the contents of a file */
472int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800473 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800474 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
475 if (fd < 0) {
476 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800477 printf("*** %s: %s\n", path, strerror(err));
478 if (title) printf("\n");
479 return -1;
480 }
481 return _dump_file_from_fd(title, path, fd);
482}
483
Felipe Leme71a74ac2016-03-17 15:43:25 -0700484int read_file_as_long(const char *path, long int *output) {
485 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
486 if (fd < 0) {
487 int err = errno;
488 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
489 return -1;
490 }
491 char buffer[50];
492 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
493 if (bytes_read == -1) {
494 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
495 return -2;
496 }
497 if (bytes_read == 0) {
498 MYLOGE("File %s is empty\n", path);
499 return -3;
500 }
501 *output = atoi(buffer);
502 return 0;
503}
504
Mark Salyzyn326842f2015-04-30 09:49:41 -0700505/* calls skip to gate calling dump_from_fd recursively
506 * in the specified directory. dump_from_fd defaults to
507 * dump_file_from_fd above when set to NULL. skip defaults
508 * to false when set to NULL. dump_from_fd will always be
509 * called with title NULL.
510 */
511int dump_files(const char *title, const char *dir,
512 bool (*skip)(const char *path),
513 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800514 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700515 DIR *dirp;
516 struct dirent *d;
517 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800518 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700519 int fd, retval = 0;
520
521 if (title) {
522 printf("------ %s (%s) ------\n", title, dir);
523 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800524 ON_DRY_RUN_RETURN(0);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700525
526 if (dir[strlen(dir) - 1] == '/') {
527 ++slash;
528 }
529 dirp = opendir(dir);
530 if (dirp == NULL) {
531 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800532 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700533 return retval;
534 }
535
536 if (!dump_from_fd) {
537 dump_from_fd = dump_file_from_fd;
538 }
539 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
540 if ((d->d_name[0] == '.')
541 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
542 || (d->d_name[1] == '\0'))) {
543 continue;
544 }
545 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
546 (d->d_type == DT_DIR) ? "/" : "");
547 if (!newpath) {
548 retval = -errno;
549 continue;
550 }
551 if (skip && (*skip)(newpath)) {
552 continue;
553 }
554 if (d->d_type == DT_DIR) {
555 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
556 if (ret < 0) {
557 retval = ret;
558 }
559 continue;
560 }
561 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
562 if (fd < 0) {
563 retval = fd;
564 printf("*** %s: %s\n", newpath, strerror(errno));
565 continue;
566 }
567 (*dump_from_fd)(NULL, newpath, fd);
568 }
569 closedir(dirp);
570 if (title) {
571 printf("\n");
572 }
573 return retval;
574}
575
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800576/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
577 * it's possible to avoid issues where opening the file itself can get
578 * stuck.
579 */
580int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme68116162015-11-10 20:10:25 -0800581 ON_DRY_RUN_RETURN(0);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800582 int flags = fcntl(fd, F_GETFL);
583 if (flags == -1) {
584 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800585 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800586 return -1;
587 } else if (!(flags & O_NONBLOCK)) {
588 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800589 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800590 return -1;
591 }
592 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700593}
594
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800595bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
596 sigset_t child_mask, old_mask;
597 sigemptyset(&child_mask);
598 sigaddset(&child_mask, SIGCHLD);
599
600 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
601 printf("*** sigprocmask failed: %s\n", strerror(errno));
602 return false;
603 }
604
605 struct timespec ts;
606 ts.tv_sec = timeout_seconds;
607 ts.tv_nsec = 0;
608 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
609 int saved_errno = errno;
610 // Set the signals back the way they were.
611 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
612 printf("*** sigprocmask failed: %s\n", strerror(errno));
613 if (ret == 0) {
614 return false;
615 }
616 }
617 if (ret == -1) {
618 errno = saved_errno;
619 if (errno == EAGAIN) {
620 errno = ETIMEDOUT;
621 } else {
622 printf("*** sigtimedwait failed: %s\n", strerror(errno));
623 }
624 return false;
625 }
626
627 pid_t child_pid = waitpid(pid, status, WNOHANG);
628 if (child_pid != pid) {
629 if (child_pid != -1) {
630 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
631 } else {
632 printf("*** waitpid failed: %s\n", strerror(errno));
633 }
634 return false;
635 }
636 return true;
637}
638
Felipe Lemea34efb72016-03-11 09:33:32 -0800639// TODO: refactor all those commands that convert args
640void format_args(const char* command, const char *args[], std::string *string);
641
Colin Crossf45fa6b2012-03-26 12:38:26 -0700642int run_command(const char *title, int timeout_seconds, const char *command, ...) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800643 DurationReporter duration_reporter(title);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700644 fflush(stdout);
Felipe Leme93d705b2015-11-10 20:10:25 -0800645
646 const char *args[1024] = {command};
647 size_t arg;
648 va_list ap;
649 va_start(ap, command);
650 if (title) printf("------ %s (%s", title, command);
Felipe Lemea34efb72016-03-11 09:33:32 -0800651 bool null_terminated = false;
Felipe Leme93d705b2015-11-10 20:10:25 -0800652 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
653 args[arg] = va_arg(ap, const char *);
Felipe Lemea34efb72016-03-11 09:33:32 -0800654 if (args[arg] == nullptr) {
655 null_terminated = true;
656 break;
657 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700658 // TODO: null_terminated check is not really working; line below would crash dumpstate if
659 // nullptr is missing
Felipe Leme93d705b2015-11-10 20:10:25 -0800660 if (title) printf(" %s", args[arg]);
661 }
662 if (title) printf(") ------\n");
663 fflush(stdout);
Felipe Lemea34efb72016-03-11 09:33:32 -0800664 if (!null_terminated) {
665 // Fail now, otherwise execvp() call on run_command_always() might hang.
666 std::string cmd;
667 format_args(command, args, &cmd);
668 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
669 return -1;
670 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800671
Felipe Leme71bbfc52015-11-23 14:14:51 -0800672 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
Felipe Leme93d705b2015-11-10 20:10:25 -0800673
Felipe Leme29c39712016-04-01 10:02:00 -0700674 int status = run_command_always(title, DONT_DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800675 va_end(ap);
676 return status;
677}
678
679int run_command_as_shell(const char *title, int timeout_seconds, const char *command, ...) {
680 DurationReporter duration_reporter(title);
681 fflush(stdout);
682
683 const char *args[1024] = {command};
684 size_t arg;
685 va_list ap;
686 va_start(ap, command);
687 if (title) printf("------ %s (%s", title, command);
688 bool null_terminated = false;
689 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
690 args[arg] = va_arg(ap, const char *);
691 if (args[arg] == nullptr) {
692 null_terminated = true;
693 break;
694 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700695 // TODO: null_terminated check is not really working; line below would crash dumpstate if
696 // nullptr is missing
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800697 if (title) printf(" %s", args[arg]);
698 }
699 if (title) printf(") ------\n");
700 fflush(stdout);
701 if (!null_terminated) {
702 // Fail now, otherwise execvp() call on run_command_always() might hang.
703 std::string cmd;
704 format_args(command, args, &cmd);
705 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
706 return -1;
707 }
708
709 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
710
Felipe Leme29c39712016-04-01 10:02:00 -0700711 int status = run_command_always(title, DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800712 va_end(ap);
713 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800714}
715
716/* forks a command and waits for it to finish */
Felipe Leme29c39712016-04-01 10:02:00 -0700717int run_command_always(const char *title, RootMode root_mode, StdoutMode stdout_mode,
718 int timeout_seconds, const char *args[]) {
719 bool silent = (stdout_mode == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700720 // TODO: need to check if args is null-terminated, otherwise execvp will crash dumpstate
721
Felipe Leme71bbfc52015-11-23 14:14:51 -0800722 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
723 * It's a good approximation for most cases, except when calling dumpsys, where its weight
724 * should be much higher proportionally to its timeout. */
725 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800726
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800727 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800728 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700729 pid_t pid = fork();
730
731 /* handle error case */
732 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700733 if (!silent) printf("*** fork: %s\n", strerror(errno));
734 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700735 return pid;
736 }
737
738 /* handle child case */
739 if (pid == 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700740 if (root_mode == DROP_ROOT && !drop_root_user()) {
741 if (!silent) printf("*** fail todrop root before running %s: %s\n", command,
742 strerror(errno));
743 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700744 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800745 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700746
Felipe Leme29c39712016-04-01 10:02:00 -0700747 if (silent) {
748 // Redirect stderr to stdout
749 dup2(STDERR_FILENO, STDOUT_FILENO);
750 }
751
John Michelaue7b6cf12013-03-07 15:35:35 -0600752 /* make sure the child dies when dumpstate dies */
753 prctl(PR_SET_PDEATHSIG, SIGKILL);
754
Andres Morales2e671bb2014-08-21 12:38:22 -0700755 /* just ignore SIGPIPE, will go down with parent's */
756 struct sigaction sigact;
757 memset(&sigact, 0, sizeof(sigact));
758 sigact.sa_handler = SIG_IGN;
759 sigaction(SIGPIPE, &sigact, NULL);
760
Colin Crossf45fa6b2012-03-26 12:38:26 -0700761 execvp(command, (char**) args);
Felipe Lemeea160d12016-03-24 11:29:44 -0700762 // execvp's result will be handled after waitpid_with_timeout() below, but if it failed,
763 // it's safer to exit dumpstate.
764 MYLOGD("execvp on command '%s' failed (error: %s)", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700765 fflush(stdout);
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700766 // Must call _exit (instead of exit), otherwise it will corrupt the zip file.
767 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700768 }
769
770 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800771 int status;
772 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800773 uint64_t elapsed = DurationReporter::nanotime() - start;
Felipe Lemea34efb72016-03-11 09:33:32 -0800774 std::string cmd; // used to log command and its args
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800775 if (!ret) {
776 if (errno == ETIMEDOUT) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800777 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700778 if (!silent) printf("*** command '%s' timed out after %.3fs (killing pid %d)\n",
779 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800780 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800781 (float) elapsed / NANOS_PER_SEC, pid);
782 } else {
Felipe Lemea34efb72016-03-11 09:33:32 -0800783 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700784 if (!silent) printf("*** command '%s': Error after %.4fs (killing pid %d)\n",
785 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800786 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800787 (float) elapsed / NANOS_PER_SEC, pid);
788 }
789 kill(pid, SIGTERM);
790 if (!waitpid_with_timeout(pid, 5, NULL)) {
791 kill(pid, SIGKILL);
792 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700793 if (!silent) printf("could not kill command '%s' (pid %d) even with SIGKILL.\n",
794 command, pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700795 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700796 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700797 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800798 return -1;
Felipe Lemea34efb72016-03-11 09:33:32 -0800799 } else if (status) {
800 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700801 if (!silent) printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
Felipe Lemea34efb72016-03-11 09:33:32 -0800802 MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
803 return -2;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700804 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800805
806 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700807 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
808 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800809 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700810 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
811 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800812 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800813
Felipe Leme71bbfc52015-11-23 14:14:51 -0800814 if (weight > 0) {
815 update_progress(weight);
816 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800817 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700818}
819
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800820bool drop_root_user() {
821 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
822 MYLOGD("drop_root_user(): already running as Shell");
823 return true;
824 }
825 /* ensure we will keep capabilities when we drop root */
826 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
827 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
828 return false;
829 }
830
831 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panicker496548f2016-09-23 16:43:29 -0700832 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
Ajay Panicker2f531772016-09-14 12:26:46 -0700833 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800834 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
835 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
836 return false;
837 }
838 if (setgid(AID_SHELL) != 0) {
839 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
840 return false;
841 }
842 if (setuid(AID_SHELL) != 0) {
843 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
844 return false;
845 }
846
847 struct __user_cap_header_struct capheader;
848 struct __user_cap_data_struct capdata[2];
849 memset(&capheader, 0, sizeof(capheader));
850 memset(&capdata, 0, sizeof(capdata));
851 capheader.version = _LINUX_CAPABILITY_VERSION_3;
852 capheader.pid = 0;
853
Wei Liuf87959e2016-08-26 14:51:42 -0700854 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
855 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
856 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
857 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800858 capdata[0].inheritable = 0;
859 capdata[1].inheritable = 0;
860
861 if (capset(&capheader, &capdata[0]) < 0) {
862 MYLOGE("capset failed: %s\n", strerror(errno));
863 return false;
864 }
865
866 return true;
867}
868
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800869void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
870 if (args.size() > 1000) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800871 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800872 return;
873 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800874 const char *am_args[1024] = { "/system/bin/am", "broadcast", "--user", "0", "-a",
875 action.c_str() };
876 size_t am_index = 5; // Starts at the index of last initial value above.
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800877 for (const std::string& arg : args) {
878 am_args[++am_index] = arg.c_str();
879 }
880 // Always terminate with NULL.
881 am_args[am_index + 1] = NULL;
Felipe Lemea34efb72016-03-11 09:33:32 -0800882 std::string args_string;
883 format_args(am_index + 1, am_args, &args_string);
884 MYLOGD("send_broadcast command: %s\n", args_string.c_str());
Felipe Leme29c39712016-04-01 10:02:00 -0700885 run_command_always(NULL, DROP_ROOT, REDIRECT_TO_STDERR, 20, am_args);
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800886}
887
Colin Crossf45fa6b2012-03-26 12:38:26 -0700888size_t num_props = 0;
889static char* props[2000];
890
891static void print_prop(const char *key, const char *name, void *user) {
892 (void) user;
893 if (num_props < sizeof(props) / sizeof(props[0])) {
894 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
895 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
896 props[num_props++] = strdup(buf);
897 }
898}
899
900static int compare_prop(const void *a, const void *b) {
901 return strcmp(*(char * const *) a, *(char * const *) b);
902}
903
904/* prints all the system properties */
905void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800906 const char* title = "SYSTEM PROPERTIES";
907 DurationReporter duration_reporter(title);
908 printf("------ %s ------\n", title);
Felipe Leme93d705b2015-11-10 20:10:25 -0800909 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700910 size_t i;
911 num_props = 0;
912 property_list(print_prop, NULL);
913 qsort(&props, num_props, sizeof(props[0]), compare_prop);
914
Colin Crossf45fa6b2012-03-26 12:38:26 -0700915 for (i = 0; i < num_props; ++i) {
916 fputs(props[i], stdout);
917 free(props[i]);
918 }
919 printf("\n");
920}
921
Felipe Leme2628e9e2016-04-12 16:36:51 -0700922int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700923 int s = android_get_control_socket(service);
924 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800925 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700926 exit(1);
927 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700928 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700929 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800930 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700931 exit(1);
932 }
933
934 struct sockaddr addr;
935 socklen_t alen = sizeof(addr);
936 int fd = accept(s, &addr, &alen);
937 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800938 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700939 exit(1);
940 }
941
Felipe Leme2628e9e2016-04-12 16:36:51 -0700942 return fd;
943}
944
945/* redirect output to a service control socket */
946void redirect_to_socket(FILE *redirect, const char *service) {
947 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700948 fflush(redirect);
949 dup2(fd, fileno(redirect));
950 close(fd);
951}
952
Felipe Leme2628e9e2016-04-12 16:36:51 -0700953// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800954void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800955 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700956
957 /* skip initial slash */
958 if (chp[0] == '/')
959 chp++;
960
961 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800962 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700963 while (chp && chp[0]) {
964 chp = strchr(chp, '/');
965 if (chp) {
966 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800967 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800968 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800969 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800970 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800971 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800972 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800973 }
974 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700975 *chp++ = '/';
976 }
977 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800978}
979
980/* redirect output to a file */
981void redirect_to_file(FILE *redirect, char *path) {
982 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700983
Felipe Leme608385d2016-02-01 10:35:38 -0800984 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800985 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700986 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800987 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700988 exit(1);
989 }
990
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800991 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700992 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700993}
994
Jeff Brownbf7f4922012-06-07 16:40:01 -0700995static bool should_dump_native_traces(const char* path) {
996 for (const char** p = native_processes_to_dump; *p; p++) {
997 if (!strcmp(*p, path)) {
998 return true;
999 }
1000 }
1001 return false;
1002}
1003
1004/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1005const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -08001006 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Leme93d705b2015-11-10 20:10:25 -08001007 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001008 const char* result = NULL;
1009
Colin Crossf45fa6b2012-03-26 12:38:26 -07001010 char traces_path[PROPERTY_VALUE_MAX] = "";
1011 property_get("dalvik.vm.stack-trace-file", traces_path, "");
1012 if (!traces_path[0]) return NULL;
1013
1014 /* move the old traces.txt (if any) out of the way temporarily */
1015 char anr_traces_path[PATH_MAX];
1016 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
1017 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
1018 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001019 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001020 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
1021 }
1022
Colin Crossf45fa6b2012-03-26 12:38:26 -07001023 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001024 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 -08001025 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001027 MYLOGE("%s: %s\n", traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001028 return NULL;
1029 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001030 int chmod_ret = fchmod(fd, 0666);
1031 if (chmod_ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001032 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001033 close(fd);
1034 return NULL;
1035 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001036
Felipe Leme8620bb42015-11-10 11:04:45 -08001037 /* Variables below must be initialized before 'goto' statements */
1038 int dalvik_found = 0;
1039 int ifd, wfd = -1;
1040
Colin Crossf45fa6b2012-03-26 12:38:26 -07001041 /* walk /proc and kill -QUIT all Dalvik processes */
1042 DIR *proc = opendir("/proc");
1043 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001044 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001045 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001046 }
1047
1048 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001049 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001050 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001051 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001052 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001053 }
1054
Felipe Leme8620bb42015-11-10 11:04:45 -08001055 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001056 if (wfd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001057 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001058 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001059 }
1060
1061 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001062 while ((d = readdir(proc))) {
1063 int pid = atoi(d->d_name);
1064 if (pid <= 0) continue;
1065
Jeff Brownbf7f4922012-06-07 16:40:01 -07001066 char path[PATH_MAX];
1067 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001068 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001069 ssize_t len = readlink(path, data, sizeof(data) - 1);
1070 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001071 continue;
1072 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001073 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001074
Colin Cross0d6180f2014-07-16 19:00:46 -07001075 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001076 /* skip zygote -- it won't dump its stack anyway */
1077 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001078 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001079 len = read(cfd, data, sizeof(data) - 1);
1080 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001081 if (len <= 0) {
1082 continue;
1083 }
1084 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001085 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001086 continue;
1087 }
1088
1089 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -08001090 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001091 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001092 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001093 continue;
1094 }
1095
1096 /* wait for the writable-close notification from inotify */
1097 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -07001098 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -07001099 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001100 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001101 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001102 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001103 } else {
1104 struct inotify_event ie;
1105 read(ifd, &ie, sizeof(ie));
1106 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001107
1108 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001109 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001110 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001111 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001112 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001113 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001114 } else if (should_dump_native_traces(data)) {
1115 /* dump native process if appropriate */
1116 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001117 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001118 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001119 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -08001120 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001121
1122 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1123 if (timeout_failures == 3) {
1124 dprintf(fd, "too many stack dump failures, skipping...\n");
1125 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1126 dprintf(fd, "dumping failed, likely due to a timeout\n");
1127 timeout_failures++;
1128 } else {
1129 timeout_failures = 0;
1130 }
1131 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001132 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001133 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001134 }
1135 }
1136
Colin Crossf45fa6b2012-03-26 12:38:26 -07001137 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001138 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001139 }
1140
1141 static char dump_traces_path[PATH_MAX];
1142 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
1143 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
1144 if (rename(traces_path, dump_traces_path)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001145 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001146 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001147 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001148 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001149
1150 /* replace the saved [ANR] traces.txt file */
1151 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001152
1153error_close_ifd:
1154 close(ifd);
1155error_close_fd:
1156 close(fd);
1157 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001158}
1159
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001160void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001161 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -08001162 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001163 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1164 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001165 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001166 if (!fp) {
1167 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1168 return;
1169 }
1170 char table[16];
1171 // Each line has an integer (the table number), a space, and a string (the table name). We only
1172 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1173 // Add a fixed max limit so this doesn't go awry.
1174 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
1175 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
1176 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
1177 }
1178 fclose(fp);
1179}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001180
1181/* overall progress */
1182int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001183int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001184int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001185
1186// TODO: make this function thread safe if sections are generated in parallel.
1187void update_progress(int delta) {
1188 if (!do_update_progress) return;
1189
1190 progress += delta;
1191
1192 char key[PROPERTY_KEY_MAX];
1193 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001194
1195 // adjusts max on the fly
1196 if (progress > weight_total) {
1197 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001198 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001199 weight_total = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001200 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
1201 snprintf(value, sizeof(value), "%d", weight_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001202 int status = property_set(key, value);
1203 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001204 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001205 key, value, status);
1206 }
1207 }
1208
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001209 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
1210 snprintf(value, sizeof(value), "%d", progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001211
Felipe Leme107a05f2016-03-08 15:11:15 -08001212 if (progress % 100 == 0) {
1213 // We don't want to spam logcat, so only log multiples of 100.
1214 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1215 } else {
1216 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1217 // directly for debuggging.
1218 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1219 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001220
Felipe Leme02b7e002016-07-22 12:03:20 -07001221 if (control_socket_fd >= 0) {
1222 dprintf(control_socket_fd, "PROGRESS:%d/%d\n", progress, weight_total);
1223 fsync(control_socket_fd);
1224 }
1225
Felipe Leme71bbfc52015-11-23 14:14:51 -08001226 int status = property_set(key, value);
1227 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001228 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001229 key, value, status);
1230 }
1231}
Felipe Lemee338bf62015-12-07 14:03:50 -08001232
Felipe Leme3634a1e2015-12-09 10:11:47 -08001233void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -08001234 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
Felipe Leme29c39712016-04-01 10:02:00 -07001235 run_command_always(NULL, DONT_DROP_ROOT, REDIRECT_TO_STDERR, 10, args);
Felipe Lemee338bf62015-12-07 14:03:50 -08001236}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001237
Felipe Leme0c80cf02016-01-05 13:25:34 -08001238void vibrate(FILE* vibrator, int ms) {
1239 fprintf(vibrator, "%d\n", ms);
1240 fflush(vibrator);
1241}
1242
1243bool is_dir(const char* pathname) {
1244 struct stat info;
1245 if (stat(pathname, &info) == -1) {
1246 return false;
1247 }
1248 return S_ISDIR(info.st_mode);
1249}
1250
1251time_t get_mtime(int fd, time_t default_mtime) {
1252 struct stat info;
1253 if (fstat(fd, &info) == -1) {
1254 return default_mtime;
1255 }
1256 return info.st_mtime;
1257}
1258
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001259void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001260 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001261 struct hex {
1262 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001263 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001264 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1265 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1266 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1267 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1268
1269 std::string buffer;
1270 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1271 return;
1272 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001273
1274 printf("------ %s Extended CSD ------\n", ext_csd_path);
1275
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001276 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1277 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001278 return;
1279 }
1280
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001281 int ext_csd_rev = 0;
1282 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1283 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1284 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1285 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001286 return;
1287 }
1288
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001289 static const char *ver_str[] = {
1290 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1291 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001292 printf("rev 1.%d (MMC %s)\n",
1293 ext_csd_rev,
1294 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1295 ver_str[ext_csd_rev] :
1296 "Unknown");
1297 if (ext_csd_rev < 7) {
1298 printf("\n");
1299 return;
1300 }
1301
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001302 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1303 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001304 return;
1305 }
1306
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001307 int ext_pre_eol_info = 0;
1308 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1309 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1310 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1311 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001312 return;
1313 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001314
1315 static const char *eol_str[] = {
1316 "Undefined",
1317 "Normal",
1318 "Warning (consumed 80% of reserve)",
1319 "Urgent (consumed 90% of reserve)"
1320 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001321 printf("PRE_EOL_INFO %d (MMC %s)\n",
1322 ext_pre_eol_info,
1323 eol_str[(ext_pre_eol_info < (int)
1324 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1325 ext_pre_eol_info : 0]);
1326
1327 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1328 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001329 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001330 int ext_device_life_time_est;
1331 static const char *est_str[] = {
1332 "Undefined",
1333 "0-10% of device lifetime used",
1334 "10-20% of device lifetime used",
1335 "20-30% of device lifetime used",
1336 "30-40% of device lifetime used",
1337 "40-50% of device lifetime used",
1338 "50-60% of device lifetime used",
1339 "60-70% of device lifetime used",
1340 "70-80% of device lifetime used",
1341 "80-90% of device lifetime used",
1342 "90-100% of device lifetime used",
1343 "Exceeded the maximum estimated device lifetime",
1344 };
1345
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001346 if (buffer.length() < (lifetime + sizeof(hex))) {
1347 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001348 break;
1349 }
1350
1351 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001352 sub = buffer.substr(lifetime, sizeof(hex));
1353 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1354 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001355 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001356 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1357 sizeof(hex)) + 'A',
1358 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001359 continue;
1360 }
1361 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001362 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1363 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001364 ext_device_life_time_est,
1365 est_str[(ext_device_life_time_est < (int)
1366 (sizeof(est_str) / sizeof(est_str[0]))) ?
1367 ext_device_life_time_est : 0]);
1368 }
1369
1370 printf("\n");
1371}
Felipe Leme88c79332016-02-22 11:06:49 -08001372
Felipe Lemea34efb72016-03-11 09:33:32 -08001373// TODO: refactor all those commands that convert args
1374void format_args(int argc, const char *argv[], std::string *args) {
1375 LOG_ALWAYS_FATAL_IF(args == nullptr);
Felipe Leme88c79332016-02-22 11:06:49 -08001376 for (int i = 0; i < argc; i++) {
Felipe Lemea34efb72016-03-11 09:33:32 -08001377 args->append(argv[i]);
1378 if (i < argc -1) {
1379 args->append(" ");
1380 }
Felipe Leme88c79332016-02-22 11:06:49 -08001381 }
Felipe Lemea34efb72016-03-11 09:33:32 -08001382}
1383void format_args(const char* command, const char *args[], std::string *string) {
1384 LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr);
1385 string->append(command);
1386 if (args[0] == nullptr) return;
1387 string->append(" ");
1388
1389 for (int arg = 1; arg <= 1000; ++arg) {
1390 if (args[arg] == nullptr) return;
1391 string->append(args[arg]);
1392 if (args[arg+1] != nullptr) {
1393 string->append(" ");
1394 }
1395 }
Felipe Lemeea160d12016-03-24 11:29:44 -07001396 // TODO: not really working: if NULL is missing, it will crash dumpstate.
Felipe Lemea34efb72016-03-11 09:33:32 -08001397 MYLOGE("internal error: missing NULL entry on %s", string->c_str());
Felipe Leme88c79332016-02-22 11:06:49 -08001398}