blob: 09c2e7f74aa9a4ea1853fda40fc1ed75d8b572c0 [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <poll.h>
22#include <signal.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080026#include <string>
Colin Crossf45fa6b2012-03-26 12:38:26 -070027#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080028#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070029#include <sys/inotify.h>
30#include <sys/stat.h>
Mark Salyzyna297c322016-02-05 15:33:17 -080031#include <sys/sysconf.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/time.h>
33#include <sys/wait.h>
34#include <sys/klog.h>
35#include <time.h>
36#include <unistd.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080037#include <vector>
John Michelaue7b6cf12013-03-07 15:35:35 -060038#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070039
Felipe Leme71bbfc52015-11-23 14:14:51 -080040#define LOG_TAG "dumpstate"
Jeff Brownbf7f4922012-06-07 16:40:01 -070041#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080042#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070043#include <cutils/properties.h>
44#include <cutils/sockets.h>
45#include <private/android_filesystem_config.h>
46
Robert Craig95798372013-04-04 06:33:10 -040047#include <selinux/android.h>
48
Colin Crossf45fa6b2012-03-26 12:38:26 -070049#include "dumpstate.h"
50
Jeff Brown1dc94e32014-09-11 14:15:27 -070051static const int64_t NANOS_PER_SEC = 1000000000;
52
Jeff Brownbf7f4922012-06-07 16:40:01 -070053/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070054// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070055static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080056 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080057 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070058 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070059 "/system/bin/mediacodec", // media.codec
60 "/system/bin/mediadrmserver",
61 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070062 "/system/bin/mediaserver",
63 "/system/bin/sdcard",
64 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070065 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070066 NULL,
67};
68
Felipe Leme608385d2016-02-01 10:35:38 -080069DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
70
71DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme78f2c862015-12-21 09:55:22 -080072 title_ = title;
73 if (title) {
74 started_ = DurationReporter::nanotime();
75 }
Felipe Leme608385d2016-02-01 10:35:38 -080076 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -080077}
78
79DurationReporter::~DurationReporter() {
80 if (title_) {
81 uint64_t elapsed = DurationReporter::nanotime() - started_;
82 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme608385d2016-02-01 10:35:38 -080083 if (out_) {
84 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
85 (float) elapsed / NANOS_PER_SEC, title_);
86 } else {
Felipe Lemecbce55d2016-02-08 09:53:18 -080087 MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -080088 }
Felipe Leme78f2c862015-12-21 09:55:22 -080089 }
90}
91
92uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080093 struct timespec ts;
94 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080095 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080096}
97
John Spurlock5ecd4be2014-01-29 14:14:40 -050098void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -080099 ON_DRY_RUN_RETURN();
John Spurlock5ecd4be2014-01-29 14:14:40 -0500100 DIR *d;
101 struct dirent *de;
102
103 if (header) printf("\n------ %s ------\n", header);
104 func(0);
105
106 if (!(d = opendir("/data/system/users"))) {
107 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
108 return;
109 }
110
111 while ((de = readdir(d))) {
112 int userid;
113 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
114 continue;
115 }
116 func(userid);
117 }
118
119 closedir(d);
120}
121
Colin Cross0c22e8b2012-11-02 15:46:56 -0700122static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700123 DIR *d;
124 struct dirent *de;
125
126 if (!(d = opendir("/proc"))) {
127 printf("Failed to open /proc (%s)\n", strerror(errno));
128 return;
129 }
130
Felipe Leme635ca312016-01-05 14:23:02 -0800131 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700132 while ((de = readdir(d))) {
133 int pid;
134 int fd;
135 char cmdpath[255];
136 char cmdline[255];
137
138 if (!(pid = atoi(de->d_name))) {
139 continue;
140 }
141
Colin Crossf45fa6b2012-03-26 12:38:26 -0700142 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyna297c322016-02-05 15:33:17 -0800143
144 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
145 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
146 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700147 close(fd);
Mark Salyzyna297c322016-02-05 15:33:17 -0800148 if (cmdline[0]) {
149 helper(pid, cmdline, arg);
150 continue;
151 }
152 }
153
154 // if no cmdline, a kernel thread has comm
155 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
156 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
157 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
158 close(fd);
159 if (cmdline[1]) {
160 cmdline[0] = '[';
161 size_t len = strcspn(cmdline, "\f\b\r\n");
162 cmdline[len] = ']';
163 cmdline[len+1] = '\0';
164 }
165 }
166 if (!cmdline[0]) {
167 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700168 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700169 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700170 }
171
172 closedir(d);
173}
174
Colin Cross0c22e8b2012-11-02 15:46:56 -0700175static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800176 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700177 func(pid, cmdline);
178}
179
180void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800181 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800182 __for_each_pid(for_each_pid_helper, header, (void *)func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700183}
184
185static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
186 DIR *d;
187 struct dirent *de;
188 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800189 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700190
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700191 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700192
193 if (!(d = opendir(taskpath))) {
194 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
195 return;
196 }
197
198 func(pid, pid, cmdline);
199
200 while ((de = readdir(d))) {
201 int tid;
202 int fd;
203 char commpath[255];
204 char comm[255];
205
206 if (!(tid = atoi(de->d_name))) {
207 continue;
208 }
209
210 if (tid == pid)
211 continue;
212
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700213 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800214 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700215 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700216 strcpy(comm, "N/A");
217 } else {
218 char *c;
Mark Salyzyna297c322016-02-05 15:33:17 -0800219 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700220 close(fd);
221
222 c = strrchr(comm, '\n');
223 if (c) {
224 *c = '\0';
225 }
226 }
227 func(pid, tid, comm);
228 }
229
230 closedir(d);
231}
232
233void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800234 ON_DRY_RUN_RETURN();
Felipe Leme8620bb42015-11-10 11:04:45 -0800235 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700236}
237
238void show_wchan(int pid, int tid, const char *name) {
Felipe Leme93d705b2015-11-10 20:10:25 -0800239 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700240 char path[255];
241 char buffer[255];
Mark Salyzyna297c322016-02-05 15:33:17 -0800242 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700243 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700244
245 memset(buffer, 0, sizeof(buffer));
246
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700247 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700248 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700249 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
250 return;
251 }
252
Mark Salyzyna297c322016-02-05 15:33:17 -0800253 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
254 save_errno = errno;
255 close(fd);
256
257 if (ret < 0) {
258 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
259 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700260 }
261
Colin Cross0c22e8b2012-11-02 15:46:56 -0700262 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
263 pid == tid ? 0 : 3, "", name);
264
265 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700266
Mark Salyzyna297c322016-02-05 15:33:17 -0800267 return;
268}
269
270// print time in centiseconds
271static void snprcent(char *buffer, size_t len, size_t spc,
272 unsigned long long time) {
273 static long hz; // cache discovered hz
274
275 if (hz <= 0) {
276 hz = sysconf(_SC_CLK_TCK);
277 if (hz <= 0) {
278 hz = 1000;
279 }
280 }
281
282 // convert to centiseconds
283 time = (time * 100 + (hz / 2)) / hz;
284
285 char str[16];
286
287 snprintf(str, sizeof(str), " %llu.%02u",
288 time / 100, (unsigned)(time % 100));
289 size_t offset = strlen(buffer);
290 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
291 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
292}
293
294// print permille as a percent
295static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
296 char str[16];
297
298 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
299 size_t offset = strlen(buffer);
300 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
301 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
302}
303
304void show_showtime(int pid, const char *name) {
305 ON_DRY_RUN_RETURN();
306 char path[255];
307 char buffer[1023];
308 int fd, ret, save_errno;
309
310 memset(buffer, 0, sizeof(buffer));
311
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700312 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyna297c322016-02-05 15:33:17 -0800313 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
314 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
315 return;
316 }
317
318 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
319 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700320 close(fd);
Mark Salyzyna297c322016-02-05 15:33:17 -0800321
322 if (ret < 0) {
323 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
324 return;
325 }
326
327 // field 14 is utime
328 // field 15 is stime
329 // field 42 is iotime
330 unsigned long long utime = 0, stime = 0, iotime = 0;
331 if (sscanf(buffer,
Xia Yang60292e52016-02-16 03:05:18 -0800332 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
333 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
334 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
335 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyna297c322016-02-05 15:33:17 -0800336 &utime, &stime, &iotime) != 3) {
337 return;
338 }
339
340 unsigned long long total = utime + stime;
341 if (!total) {
342 return;
343 }
344
345 unsigned permille = (iotime * 1000 + (total / 2)) / total;
346 if (permille > 1000) {
347 permille = 1000;
348 }
349
350 // try to beautify and stabilize columns at <80 characters
351 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
352 if ((name[0] != '[') || utime) {
353 snprcent(buffer, sizeof(buffer), 57, utime);
354 }
355 snprcent(buffer, sizeof(buffer), 65, stime);
356 if ((name[0] != '[') || iotime) {
357 snprcent(buffer, sizeof(buffer), 73, iotime);
358 }
359 if (iotime) {
360 snprdec(buffer, sizeof(buffer), 79, permille);
361 }
362 puts(buffer); // adds a trailing newline
363
Colin Crossf45fa6b2012-03-26 12:38:26 -0700364 return;
365}
366
367void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800368 const char *title = "KERNEL LOG (dmesg)";
369 DurationReporter duration_reporter(title);
370 printf("------ %s ------\n", title);
371
Felipe Leme93d705b2015-11-10 20:10:25 -0800372 ON_DRY_RUN_RETURN();
Elliott Hughes5f87b312012-09-17 11:43:40 -0700373 /* Get size of kernel buffer */
374 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700375 if (size <= 0) {
376 printf("Unexpected klogctl return value: %d\n\n", size);
377 return;
378 }
379 char *buf = (char *) malloc(size + 1);
380 if (buf == NULL) {
381 printf("memory allocation failed\n\n");
382 return;
383 }
384 int retval = klogctl(KLOG_READ_ALL, buf, size);
385 if (retval < 0) {
386 printf("klogctl failure\n\n");
387 free(buf);
388 return;
389 }
390 buf[retval] = '\0';
391 printf("%s\n\n", buf);
392 free(buf);
393 return;
394}
395
396void do_showmap(int pid, const char *name) {
397 char title[255];
398 char arg[255];
399
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700400 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
401 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Leme3dba69a2016-03-17 14:59:13 -0700402 run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700403}
404
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800405static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700406 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800407 printf("------ %s (%s", title, path);
408
Colin Crossf45fa6b2012-03-26 12:38:26 -0700409 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800410 // Only show the modification time of non-device files.
411 size_t path_len = strlen(path);
412 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
413 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
414 (path_len < 3 || memcmp(path, "/d/", 3)) &&
415 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700416 char stamp[80];
417 time_t mtime = st.st_mtime;
418 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
419 printf(": %s", stamp);
420 }
421 printf(") ------\n");
422 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800423 ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
Colin Crossf45fa6b2012-03-26 12:38:26 -0700424
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800425 bool newline = false;
426 fd_set read_set;
427 struct timeval tm;
428 while (1) {
429 FD_ZERO(&read_set);
430 FD_SET(fd, &read_set);
431 /* Timeout if no data is read for 30 seconds. */
432 tm.tv_sec = 30;
433 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800434 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800435 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
436 if (ret == -1) {
437 printf("*** %s: select failed: %s\n", path, strerror(errno));
438 newline = true;
439 break;
440 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800441 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800442 printf("*** %s: Timed out after %.3fs\n", path,
443 (float) elapsed / NANOS_PER_SEC);
444 newline = true;
445 break;
446 } else {
447 char buffer[65536];
448 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
449 if (bytes_read > 0) {
450 fwrite(buffer, bytes_read, 1, stdout);
451 newline = (buffer[bytes_read-1] == '\n');
452 } else {
453 if (bytes_read == -1) {
454 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
455 newline = true;
456 }
457 break;
458 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700459 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700460 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800461 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700462 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700463
Colin Crossf45fa6b2012-03-26 12:38:26 -0700464 if (!newline) printf("\n");
465 if (title) printf("\n");
466 return 0;
467}
468
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800469/* prints the contents of a file */
470int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800471 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800472 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
473 if (fd < 0) {
474 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800475 printf("*** %s: %s\n", path, strerror(err));
476 if (title) printf("\n");
477 return -1;
478 }
479 return _dump_file_from_fd(title, path, fd);
480}
481
Felipe Leme71a74ac2016-03-17 15:43:25 -0700482int read_file_as_long(const char *path, long int *output) {
483 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
484 if (fd < 0) {
485 int err = errno;
486 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
487 return -1;
488 }
489 char buffer[50];
490 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
491 if (bytes_read == -1) {
492 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
493 return -2;
494 }
495 if (bytes_read == 0) {
496 MYLOGE("File %s is empty\n", path);
497 return -3;
498 }
499 *output = atoi(buffer);
500 return 0;
501}
502
Mark Salyzyn326842f2015-04-30 09:49:41 -0700503/* calls skip to gate calling dump_from_fd recursively
504 * in the specified directory. dump_from_fd defaults to
505 * dump_file_from_fd above when set to NULL. skip defaults
506 * to false when set to NULL. dump_from_fd will always be
507 * called with title NULL.
508 */
509int dump_files(const char *title, const char *dir,
510 bool (*skip)(const char *path),
511 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800512 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700513 DIR *dirp;
514 struct dirent *d;
515 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800516 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700517 int fd, retval = 0;
518
519 if (title) {
520 printf("------ %s (%s) ------\n", title, dir);
521 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800522 ON_DRY_RUN_RETURN(0);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700523
524 if (dir[strlen(dir) - 1] == '/') {
525 ++slash;
526 }
527 dirp = opendir(dir);
528 if (dirp == NULL) {
529 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800530 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700531 return retval;
532 }
533
534 if (!dump_from_fd) {
535 dump_from_fd = dump_file_from_fd;
536 }
537 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
538 if ((d->d_name[0] == '.')
539 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
540 || (d->d_name[1] == '\0'))) {
541 continue;
542 }
543 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
544 (d->d_type == DT_DIR) ? "/" : "");
545 if (!newpath) {
546 retval = -errno;
547 continue;
548 }
549 if (skip && (*skip)(newpath)) {
550 continue;
551 }
552 if (d->d_type == DT_DIR) {
553 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
554 if (ret < 0) {
555 retval = ret;
556 }
557 continue;
558 }
559 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
560 if (fd < 0) {
561 retval = fd;
562 printf("*** %s: %s\n", newpath, strerror(errno));
563 continue;
564 }
565 (*dump_from_fd)(NULL, newpath, fd);
566 }
567 closedir(dirp);
568 if (title) {
569 printf("\n");
570 }
571 return retval;
572}
573
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800574/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
575 * it's possible to avoid issues where opening the file itself can get
576 * stuck.
577 */
578int dump_file_from_fd(const char *title, const char *path, int fd) {
579 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());
666 return -1;
667 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800668
Felipe Leme71bbfc52015-11-23 14:14:51 -0800669 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
Felipe Leme93d705b2015-11-10 20:10:25 -0800670
Felipe Leme29c39712016-04-01 10:02:00 -0700671 int status = run_command_always(title, DONT_DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800672 va_end(ap);
673 return status;
674}
675
676int run_command_as_shell(const char *title, int timeout_seconds, const char *command, ...) {
677 DurationReporter duration_reporter(title);
678 fflush(stdout);
679
680 const char *args[1024] = {command};
681 size_t arg;
682 va_list ap;
683 va_start(ap, command);
684 if (title) printf("------ %s (%s", title, command);
685 bool null_terminated = false;
686 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
687 args[arg] = va_arg(ap, const char *);
688 if (args[arg] == nullptr) {
689 null_terminated = true;
690 break;
691 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700692 // TODO: null_terminated check is not really working; line below would crash dumpstate if
693 // nullptr is missing
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800694 if (title) printf(" %s", args[arg]);
695 }
696 if (title) printf(") ------\n");
697 fflush(stdout);
698 if (!null_terminated) {
699 // Fail now, otherwise execvp() call on run_command_always() might hang.
700 std::string cmd;
701 format_args(command, args, &cmd);
702 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
703 return -1;
704 }
705
706 ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
707
Felipe Leme29c39712016-04-01 10:02:00 -0700708 int status = run_command_always(title, DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800709 va_end(ap);
710 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800711}
712
713/* forks a command and waits for it to finish */
Felipe Leme29c39712016-04-01 10:02:00 -0700714int run_command_always(const char *title, RootMode root_mode, StdoutMode stdout_mode,
715 int timeout_seconds, const char *args[]) {
716 bool silent = (stdout_mode == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700717 // TODO: need to check if args is null-terminated, otherwise execvp will crash dumpstate
718
Felipe Leme71bbfc52015-11-23 14:14:51 -0800719 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
720 * It's a good approximation for most cases, except when calling dumpsys, where its weight
721 * should be much higher proportionally to its timeout. */
722 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800723
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800724 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800725 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700726 pid_t pid = fork();
727
728 /* handle error case */
729 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700730 if (!silent) printf("*** fork: %s\n", strerror(errno));
731 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700732 return pid;
733 }
734
735 /* handle child case */
736 if (pid == 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700737 if (root_mode == DROP_ROOT && !drop_root_user()) {
738 if (!silent) printf("*** fail todrop root before running %s: %s\n", command,
739 strerror(errno));
740 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700741 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800742 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700743
Felipe Leme29c39712016-04-01 10:02:00 -0700744 if (silent) {
745 // Redirect stderr to stdout
746 dup2(STDERR_FILENO, STDOUT_FILENO);
747 }
748
John Michelaue7b6cf12013-03-07 15:35:35 -0600749 /* make sure the child dies when dumpstate dies */
750 prctl(PR_SET_PDEATHSIG, SIGKILL);
751
Andres Morales2e671bb2014-08-21 12:38:22 -0700752 /* just ignore SIGPIPE, will go down with parent's */
753 struct sigaction sigact;
754 memset(&sigact, 0, sizeof(sigact));
755 sigact.sa_handler = SIG_IGN;
756 sigaction(SIGPIPE, &sigact, NULL);
757
Colin Crossf45fa6b2012-03-26 12:38:26 -0700758 execvp(command, (char**) args);
Felipe Lemeea160d12016-03-24 11:29:44 -0700759 // execvp's result will be handled after waitpid_with_timeout() below, but if it failed,
760 // it's safer to exit dumpstate.
761 MYLOGD("execvp on command '%s' failed (error: %s)", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700762 fflush(stdout);
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700763 // Must call _exit (instead of exit), otherwise it will corrupt the zip file.
764 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700765 }
766
767 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800768 int status;
769 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800770 uint64_t elapsed = DurationReporter::nanotime() - start;
Felipe Lemea34efb72016-03-11 09:33:32 -0800771 std::string cmd; // used to log command and its args
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800772 if (!ret) {
773 if (errno == ETIMEDOUT) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800774 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700775 if (!silent) printf("*** command '%s' timed out after %.3fs (killing pid %d)\n",
776 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800777 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800778 (float) elapsed / NANOS_PER_SEC, pid);
779 } else {
Felipe Lemea34efb72016-03-11 09:33:32 -0800780 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700781 if (!silent) printf("*** command '%s': Error after %.4fs (killing pid %d)\n",
782 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800783 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800784 (float) elapsed / NANOS_PER_SEC, pid);
785 }
786 kill(pid, SIGTERM);
787 if (!waitpid_with_timeout(pid, 5, NULL)) {
788 kill(pid, SIGKILL);
789 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700790 if (!silent) printf("could not kill command '%s' (pid %d) even with SIGKILL.\n",
791 command, pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700792 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700793 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700794 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800795 return -1;
Felipe Lemea34efb72016-03-11 09:33:32 -0800796 } else if (status) {
797 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700798 if (!silent) printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
Felipe Lemea34efb72016-03-11 09:33:32 -0800799 MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
800 return -2;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700801 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800802
803 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700804 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
805 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800806 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700807 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
808 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800809 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800810
Felipe Leme71bbfc52015-11-23 14:14:51 -0800811 if (weight > 0) {
812 update_progress(weight);
813 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800814 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700815}
816
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800817bool drop_root_user() {
818 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
819 MYLOGD("drop_root_user(): already running as Shell");
820 return true;
821 }
822 /* ensure we will keep capabilities when we drop root */
823 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
824 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
825 return false;
826 }
827
828 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
829 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC };
830 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
831 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
832 return false;
833 }
834 if (setgid(AID_SHELL) != 0) {
835 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
836 return false;
837 }
838 if (setuid(AID_SHELL) != 0) {
839 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
840 return false;
841 }
842
843 struct __user_cap_header_struct capheader;
844 struct __user_cap_data_struct capdata[2];
845 memset(&capheader, 0, sizeof(capheader));
846 memset(&capdata, 0, sizeof(capdata));
847 capheader.version = _LINUX_CAPABILITY_VERSION_3;
848 capheader.pid = 0;
849
850 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
851 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
852 capdata[0].inheritable = 0;
853 capdata[1].inheritable = 0;
854
855 if (capset(&capheader, &capdata[0]) < 0) {
856 MYLOGE("capset failed: %s\n", strerror(errno));
857 return false;
858 }
859
860 return true;
861}
862
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800863void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
864 if (args.size() > 1000) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800865 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800866 return;
867 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800868 const char *am_args[1024] = { "/system/bin/am", "broadcast", "--user", "0", "-a",
869 action.c_str() };
870 size_t am_index = 5; // Starts at the index of last initial value above.
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800871 for (const std::string& arg : args) {
872 am_args[++am_index] = arg.c_str();
873 }
874 // Always terminate with NULL.
875 am_args[am_index + 1] = NULL;
Felipe Lemea34efb72016-03-11 09:33:32 -0800876 std::string args_string;
877 format_args(am_index + 1, am_args, &args_string);
878 MYLOGD("send_broadcast command: %s\n", args_string.c_str());
Felipe Leme29c39712016-04-01 10:02:00 -0700879 run_command_always(NULL, DROP_ROOT, REDIRECT_TO_STDERR, 20, am_args);
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800880}
881
Colin Crossf45fa6b2012-03-26 12:38:26 -0700882size_t num_props = 0;
883static char* props[2000];
884
885static void print_prop(const char *key, const char *name, void *user) {
886 (void) user;
887 if (num_props < sizeof(props) / sizeof(props[0])) {
888 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
889 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
890 props[num_props++] = strdup(buf);
891 }
892}
893
894static int compare_prop(const void *a, const void *b) {
895 return strcmp(*(char * const *) a, *(char * const *) b);
896}
897
898/* prints all the system properties */
899void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800900 const char* title = "SYSTEM PROPERTIES";
901 DurationReporter duration_reporter(title);
902 printf("------ %s ------\n", title);
Felipe Leme93d705b2015-11-10 20:10:25 -0800903 ON_DRY_RUN_RETURN();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700904 size_t i;
905 num_props = 0;
906 property_list(print_prop, NULL);
907 qsort(&props, num_props, sizeof(props[0]), compare_prop);
908
Colin Crossf45fa6b2012-03-26 12:38:26 -0700909 for (i = 0; i < num_props; ++i) {
910 fputs(props[i], stdout);
911 free(props[i]);
912 }
913 printf("\n");
914}
915
Felipe Leme2628e9e2016-04-12 16:36:51 -0700916int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700917 int s = android_get_control_socket(service);
918 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800919 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700920 exit(1);
921 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700922 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700923 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800924 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700925 exit(1);
926 }
927
928 struct sockaddr addr;
929 socklen_t alen = sizeof(addr);
930 int fd = accept(s, &addr, &alen);
931 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800932 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700933 exit(1);
934 }
935
Felipe Leme2628e9e2016-04-12 16:36:51 -0700936 return fd;
937}
938
939/* redirect output to a service control socket */
940void redirect_to_socket(FILE *redirect, const char *service) {
941 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700942 fflush(redirect);
943 dup2(fd, fileno(redirect));
944 close(fd);
945}
946
Felipe Leme2628e9e2016-04-12 16:36:51 -0700947// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800948void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800949 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700950
951 /* skip initial slash */
952 if (chp[0] == '/')
953 chp++;
954
955 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800956 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700957 while (chp && chp[0]) {
958 chp = strchr(chp, '/');
959 if (chp) {
960 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800961 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800962 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800963 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800964 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800965 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800966 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800967 }
968 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700969 *chp++ = '/';
970 }
971 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800972}
973
974/* redirect output to a file */
975void redirect_to_file(FILE *redirect, char *path) {
976 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700977
Felipe Leme608385d2016-02-01 10:35:38 -0800978 int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800979 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700980 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800981 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700982 exit(1);
983 }
984
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800985 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700986 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700987}
988
Jeff Brownbf7f4922012-06-07 16:40:01 -0700989static bool should_dump_native_traces(const char* path) {
990 for (const char** p = native_processes_to_dump; *p; p++) {
991 if (!strcmp(*p, path)) {
992 return true;
993 }
994 }
995 return false;
996}
997
998/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
999const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -08001000 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Leme93d705b2015-11-10 20:10:25 -08001001 ON_DRY_RUN_RETURN(NULL);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001002 const char* result = NULL;
1003
Colin Crossf45fa6b2012-03-26 12:38:26 -07001004 char traces_path[PROPERTY_VALUE_MAX] = "";
1005 property_get("dalvik.vm.stack-trace-file", traces_path, "");
1006 if (!traces_path[0]) return NULL;
1007
1008 /* move the old traces.txt (if any) out of the way temporarily */
1009 char anr_traces_path[PATH_MAX];
1010 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
1011 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
1012 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001013 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001014 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
1015 }
1016
Colin Crossf45fa6b2012-03-26 12:38:26 -07001017 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001018 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 -08001019 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001020 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001021 MYLOGE("%s: %s\n", traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001022 return NULL;
1023 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001024 int chmod_ret = fchmod(fd, 0666);
1025 if (chmod_ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001026 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001027 close(fd);
1028 return NULL;
1029 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001030
Felipe Leme8620bb42015-11-10 11:04:45 -08001031 /* Variables below must be initialized before 'goto' statements */
1032 int dalvik_found = 0;
1033 int ifd, wfd = -1;
1034
Colin Crossf45fa6b2012-03-26 12:38:26 -07001035 /* walk /proc and kill -QUIT all Dalvik processes */
1036 DIR *proc = opendir("/proc");
1037 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001038 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001039 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001040 }
1041
1042 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001043 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001044 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001045 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001046 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001047 }
1048
Felipe Leme8620bb42015-11-10 11:04:45 -08001049 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001050 if (wfd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001051 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001052 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001053 }
1054
1055 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001056 while ((d = readdir(proc))) {
1057 int pid = atoi(d->d_name);
1058 if (pid <= 0) continue;
1059
Jeff Brownbf7f4922012-06-07 16:40:01 -07001060 char path[PATH_MAX];
1061 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001062 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001063 ssize_t len = readlink(path, data, sizeof(data) - 1);
1064 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001065 continue;
1066 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001067 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001068
Colin Cross0d6180f2014-07-16 19:00:46 -07001069 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001070 /* skip zygote -- it won't dump its stack anyway */
1071 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001072 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001073 len = read(cfd, data, sizeof(data) - 1);
1074 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001075 if (len <= 0) {
1076 continue;
1077 }
1078 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001079 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001080 continue;
1081 }
1082
1083 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -08001084 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001085 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001086 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001087 continue;
1088 }
1089
1090 /* wait for the writable-close notification from inotify */
1091 struct pollfd pfd = { ifd, POLLIN, 0 };
Nick Vaccaro85453ec2014-04-30 11:19:23 -07001092 int ret = poll(&pfd, 1, 5000); /* 5 sec timeout */
Jeff Brownbf7f4922012-06-07 16:40:01 -07001093 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001094 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001095 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001096 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001097 } else {
1098 struct inotify_event ie;
1099 read(ifd, &ie, sizeof(ie));
1100 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001101
1102 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001103 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001104 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001105 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001106 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001107 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001108 } else if (should_dump_native_traces(data)) {
1109 /* dump native process if appropriate */
1110 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001111 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001112 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001113 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -08001114 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001115
1116 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1117 if (timeout_failures == 3) {
1118 dprintf(fd, "too many stack dump failures, skipping...\n");
1119 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1120 dprintf(fd, "dumping failed, likely due to a timeout\n");
1121 timeout_failures++;
1122 } else {
1123 timeout_failures = 0;
1124 }
1125 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001126 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001127 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001128 }
1129 }
1130
Colin Crossf45fa6b2012-03-26 12:38:26 -07001131 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001132 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001133 }
1134
1135 static char dump_traces_path[PATH_MAX];
1136 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
1137 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
1138 if (rename(traces_path, dump_traces_path)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001139 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001140 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001141 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001142 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001143
1144 /* replace the saved [ANR] traces.txt file */
1145 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001146
1147error_close_ifd:
1148 close(ifd);
1149error_close_fd:
1150 close(fd);
1151 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001152}
1153
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001154void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001155 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme93d705b2015-11-10 20:10:25 -08001156 ON_DRY_RUN_RETURN();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001157 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1158 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001159 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001160 if (!fp) {
1161 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1162 return;
1163 }
1164 char table[16];
1165 // Each line has an integer (the table number), a space, and a string (the table name). We only
1166 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1167 // Add a fixed max limit so this doesn't go awry.
1168 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
1169 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
1170 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
1171 }
1172 fclose(fp);
1173}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001174
1175/* overall progress */
1176int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001177int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001178int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001179
1180// TODO: make this function thread safe if sections are generated in parallel.
1181void update_progress(int delta) {
1182 if (!do_update_progress) return;
1183
1184 progress += delta;
1185
1186 char key[PROPERTY_KEY_MAX];
1187 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001188
1189 // adjusts max on the fly
1190 if (progress > weight_total) {
1191 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001192 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001193 weight_total = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001194 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
1195 snprintf(value, sizeof(value), "%d", weight_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001196 int status = property_set(key, value);
1197 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001198 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001199 key, value, status);
1200 }
1201 }
1202
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001203 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
1204 snprintf(value, sizeof(value), "%d", progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001205
Felipe Leme107a05f2016-03-08 15:11:15 -08001206 if (progress % 100 == 0) {
1207 // We don't want to spam logcat, so only log multiples of 100.
1208 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1209 } else {
1210 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1211 // directly for debuggging.
1212 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1213 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001214
1215 int status = property_set(key, value);
1216 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001217 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001218 key, value, status);
1219 }
1220}
Felipe Lemee338bf62015-12-07 14:03:50 -08001221
Felipe Leme3634a1e2015-12-09 10:11:47 -08001222void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -08001223 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
Felipe Leme29c39712016-04-01 10:02:00 -07001224 run_command_always(NULL, DONT_DROP_ROOT, REDIRECT_TO_STDERR, 10, args);
Felipe Lemee338bf62015-12-07 14:03:50 -08001225}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001226
Felipe Leme0c80cf02016-01-05 13:25:34 -08001227void vibrate(FILE* vibrator, int ms) {
1228 fprintf(vibrator, "%d\n", ms);
1229 fflush(vibrator);
1230}
1231
1232bool is_dir(const char* pathname) {
1233 struct stat info;
1234 if (stat(pathname, &info) == -1) {
1235 return false;
1236 }
1237 return S_ISDIR(info.st_mode);
1238}
1239
1240time_t get_mtime(int fd, time_t default_mtime) {
1241 struct stat info;
1242 if (fstat(fd, &info) == -1) {
1243 return default_mtime;
1244 }
1245 return info.st_mtime;
1246}
1247
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001248void dump_emmc_ecsd(const char *ext_csd_path) {
1249 static const size_t EXT_CSD_REV = 192;
1250 static const size_t EXT_PRE_EOL_INFO = 267;
1251 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
1252 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
1253 struct hex {
1254 char str[2];
1255 } buffer[512];
1256 int fd, ext_csd_rev, ext_pre_eol_info;
1257 ssize_t bytes_read;
1258 static const char *ver_str[] = {
1259 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1260 };
1261 static const char *eol_str[] = {
1262 "Undefined",
1263 "Normal",
1264 "Warning (consumed 80% of reserve)",
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001265 "Urgent (consumed 90% of reserve)"
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001266 };
1267
1268 printf("------ %s Extended CSD ------\n", ext_csd_path);
1269
1270 fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
1271 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
1272 if (fd < 0) {
1273 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1274 return;
1275 }
1276
1277 bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
1278 close(fd);
1279 if (bytes_read < 0) {
1280 printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1281 return;
1282 }
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001283 if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001284 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1285 return;
1286 }
1287
1288 ext_csd_rev = 0;
1289 if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
1290 printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
1291 ext_csd_path, buffer[EXT_CSD_REV].str);
1292 return;
1293 }
1294
1295 printf("rev 1.%d (MMC %s)\n",
1296 ext_csd_rev,
1297 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1298 ver_str[ext_csd_rev] :
1299 "Unknown");
1300 if (ext_csd_rev < 7) {
1301 printf("\n");
1302 return;
1303 }
1304
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001305 if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001306 printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1307 return;
1308 }
1309
1310 ext_pre_eol_info = 0;
1311 if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1312 printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1313 ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1314 return;
1315 }
1316 printf("PRE_EOL_INFO %d (MMC %s)\n",
1317 ext_pre_eol_info,
1318 eol_str[(ext_pre_eol_info < (int)
1319 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1320 ext_pre_eol_info : 0]);
1321
1322 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1323 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1324 ++lifetime) {
1325 int ext_device_life_time_est;
1326 static const char *est_str[] = {
1327 "Undefined",
1328 "0-10% of device lifetime used",
1329 "10-20% of device lifetime used",
1330 "20-30% of device lifetime used",
1331 "30-40% of device lifetime used",
1332 "40-50% of device lifetime used",
1333 "50-60% of device lifetime used",
1334 "60-70% of device lifetime used",
1335 "70-80% of device lifetime used",
1336 "80-90% of device lifetime used",
1337 "90-100% of device lifetime used",
1338 "Exceeded the maximum estimated device lifetime",
1339 };
1340
Mark Salyzyn4b45d672015-12-11 10:41:52 -08001341 if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001342 printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1343 break;
1344 }
1345
1346 ext_device_life_time_est = 0;
1347 if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1348 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1349 ext_csd_path,
1350 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1351 buffer[lifetime].str);
1352 continue;
1353 }
1354 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1355 (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1356 ext_device_life_time_est,
1357 est_str[(ext_device_life_time_est < (int)
1358 (sizeof(est_str) / sizeof(est_str[0]))) ?
1359 ext_device_life_time_est : 0]);
1360 }
1361
1362 printf("\n");
1363}
Felipe Leme88c79332016-02-22 11:06:49 -08001364
Felipe Lemea34efb72016-03-11 09:33:32 -08001365// TODO: refactor all those commands that convert args
1366void format_args(int argc, const char *argv[], std::string *args) {
1367 LOG_ALWAYS_FATAL_IF(args == nullptr);
Felipe Leme88c79332016-02-22 11:06:49 -08001368 for (int i = 0; i < argc; i++) {
Felipe Lemea34efb72016-03-11 09:33:32 -08001369 args->append(argv[i]);
1370 if (i < argc -1) {
1371 args->append(" ");
1372 }
Felipe Leme88c79332016-02-22 11:06:49 -08001373 }
Felipe Lemea34efb72016-03-11 09:33:32 -08001374}
1375void format_args(const char* command, const char *args[], std::string *string) {
1376 LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr);
1377 string->append(command);
1378 if (args[0] == nullptr) return;
1379 string->append(" ");
1380
1381 for (int arg = 1; arg <= 1000; ++arg) {
1382 if (args[arg] == nullptr) return;
1383 string->append(args[arg]);
1384 if (args[arg+1] != nullptr) {
1385 string->append(" ");
1386 }
1387 }
Felipe Lemeea160d12016-03-24 11:29:44 -07001388 // TODO: not really working: if NULL is missing, it will crash dumpstate.
Felipe Lemea34efb72016-03-11 09:33:32 -08001389 MYLOGE("internal error: missing NULL entry on %s", string->c_str());
Felipe Leme88c79332016-02-22 11:06:49 -08001390}