blob: 4076f6ae3746d4e545548a35bfa7787f555cdf2a [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <poll.h>
22#include <signal.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080026#include <string>
Colin Crossf45fa6b2012-03-26 12:38:26 -070027#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080028#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070029#include <sys/inotify.h>
30#include <sys/stat.h>
31#include <sys/time.h>
32#include <sys/wait.h>
33#include <sys/klog.h>
34#include <time.h>
35#include <unistd.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080036#include <vector>
John Michelaue7b6cf12013-03-07 15:35:35 -060037#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038
Felipe Leme71bbfc52015-11-23 14:14:51 -080039#define LOG_TAG "dumpstate"
Mark Salyzyn261a7332016-05-24 12:38:40 -070040
Mark Salyzyn290f4b92016-05-16 08:33:59 -070041#include <android-base/file.h>
Jeff Brownbf7f4922012-06-07 16:40:01 -070042#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080043#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070044#include <cutils/properties.h>
45#include <cutils/sockets.h>
46#include <private/android_filesystem_config.h>
47
Robert Craig95798372013-04-04 06:33:10 -040048#include <selinux/android.h>
49
Colin Crossf45fa6b2012-03-26 12:38:26 -070050#include "dumpstate.h"
51
Jeff Brown1dc94e32014-09-11 14:15:27 -070052static const int64_t NANOS_PER_SEC = 1000000000;
53
Felipe Leme61884122016-06-13 09:23:30 -070054static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
55
Jeff Brownbf7f4922012-06-07 16:40:01 -070056/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070057// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070058static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080059 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080060 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070061 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070062 "/system/bin/mediacodec", // media.codec
63 "/system/bin/mediadrmserver",
64 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070065 "/system/bin/mediaserver",
66 "/system/bin/sdcard",
67 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070068 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070069 NULL,
70};
71
Felipe Leme608385d2016-02-01 10:35:38 -080072DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
73
74DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme78f2c862015-12-21 09:55:22 -080075 title_ = title;
76 if (title) {
77 started_ = DurationReporter::nanotime();
78 }
Felipe Leme608385d2016-02-01 10:35:38 -080079 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -080080}
81
82DurationReporter::~DurationReporter() {
83 if (title_) {
84 uint64_t elapsed = DurationReporter::nanotime() - started_;
85 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme608385d2016-02-01 10:35:38 -080086 if (out_) {
87 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
88 (float) elapsed / NANOS_PER_SEC, title_);
89 } else {
Felipe Lemecbce55d2016-02-08 09:53:18 -080090 MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -080091 }
Felipe Leme78f2c862015-12-21 09:55:22 -080092 }
93}
94
95uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080096 struct timespec ts;
97 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -080098 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -080099}
100
John Spurlock5ecd4be2014-01-29 14:14:40 -0500101void for_each_userid(void (*func)(int), const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700102 if (is_dry_run()) return;
103
John Spurlock5ecd4be2014-01-29 14:14:40 -0500104 DIR *d;
105 struct dirent *de;
106
107 if (header) printf("\n------ %s ------\n", header);
108 func(0);
109
110 if (!(d = opendir("/data/system/users"))) {
111 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
112 return;
113 }
114
115 while ((de = readdir(d))) {
116 int userid;
117 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
118 continue;
119 }
120 func(userid);
121 }
122
123 closedir(d);
124}
125
Colin Cross0c22e8b2012-11-02 15:46:56 -0700126static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700127 DIR *d;
128 struct dirent *de;
129
130 if (!(d = opendir("/proc"))) {
131 printf("Failed to open /proc (%s)\n", strerror(errno));
132 return;
133 }
134
Felipe Leme635ca312016-01-05 14:23:02 -0800135 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700136 while ((de = readdir(d))) {
137 int pid;
138 int fd;
139 char cmdpath[255];
140 char cmdline[255];
141
142 if (!(pid = atoi(de->d_name))) {
143 continue;
144 }
145
Colin Crossf45fa6b2012-03-26 12:38:26 -0700146 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800147
148 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
149 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
150 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700151 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800152 if (cmdline[0]) {
153 helper(pid, cmdline, arg);
154 continue;
155 }
156 }
157
158 // if no cmdline, a kernel thread has comm
159 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
160 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
161 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
162 close(fd);
163 if (cmdline[1]) {
164 cmdline[0] = '[';
165 size_t len = strcspn(cmdline, "\f\b\r\n");
166 cmdline[len] = ']';
167 cmdline[len+1] = '\0';
168 }
169 }
170 if (!cmdline[0]) {
171 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700172 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700173 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700174 }
175
176 closedir(d);
177}
178
Colin Cross0c22e8b2012-11-02 15:46:56 -0700179static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800180 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700181 func(pid, cmdline);
182}
183
184void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700185 if (is_dry_run()) return;
186
Felipe Leme515eb0d2015-12-14 15:09:56 -0800187 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700188}
189
190static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
191 DIR *d;
192 struct dirent *de;
193 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800194 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700195
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700196 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700197
198 if (!(d = opendir(taskpath))) {
199 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
200 return;
201 }
202
203 func(pid, pid, cmdline);
204
205 while ((de = readdir(d))) {
206 int tid;
207 int fd;
208 char commpath[255];
209 char comm[255];
210
211 if (!(tid = atoi(de->d_name))) {
212 continue;
213 }
214
215 if (tid == pid)
216 continue;
217
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700218 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800219 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700220 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700221 strcpy(comm, "N/A");
222 } else {
223 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800224 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700225 close(fd);
226
227 c = strrchr(comm, '\n');
228 if (c) {
229 *c = '\0';
230 }
231 }
232 func(pid, tid, comm);
233 }
234
235 closedir(d);
236}
237
238void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700239 if (is_dry_run()) return;
240
Felipe Leme8620bb42015-11-10 11:04:45 -0800241 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700242}
243
244void show_wchan(int pid, int tid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700245 if (is_dry_run()) return;
246
Colin Crossf45fa6b2012-03-26 12:38:26 -0700247 char path[255];
248 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800249 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700250 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700251
252 memset(buffer, 0, sizeof(buffer));
253
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700254 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700255 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700256 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
257 return;
258 }
259
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800260 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
261 save_errno = errno;
262 close(fd);
263
264 if (ret < 0) {
265 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
266 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700267 }
268
Colin Cross0c22e8b2012-11-02 15:46:56 -0700269 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
270 pid == tid ? 0 : 3, "", name);
271
272 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700273
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800274 return;
275}
276
277// print time in centiseconds
278static void snprcent(char *buffer, size_t len, size_t spc,
279 unsigned long long time) {
280 static long hz; // cache discovered hz
281
282 if (hz <= 0) {
283 hz = sysconf(_SC_CLK_TCK);
284 if (hz <= 0) {
285 hz = 1000;
286 }
287 }
288
289 // convert to centiseconds
290 time = (time * 100 + (hz / 2)) / hz;
291
292 char str[16];
293
294 snprintf(str, sizeof(str), " %llu.%02u",
295 time / 100, (unsigned)(time % 100));
296 size_t offset = strlen(buffer);
297 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
298 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
299}
300
301// print permille as a percent
302static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
303 char str[16];
304
305 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
306 size_t offset = strlen(buffer);
307 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
308 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
309}
310
311void show_showtime(int pid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700312 if (is_dry_run()) return;
313
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800314 char path[255];
315 char buffer[1023];
316 int fd, ret, save_errno;
317
318 memset(buffer, 0, sizeof(buffer));
319
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700320 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800321 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
322 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
323 return;
324 }
325
326 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
327 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700328 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800329
330 if (ret < 0) {
331 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
332 return;
333 }
334
335 // field 14 is utime
336 // field 15 is stime
337 // field 42 is iotime
338 unsigned long long utime = 0, stime = 0, iotime = 0;
339 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800340 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
341 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
342 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
343 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800344 &utime, &stime, &iotime) != 3) {
345 return;
346 }
347
348 unsigned long long total = utime + stime;
349 if (!total) {
350 return;
351 }
352
353 unsigned permille = (iotime * 1000 + (total / 2)) / total;
354 if (permille > 1000) {
355 permille = 1000;
356 }
357
358 // try to beautify and stabilize columns at <80 characters
359 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
360 if ((name[0] != '[') || utime) {
361 snprcent(buffer, sizeof(buffer), 57, utime);
362 }
363 snprcent(buffer, sizeof(buffer), 65, stime);
364 if ((name[0] != '[') || iotime) {
365 snprcent(buffer, sizeof(buffer), 73, iotime);
366 }
367 if (iotime) {
368 snprdec(buffer, sizeof(buffer), 79, permille);
369 }
370 puts(buffer); // adds a trailing newline
371
Colin Crossf45fa6b2012-03-26 12:38:26 -0700372 return;
373}
374
375void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800376 const char *title = "KERNEL LOG (dmesg)";
377 DurationReporter duration_reporter(title);
378 printf("------ %s ------\n", title);
379
Felipe Lemed402e7d2016-08-03 09:22:27 -0700380 if (is_dry_run()) return;
381
Elliott Hughes5f87b312012-09-17 11:43:40 -0700382 /* Get size of kernel buffer */
383 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700384 if (size <= 0) {
385 printf("Unexpected klogctl return value: %d\n\n", size);
386 return;
387 }
388 char *buf = (char *) malloc(size + 1);
389 if (buf == NULL) {
390 printf("memory allocation failed\n\n");
391 return;
392 }
393 int retval = klogctl(KLOG_READ_ALL, buf, size);
394 if (retval < 0) {
395 printf("klogctl failure\n\n");
396 free(buf);
397 return;
398 }
399 buf[retval] = '\0';
400 printf("%s\n\n", buf);
401 free(buf);
402 return;
403}
404
405void do_showmap(int pid, const char *name) {
406 char title[255];
407 char arg[255];
408
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700409 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
410 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Leme3dba69a2016-03-17 14:59:13 -0700411 run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700412}
413
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800414static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700415 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800416 printf("------ %s (%s", title, path);
417
Colin Crossf45fa6b2012-03-26 12:38:26 -0700418 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800419 // Only show the modification time of non-device files.
420 size_t path_len = strlen(path);
421 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
422 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
423 (path_len < 3 || memcmp(path, "/d/", 3)) &&
424 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700425 char stamp[80];
426 time_t mtime = st.st_mtime;
427 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
428 printf(": %s", stamp);
429 }
430 printf(") ------\n");
431 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700432 if (is_dry_run()) {
433 update_progress(WEIGHT_FILE);
434 close(fd);
435 return 0;
436 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700437
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800438 bool newline = false;
439 fd_set read_set;
440 struct timeval tm;
441 while (1) {
442 FD_ZERO(&read_set);
443 FD_SET(fd, &read_set);
444 /* Timeout if no data is read for 30 seconds. */
445 tm.tv_sec = 30;
446 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800447 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800448 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
449 if (ret == -1) {
450 printf("*** %s: select failed: %s\n", path, strerror(errno));
451 newline = true;
452 break;
453 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800454 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800455 printf("*** %s: Timed out after %.3fs\n", path,
456 (float) elapsed / NANOS_PER_SEC);
457 newline = true;
458 break;
459 } else {
460 char buffer[65536];
461 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
462 if (bytes_read > 0) {
463 fwrite(buffer, bytes_read, 1, stdout);
464 newline = (buffer[bytes_read-1] == '\n');
465 } else {
466 if (bytes_read == -1) {
467 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
468 newline = true;
469 }
470 break;
471 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700472 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700473 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800474 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700475 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700476
Colin Crossf45fa6b2012-03-26 12:38:26 -0700477 if (!newline) printf("\n");
478 if (title) printf("\n");
479 return 0;
480}
481
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800482/* prints the contents of a file */
483int dump_file(const char *title, const char *path) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800484 DurationReporter duration_reporter(title);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800485 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
486 if (fd < 0) {
487 int err = errno;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800488 printf("*** %s: %s\n", path, strerror(err));
489 if (title) printf("\n");
490 return -1;
491 }
492 return _dump_file_from_fd(title, path, fd);
493}
494
Felipe Leme71a74ac2016-03-17 15:43:25 -0700495int read_file_as_long(const char *path, long int *output) {
496 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
497 if (fd < 0) {
498 int err = errno;
499 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
500 return -1;
501 }
502 char buffer[50];
503 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
504 if (bytes_read == -1) {
505 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
506 return -2;
507 }
508 if (bytes_read == 0) {
509 MYLOGE("File %s is empty\n", path);
510 return -3;
511 }
512 *output = atoi(buffer);
513 return 0;
514}
515
Mark Salyzyn326842f2015-04-30 09:49:41 -0700516/* calls skip to gate calling dump_from_fd recursively
517 * in the specified directory. dump_from_fd defaults to
518 * dump_file_from_fd above when set to NULL. skip defaults
519 * to false when set to NULL. dump_from_fd will always be
520 * called with title NULL.
521 */
522int dump_files(const char *title, const char *dir,
523 bool (*skip)(const char *path),
524 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800525 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700526 DIR *dirp;
527 struct dirent *d;
528 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800529 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700530 int fd, retval = 0;
531
532 if (title) {
533 printf("------ %s (%s) ------\n", title, dir);
534 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700535 if (is_dry_run()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700536
537 if (dir[strlen(dir) - 1] == '/') {
538 ++slash;
539 }
540 dirp = opendir(dir);
541 if (dirp == NULL) {
542 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800543 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700544 return retval;
545 }
546
547 if (!dump_from_fd) {
548 dump_from_fd = dump_file_from_fd;
549 }
550 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
551 if ((d->d_name[0] == '.')
552 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
553 || (d->d_name[1] == '\0'))) {
554 continue;
555 }
556 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
557 (d->d_type == DT_DIR) ? "/" : "");
558 if (!newpath) {
559 retval = -errno;
560 continue;
561 }
562 if (skip && (*skip)(newpath)) {
563 continue;
564 }
565 if (d->d_type == DT_DIR) {
566 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
567 if (ret < 0) {
568 retval = ret;
569 }
570 continue;
571 }
572 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
573 if (fd < 0) {
574 retval = fd;
575 printf("*** %s: %s\n", newpath, strerror(errno));
576 continue;
577 }
578 (*dump_from_fd)(NULL, newpath, fd);
579 }
580 closedir(dirp);
581 if (title) {
582 printf("\n");
583 }
584 return retval;
585}
586
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800587/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
588 * it's possible to avoid issues where opening the file itself can get
589 * stuck.
590 */
591int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700592 if (is_dry_run()) return 0;
593
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800594 int flags = fcntl(fd, F_GETFL);
595 if (flags == -1) {
596 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800597 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800598 return -1;
599 } else if (!(flags & O_NONBLOCK)) {
600 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800601 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800602 return -1;
603 }
604 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700605}
606
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800607bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
608 sigset_t child_mask, old_mask;
609 sigemptyset(&child_mask);
610 sigaddset(&child_mask, SIGCHLD);
611
612 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
613 printf("*** sigprocmask failed: %s\n", strerror(errno));
614 return false;
615 }
616
617 struct timespec ts;
618 ts.tv_sec = timeout_seconds;
619 ts.tv_nsec = 0;
620 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
621 int saved_errno = errno;
622 // Set the signals back the way they were.
623 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
624 printf("*** sigprocmask failed: %s\n", strerror(errno));
625 if (ret == 0) {
626 return false;
627 }
628 }
629 if (ret == -1) {
630 errno = saved_errno;
631 if (errno == EAGAIN) {
632 errno = ETIMEDOUT;
633 } else {
634 printf("*** sigtimedwait failed: %s\n", strerror(errno));
635 }
636 return false;
637 }
638
639 pid_t child_pid = waitpid(pid, status, WNOHANG);
640 if (child_pid != pid) {
641 if (child_pid != -1) {
642 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
643 } else {
644 printf("*** waitpid failed: %s\n", strerror(errno));
645 }
646 return false;
647 }
648 return true;
649}
650
Felipe Lemea34efb72016-03-11 09:33:32 -0800651// TODO: refactor all those commands that convert args
652void format_args(const char* command, const char *args[], std::string *string);
653
Colin Crossf45fa6b2012-03-26 12:38:26 -0700654int run_command(const char *title, int timeout_seconds, const char *command, ...) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800655 DurationReporter duration_reporter(title);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700656 fflush(stdout);
Felipe Leme93d705b2015-11-10 20:10:25 -0800657
Felipe Lemedc42bda2016-06-30 14:27:04 -0700658 const char *args[ARG_MAX] = {command};
Felipe Leme93d705b2015-11-10 20:10:25 -0800659 size_t arg;
660 va_list ap;
661 va_start(ap, command);
662 if (title) printf("------ %s (%s", title, command);
Felipe Lemea34efb72016-03-11 09:33:32 -0800663 bool null_terminated = false;
Felipe Leme93d705b2015-11-10 20:10:25 -0800664 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
665 args[arg] = va_arg(ap, const char *);
Felipe Lemea34efb72016-03-11 09:33:32 -0800666 if (args[arg] == nullptr) {
667 null_terminated = true;
668 break;
669 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700670 // TODO: null_terminated check is not really working; line below would crash dumpstate if
671 // nullptr is missing
Felipe Leme93d705b2015-11-10 20:10:25 -0800672 if (title) printf(" %s", args[arg]);
673 }
674 if (title) printf(") ------\n");
675 fflush(stdout);
Felipe Lemea34efb72016-03-11 09:33:32 -0800676 if (!null_terminated) {
677 // Fail now, otherwise execvp() call on run_command_always() might hang.
678 std::string cmd;
679 format_args(command, args, &cmd);
680 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
Adam Buchbinder8ede5472016-05-23 13:18:52 -0700681 va_end(ap);
Felipe Lemea34efb72016-03-11 09:33:32 -0800682 return -1;
683 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800684
Felipe Lemed402e7d2016-08-03 09:22:27 -0700685 int status = 0;
686 if (is_dry_run()) {
687 update_progress(timeout_seconds);
688 } else {
689 status = run_command_always(title, DONT_DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
690 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800691 va_end(ap);
692 return status;
693}
694
695int run_command_as_shell(const char *title, int timeout_seconds, const char *command, ...) {
696 DurationReporter duration_reporter(title);
697 fflush(stdout);
698
Felipe Lemedc42bda2016-06-30 14:27:04 -0700699 const char *args[ARG_MAX] = {command};
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800700 size_t arg;
701 va_list ap;
702 va_start(ap, command);
703 if (title) printf("------ %s (%s", title, command);
704 bool null_terminated = false;
705 for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
706 args[arg] = va_arg(ap, const char *);
707 if (args[arg] == nullptr) {
708 null_terminated = true;
709 break;
710 }
Felipe Lemeea160d12016-03-24 11:29:44 -0700711 // TODO: null_terminated check is not really working; line below would crash dumpstate if
712 // nullptr is missing
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800713 if (title) printf(" %s", args[arg]);
714 }
715 if (title) printf(") ------\n");
716 fflush(stdout);
717 if (!null_terminated) {
718 // Fail now, otherwise execvp() call on run_command_always() might hang.
719 std::string cmd;
720 format_args(command, args, &cmd);
721 MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
Adam Buchbinder8ede5472016-05-23 13:18:52 -0700722 va_end(ap);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800723 return -1;
724 }
725
Felipe Lemed402e7d2016-08-03 09:22:27 -0700726 int status = 0;
727 if (is_dry_run()) {
728 update_progress(timeout_seconds);
729 } else {
730 status = run_command_always(title, DROP_ROOT, NORMAL_STDOUT, timeout_seconds, args);
731 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800732 va_end(ap);
733 return status;
Felipe Leme93d705b2015-11-10 20:10:25 -0800734}
735
736/* forks a command and waits for it to finish */
Felipe Leme29c39712016-04-01 10:02:00 -0700737int run_command_always(const char *title, RootMode root_mode, StdoutMode stdout_mode,
738 int timeout_seconds, const char *args[]) {
739 bool silent = (stdout_mode == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700740 // TODO: need to check if args is null-terminated, otherwise execvp will crash dumpstate
741
Felipe Leme71bbfc52015-11-23 14:14:51 -0800742 /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
743 * It's a good approximation for most cases, except when calling dumpsys, where its weight
744 * should be much higher proportionally to its timeout. */
745 int weight = timeout_seconds;
Felipe Leme93d705b2015-11-10 20:10:25 -0800746
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800747 const char *command = args[0];
Felipe Leme78f2c862015-12-21 09:55:22 -0800748 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700749 pid_t pid = fork();
750
751 /* handle error case */
752 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700753 if (!silent) printf("*** fork: %s\n", strerror(errno));
754 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700755 return pid;
756 }
757
758 /* handle child case */
759 if (pid == 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700760 if (root_mode == DROP_ROOT && !drop_root_user()) {
761 if (!silent) printf("*** fail todrop root before running %s: %s\n", command,
762 strerror(errno));
763 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700764 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800765 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700766
Felipe Leme29c39712016-04-01 10:02:00 -0700767 if (silent) {
768 // Redirect stderr to stdout
769 dup2(STDERR_FILENO, STDOUT_FILENO);
770 }
771
John Michelaue7b6cf12013-03-07 15:35:35 -0600772 /* make sure the child dies when dumpstate dies */
773 prctl(PR_SET_PDEATHSIG, SIGKILL);
774
Andres Morales2e671bb2014-08-21 12:38:22 -0700775 /* just ignore SIGPIPE, will go down with parent's */
776 struct sigaction sigact;
777 memset(&sigact, 0, sizeof(sigact));
778 sigact.sa_handler = SIG_IGN;
779 sigaction(SIGPIPE, &sigact, NULL);
780
Colin Crossf45fa6b2012-03-26 12:38:26 -0700781 execvp(command, (char**) args);
Felipe Lemeea160d12016-03-24 11:29:44 -0700782 // execvp's result will be handled after waitpid_with_timeout() below, but if it failed,
783 // it's safer to exit dumpstate.
784 MYLOGD("execvp on command '%s' failed (error: %s)", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700785 fflush(stdout);
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700786 // Must call _exit (instead of exit), otherwise it will corrupt the zip file.
787 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700788 }
789
790 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800791 int status;
792 bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800793 uint64_t elapsed = DurationReporter::nanotime() - start;
Felipe Lemea34efb72016-03-11 09:33:32 -0800794 std::string cmd; // used to log command and its args
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800795 if (!ret) {
796 if (errno == ETIMEDOUT) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800797 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700798 if (!silent) printf("*** command '%s' timed out after %.3fs (killing pid %d)\n",
799 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800800 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800801 (float) elapsed / NANOS_PER_SEC, pid);
802 } else {
Felipe Lemea34efb72016-03-11 09:33:32 -0800803 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700804 if (!silent) printf("*** command '%s': Error after %.4fs (killing pid %d)\n",
805 cmd.c_str(), (float) elapsed / NANOS_PER_SEC, pid);
Felipe Lemea34efb72016-03-11 09:33:32 -0800806 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800807 (float) elapsed / NANOS_PER_SEC, pid);
808 }
809 kill(pid, SIGTERM);
810 if (!waitpid_with_timeout(pid, 5, NULL)) {
811 kill(pid, SIGKILL);
812 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700813 if (!silent) printf("could not kill command '%s' (pid %d) even with SIGKILL.\n",
814 command, pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700815 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700816 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700817 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800818 return -1;
Felipe Lemea34efb72016-03-11 09:33:32 -0800819 } else if (status) {
820 format_args(command, args, &cmd);
Felipe Leme29c39712016-04-01 10:02:00 -0700821 if (!silent) printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
Felipe Lemea34efb72016-03-11 09:33:32 -0800822 MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
823 return -2;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700824 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800825
826 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700827 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
828 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800829 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700830 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
831 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800832 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800833
Felipe Leme71bbfc52015-11-23 14:14:51 -0800834 if (weight > 0) {
835 update_progress(weight);
836 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800837 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700838}
839
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800840bool drop_root_user() {
841 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
842 MYLOGD("drop_root_user(): already running as Shell");
843 return true;
844 }
845 /* ensure we will keep capabilities when we drop root */
846 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
847 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
848 return false;
849 }
850
851 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
852 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC };
853 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
854 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
855 return false;
856 }
857 if (setgid(AID_SHELL) != 0) {
858 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
859 return false;
860 }
861 if (setuid(AID_SHELL) != 0) {
862 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
863 return false;
864 }
865
866 struct __user_cap_header_struct capheader;
867 struct __user_cap_data_struct capdata[2];
868 memset(&capheader, 0, sizeof(capheader));
869 memset(&capdata, 0, sizeof(capdata));
870 capheader.version = _LINUX_CAPABILITY_VERSION_3;
871 capheader.pid = 0;
872
873 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
874 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
875 capdata[0].inheritable = 0;
876 capdata[1].inheritable = 0;
877
878 if (capset(&capheader, &capdata[0]) < 0) {
879 MYLOGE("capset failed: %s\n", strerror(errno));
880 return false;
881 }
882
883 return true;
884}
885
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800886void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
887 if (args.size() > 1000) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800888 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800889 return;
890 }
Felipe Lemedc42bda2016-06-30 14:27:04 -0700891 const char *am_args[ARG_MAX] = { "/system/bin/am", "broadcast", "--user", "0", "-a",
892 action.c_str() };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800893 size_t am_index = 5; // Starts at the index of last initial value above.
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800894 for (const std::string& arg : args) {
Felipe Lemedc42bda2016-06-30 14:27:04 -0700895 if (am_index > ARG_MAX - 2) {
896 MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
897 return;
898 }
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800899 am_args[++am_index] = arg.c_str();
900 }
Felipe Lemedc42bda2016-06-30 14:27:04 -0700901 // Always terminate with nullptr.
902 am_args[am_index + 1] = nullptr;
Felipe Lemea34efb72016-03-11 09:33:32 -0800903 std::string args_string;
904 format_args(am_index + 1, am_args, &args_string);
905 MYLOGD("send_broadcast command: %s\n", args_string.c_str());
Felipe Leme29c39712016-04-01 10:02:00 -0700906 run_command_always(NULL, DROP_ROOT, REDIRECT_TO_STDERR, 20, am_args);
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800907}
908
Colin Crossf45fa6b2012-03-26 12:38:26 -0700909size_t num_props = 0;
910static char* props[2000];
911
912static void print_prop(const char *key, const char *name, void *user) {
913 (void) user;
914 if (num_props < sizeof(props) / sizeof(props[0])) {
915 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
916 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
917 props[num_props++] = strdup(buf);
918 }
919}
920
921static int compare_prop(const void *a, const void *b) {
922 return strcmp(*(char * const *) a, *(char * const *) b);
923}
924
925/* prints all the system properties */
926void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800927 const char* title = "SYSTEM PROPERTIES";
928 DurationReporter duration_reporter(title);
929 printf("------ %s ------\n", title);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700930 if (is_dry_run()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700931 size_t i;
932 num_props = 0;
933 property_list(print_prop, NULL);
934 qsort(&props, num_props, sizeof(props[0]), compare_prop);
935
Colin Crossf45fa6b2012-03-26 12:38:26 -0700936 for (i = 0; i < num_props; ++i) {
937 fputs(props[i], stdout);
938 free(props[i]);
939 }
940 printf("\n");
941}
942
Felipe Leme2628e9e2016-04-12 16:36:51 -0700943int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700944 int s = android_get_control_socket(service);
945 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800946 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700947 exit(1);
948 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700949 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700950 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800951 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700952 exit(1);
953 }
954
955 struct sockaddr addr;
956 socklen_t alen = sizeof(addr);
957 int fd = accept(s, &addr, &alen);
958 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800959 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700960 exit(1);
961 }
962
Felipe Leme2628e9e2016-04-12 16:36:51 -0700963 return fd;
964}
965
966/* redirect output to a service control socket */
967void redirect_to_socket(FILE *redirect, const char *service) {
968 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700969 fflush(redirect);
970 dup2(fd, fileno(redirect));
971 close(fd);
972}
973
Felipe Leme2628e9e2016-04-12 16:36:51 -0700974// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800975void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800976 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700977
978 /* skip initial slash */
979 if (chp[0] == '/')
980 chp++;
981
982 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800983 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700984 while (chp && chp[0]) {
985 chp = strchr(chp, '/');
986 if (chp) {
987 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800988 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800989 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800990 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800991 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800992 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800993 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800994 }
995 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700996 *chp++ = '/';
997 }
998 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800999}
1000
Felipe Leme0f3fb202016-06-10 17:10:53 -07001001void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001002 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001003
Felipe Leme0f3fb202016-06-10 17:10:53 -07001004 int fd = TEMP_FAILURE_RETRY(open(path,
1005 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001006 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001007 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001008 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001009 exit(1);
1010 }
1011
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001012 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001013 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001014}
1015
Felipe Leme0f3fb202016-06-10 17:10:53 -07001016void redirect_to_file(FILE *redirect, char *path) {
1017 _redirect_to_file(redirect, path, O_TRUNC);
1018}
1019
1020void redirect_to_existing_file(FILE *redirect, char *path) {
1021 _redirect_to_file(redirect, path, O_APPEND);
1022}
1023
Jeff Brownbf7f4922012-06-07 16:40:01 -07001024static bool should_dump_native_traces(const char* path) {
1025 for (const char** p = native_processes_to_dump; *p; p++) {
1026 if (!strcmp(*p, path)) {
1027 return true;
1028 }
1029 }
1030 return false;
1031}
1032
1033/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1034const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -08001035 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Lemed402e7d2016-08-03 09:22:27 -07001036 if (is_dry_run()) return NULL;
1037
Jeff Brownbf7f4922012-06-07 16:40:01 -07001038 const char* result = NULL;
1039
Colin Crossf45fa6b2012-03-26 12:38:26 -07001040 char traces_path[PROPERTY_VALUE_MAX] = "";
1041 property_get("dalvik.vm.stack-trace-file", traces_path, "");
1042 if (!traces_path[0]) return NULL;
1043
1044 /* move the old traces.txt (if any) out of the way temporarily */
1045 char anr_traces_path[PATH_MAX];
1046 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
1047 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
1048 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001049 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001050 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
1051 }
1052
Colin Crossf45fa6b2012-03-26 12:38:26 -07001053 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001054 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 -08001055 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001056 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001057 MYLOGE("%s: %s\n", traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001058 return NULL;
1059 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001060 int chmod_ret = fchmod(fd, 0666);
1061 if (chmod_ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001062 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001063 close(fd);
1064 return NULL;
1065 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001066
Felipe Leme8620bb42015-11-10 11:04:45 -08001067 /* Variables below must be initialized before 'goto' statements */
1068 int dalvik_found = 0;
1069 int ifd, wfd = -1;
1070
Colin Crossf45fa6b2012-03-26 12:38:26 -07001071 /* walk /proc and kill -QUIT all Dalvik processes */
1072 DIR *proc = opendir("/proc");
1073 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001074 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001075 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001076 }
1077
1078 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001079 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001080 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001081 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001082 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001083 }
1084
Felipe Leme8620bb42015-11-10 11:04:45 -08001085 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001086 if (wfd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001087 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001088 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001089 }
1090
1091 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001092 while ((d = readdir(proc))) {
1093 int pid = atoi(d->d_name);
1094 if (pid <= 0) continue;
1095
Jeff Brownbf7f4922012-06-07 16:40:01 -07001096 char path[PATH_MAX];
1097 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001098 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001099 ssize_t len = readlink(path, data, sizeof(data) - 1);
1100 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001101 continue;
1102 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001103 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001104
Colin Cross0d6180f2014-07-16 19:00:46 -07001105 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001106 /* skip zygote -- it won't dump its stack anyway */
1107 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001108 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001109 len = read(cfd, data, sizeof(data) - 1);
1110 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001111 if (len <= 0) {
1112 continue;
1113 }
1114 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001115 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001116 continue;
1117 }
1118
1119 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -08001120 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001121 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001122 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001123 continue;
1124 }
1125
1126 /* wait for the writable-close notification from inotify */
1127 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001128 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001129 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001130 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001131 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001132 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001133 } else {
1134 struct inotify_event ie;
1135 read(ifd, &ie, sizeof(ie));
1136 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001137
1138 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001139 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001140 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001141 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001142 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001143 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001144 } else if (should_dump_native_traces(data)) {
1145 /* dump native process if appropriate */
1146 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001147 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001148 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001149 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -08001150 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001151
1152 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1153 if (timeout_failures == 3) {
1154 dprintf(fd, "too many stack dump failures, skipping...\n");
1155 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1156 dprintf(fd, "dumping failed, likely due to a timeout\n");
1157 timeout_failures++;
1158 } else {
1159 timeout_failures = 0;
1160 }
1161 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001162 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001163 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001164 }
1165 }
1166
Colin Crossf45fa6b2012-03-26 12:38:26 -07001167 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001168 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169 }
1170
1171 static char dump_traces_path[PATH_MAX];
1172 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
1173 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
1174 if (rename(traces_path, dump_traces_path)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001175 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001176 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001177 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001178 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001179
1180 /* replace the saved [ANR] traces.txt file */
1181 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001182
1183error_close_ifd:
1184 close(ifd);
1185error_close_fd:
1186 close(fd);
1187 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001188}
1189
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001190void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001191 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001192 if (is_dry_run()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001193 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1194 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001195 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001196 if (!fp) {
1197 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1198 return;
1199 }
1200 char table[16];
1201 // Each line has an integer (the table number), a space, and a string (the table name). We only
1202 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1203 // Add a fixed max limit so this doesn't go awry.
1204 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
1205 run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
1206 run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
1207 }
1208 fclose(fp);
1209}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001210
1211/* overall progress */
1212int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001213int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001214int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001215
1216// TODO: make this function thread safe if sections are generated in parallel.
1217void update_progress(int delta) {
1218 if (!do_update_progress) return;
1219
1220 progress += delta;
1221
1222 char key[PROPERTY_KEY_MAX];
1223 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001224
1225 // adjusts max on the fly
1226 if (progress > weight_total) {
1227 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001228 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001229 weight_total = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001230 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
1231 snprintf(value, sizeof(value), "%d", weight_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001232 int status = property_set(key, value);
1233 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001234 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001235 key, value, status);
1236 }
1237 }
1238
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001239 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
1240 snprintf(value, sizeof(value), "%d", progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001241
Felipe Leme107a05f2016-03-08 15:11:15 -08001242 if (progress % 100 == 0) {
1243 // We don't want to spam logcat, so only log multiples of 100.
1244 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1245 } else {
1246 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1247 // directly for debuggging.
1248 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1249 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001250
Felipe Leme02b7e002016-07-22 12:03:20 -07001251 if (control_socket_fd >= 0) {
1252 dprintf(control_socket_fd, "PROGRESS:%d/%d\n", progress, weight_total);
1253 fsync(control_socket_fd);
1254 }
1255
Felipe Leme71bbfc52015-11-23 14:14:51 -08001256 int status = property_set(key, value);
1257 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001258 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001259 key, value, status);
1260 }
1261}
Felipe Lemee338bf62015-12-07 14:03:50 -08001262
Felipe Leme3634a1e2015-12-09 10:11:47 -08001263void take_screenshot(const std::string& path) {
Felipe Lemee338bf62015-12-07 14:03:50 -08001264 const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
Felipe Leme29c39712016-04-01 10:02:00 -07001265 run_command_always(NULL, DONT_DROP_ROOT, REDIRECT_TO_STDERR, 10, args);
Felipe Lemee338bf62015-12-07 14:03:50 -08001266}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001267
Felipe Leme0c80cf02016-01-05 13:25:34 -08001268void vibrate(FILE* vibrator, int ms) {
1269 fprintf(vibrator, "%d\n", ms);
1270 fflush(vibrator);
1271}
1272
1273bool is_dir(const char* pathname) {
1274 struct stat info;
1275 if (stat(pathname, &info) == -1) {
1276 return false;
1277 }
1278 return S_ISDIR(info.st_mode);
1279}
1280
1281time_t get_mtime(int fd, time_t default_mtime) {
1282 struct stat info;
1283 if (fstat(fd, &info) == -1) {
1284 return default_mtime;
1285 }
1286 return info.st_mtime;
1287}
1288
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001289void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001290 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001291 struct hex {
1292 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001293 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001294 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1295 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1296 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1297 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1298
1299 std::string buffer;
1300 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1301 return;
1302 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001303
1304 printf("------ %s Extended CSD ------\n", ext_csd_path);
1305
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001306 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1307 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001308 return;
1309 }
1310
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001311 int ext_csd_rev = 0;
1312 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1313 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1314 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1315 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001316 return;
1317 }
1318
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001319 static const char *ver_str[] = {
1320 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1321 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001322 printf("rev 1.%d (MMC %s)\n",
1323 ext_csd_rev,
1324 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1325 ver_str[ext_csd_rev] :
1326 "Unknown");
1327 if (ext_csd_rev < 7) {
1328 printf("\n");
1329 return;
1330 }
1331
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001332 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1333 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001334 return;
1335 }
1336
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001337 int ext_pre_eol_info = 0;
1338 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1339 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1340 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1341 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001342 return;
1343 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001344
1345 static const char *eol_str[] = {
1346 "Undefined",
1347 "Normal",
1348 "Warning (consumed 80% of reserve)",
1349 "Urgent (consumed 90% of reserve)"
1350 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001351 printf("PRE_EOL_INFO %d (MMC %s)\n",
1352 ext_pre_eol_info,
1353 eol_str[(ext_pre_eol_info < (int)
1354 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1355 ext_pre_eol_info : 0]);
1356
1357 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1358 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001359 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001360 int ext_device_life_time_est;
1361 static const char *est_str[] = {
1362 "Undefined",
1363 "0-10% of device lifetime used",
1364 "10-20% of device lifetime used",
1365 "20-30% of device lifetime used",
1366 "30-40% of device lifetime used",
1367 "40-50% of device lifetime used",
1368 "50-60% of device lifetime used",
1369 "60-70% of device lifetime used",
1370 "70-80% of device lifetime used",
1371 "80-90% of device lifetime used",
1372 "90-100% of device lifetime used",
1373 "Exceeded the maximum estimated device lifetime",
1374 };
1375
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001376 if (buffer.length() < (lifetime + sizeof(hex))) {
1377 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001378 break;
1379 }
1380
1381 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001382 sub = buffer.substr(lifetime, sizeof(hex));
1383 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1384 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001385 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001386 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1387 sizeof(hex)) + 'A',
1388 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001389 continue;
1390 }
1391 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001392 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1393 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001394 ext_device_life_time_est,
1395 est_str[(ext_device_life_time_est < (int)
1396 (sizeof(est_str) / sizeof(est_str[0]))) ?
1397 ext_device_life_time_est : 0]);
1398 }
1399
1400 printf("\n");
1401}
Felipe Leme88c79332016-02-22 11:06:49 -08001402
Felipe Lemea34efb72016-03-11 09:33:32 -08001403// TODO: refactor all those commands that convert args
1404void format_args(int argc, const char *argv[], std::string *args) {
1405 LOG_ALWAYS_FATAL_IF(args == nullptr);
Felipe Leme88c79332016-02-22 11:06:49 -08001406 for (int i = 0; i < argc; i++) {
Felipe Lemea34efb72016-03-11 09:33:32 -08001407 args->append(argv[i]);
1408 if (i < argc -1) {
1409 args->append(" ");
1410 }
Felipe Leme88c79332016-02-22 11:06:49 -08001411 }
Felipe Lemea34efb72016-03-11 09:33:32 -08001412}
1413void format_args(const char* command, const char *args[], std::string *string) {
1414 LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr);
1415 string->append(command);
Felipe Leme92157cd2016-06-13 10:08:59 -07001416 if (args[1] == nullptr) return;
Felipe Lemea34efb72016-03-11 09:33:32 -08001417 string->append(" ");
1418
1419 for (int arg = 1; arg <= 1000; ++arg) {
1420 if (args[arg] == nullptr) return;
1421 string->append(args[arg]);
1422 if (args[arg+1] != nullptr) {
1423 string->append(" ");
1424 }
1425 }
Felipe Lemeea160d12016-03-24 11:29:44 -07001426 // TODO: not really working: if NULL is missing, it will crash dumpstate.
Felipe Lemea34efb72016-03-11 09:33:32 -08001427 MYLOGE("internal error: missing NULL entry on %s", string->c_str());
Felipe Leme88c79332016-02-22 11:06:49 -08001428}