blob: 5e074d914d1bbbf1c358bc504e443aa7ee626208 [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 Leme30dbfa12016-09-02 12:43:26 -070072CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
73CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
74CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
75CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
76CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
77
78CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : mValues(timeout) {
79}
80
81CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
82 mValues.mAlways = true;
83 return *this;
84}
85
86CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
87 mValues.mRootMode = SU_ROOT;
88 return *this;
89}
90
91CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
92 mValues.mRootMode = DROP_ROOT;
93 return *this;
94}
95
96CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
97 mValues.mStdoutMode = REDIRECT_TO_STDERR;
98 return *this;
99}
100
101CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
102 const std::string& message) {
103 mValues.mLoggingMessage = message;
104 return *this;
105}
106
107CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
108 return CommandOptions(mValues);
109}
110
111CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
112 : mTimeout(timeout),
113 mAlways(false),
114 mRootMode(DONT_DROP_ROOT),
115 mStdoutMode(NORMAL_STDOUT),
116 mLoggingMessage("") {
117}
118
119CommandOptions::CommandOptions(const CommandOptionsValues& values) : mValues(values) {
120}
121
122long CommandOptions::Timeout() const {
123 return mValues.mTimeout;
124}
125
126bool CommandOptions::Always() const {
127 return mValues.mAlways;
128}
129
130RootMode CommandOptions::RootMode() const {
131 return mValues.mRootMode;
132}
133
134StdoutMode CommandOptions::StdoutMode() const {
135 return mValues.mStdoutMode;
136}
137
138std::string CommandOptions::LoggingMessage() const {
139 return mValues.mLoggingMessage;
140}
141
142CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
143 return CommandOptions::CommandOptionsBuilder(timeout);
144}
145
Felipe Leme608385d2016-02-01 10:35:38 -0800146DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
147
148DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700149 mTitle = title;
150 if (title != nullptr) {
151 mStarted = DurationReporter::nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800152 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700153 mOut = out;
Felipe Leme78f2c862015-12-21 09:55:22 -0800154}
155
156DurationReporter::~DurationReporter() {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700157 if (mTitle != nullptr) {
158 uint64_t elapsed = DurationReporter::nanotime() - mStarted;
Felipe Leme78f2c862015-12-21 09:55:22 -0800159 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme30dbfa12016-09-02 12:43:26 -0700160 if (mOut != nullptr) {
161 fprintf(mOut, "------ %.3fs was the duration of '%s' ------\n",
162 (float)elapsed / NANOS_PER_SEC, mTitle);
Felipe Leme608385d2016-02-01 10:35:38 -0800163 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700164 MYLOGD("Duration of '%s': %.3fs\n", mTitle, (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800165 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800166 }
167}
168
169uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800170 struct timespec ts;
171 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800172 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800173}
174
John Spurlock5ecd4be2014-01-29 14:14:40 -0500175void for_each_userid(void (*func)(int), const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700176 if (is_dry_run()) return;
177
John Spurlock5ecd4be2014-01-29 14:14:40 -0500178 DIR *d;
179 struct dirent *de;
180
181 if (header) printf("\n------ %s ------\n", header);
182 func(0);
183
184 if (!(d = opendir("/data/system/users"))) {
185 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
186 return;
187 }
188
189 while ((de = readdir(d))) {
190 int userid;
191 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
192 continue;
193 }
194 func(userid);
195 }
196
197 closedir(d);
198}
199
Colin Cross0c22e8b2012-11-02 15:46:56 -0700200static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700201 DIR *d;
202 struct dirent *de;
203
204 if (!(d = opendir("/proc"))) {
205 printf("Failed to open /proc (%s)\n", strerror(errno));
206 return;
207 }
208
Felipe Leme635ca312016-01-05 14:23:02 -0800209 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700210 while ((de = readdir(d))) {
211 int pid;
212 int fd;
213 char cmdpath[255];
214 char cmdline[255];
215
216 if (!(pid = atoi(de->d_name))) {
217 continue;
218 }
219
Colin Crossf45fa6b2012-03-26 12:38:26 -0700220 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800221
222 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
223 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
224 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700225 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800226 if (cmdline[0]) {
227 helper(pid, cmdline, arg);
228 continue;
229 }
230 }
231
232 // if no cmdline, a kernel thread has comm
233 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
234 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
235 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
236 close(fd);
237 if (cmdline[1]) {
238 cmdline[0] = '[';
239 size_t len = strcspn(cmdline, "\f\b\r\n");
240 cmdline[len] = ']';
241 cmdline[len+1] = '\0';
242 }
243 }
244 if (!cmdline[0]) {
245 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700246 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700247 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700248 }
249
250 closedir(d);
251}
252
Colin Cross0c22e8b2012-11-02 15:46:56 -0700253static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800254 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700255 func(pid, cmdline);
256}
257
258void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700259 if (is_dry_run()) return;
260
Felipe Leme515eb0d2015-12-14 15:09:56 -0800261 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700262}
263
264static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
265 DIR *d;
266 struct dirent *de;
267 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800268 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700269
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700270 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700271
272 if (!(d = opendir(taskpath))) {
273 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
274 return;
275 }
276
277 func(pid, pid, cmdline);
278
279 while ((de = readdir(d))) {
280 int tid;
281 int fd;
282 char commpath[255];
283 char comm[255];
284
285 if (!(tid = atoi(de->d_name))) {
286 continue;
287 }
288
289 if (tid == pid)
290 continue;
291
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700292 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800293 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700294 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700295 strcpy(comm, "N/A");
296 } else {
297 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800298 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700299 close(fd);
300
301 c = strrchr(comm, '\n');
302 if (c) {
303 *c = '\0';
304 }
305 }
306 func(pid, tid, comm);
307 }
308
309 closedir(d);
310}
311
312void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700313 if (is_dry_run()) return;
314
Felipe Leme8620bb42015-11-10 11:04:45 -0800315 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700316}
317
318void show_wchan(int pid, int tid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700319 if (is_dry_run()) return;
320
Colin Crossf45fa6b2012-03-26 12:38:26 -0700321 char path[255];
322 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800323 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700324 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700325
326 memset(buffer, 0, sizeof(buffer));
327
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700328 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700329 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700330 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
331 return;
332 }
333
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800334 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
335 save_errno = errno;
336 close(fd);
337
338 if (ret < 0) {
339 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
340 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700341 }
342
Colin Cross0c22e8b2012-11-02 15:46:56 -0700343 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
344 pid == tid ? 0 : 3, "", name);
345
346 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700347
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800348 return;
349}
350
351// print time in centiseconds
352static void snprcent(char *buffer, size_t len, size_t spc,
353 unsigned long long time) {
354 static long hz; // cache discovered hz
355
356 if (hz <= 0) {
357 hz = sysconf(_SC_CLK_TCK);
358 if (hz <= 0) {
359 hz = 1000;
360 }
361 }
362
363 // convert to centiseconds
364 time = (time * 100 + (hz / 2)) / hz;
365
366 char str[16];
367
368 snprintf(str, sizeof(str), " %llu.%02u",
369 time / 100, (unsigned)(time % 100));
370 size_t offset = strlen(buffer);
371 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
372 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
373}
374
375// print permille as a percent
376static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
377 char str[16];
378
379 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
380 size_t offset = strlen(buffer);
381 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
382 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
383}
384
385void show_showtime(int pid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700386 if (is_dry_run()) return;
387
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800388 char path[255];
389 char buffer[1023];
390 int fd, ret, save_errno;
391
392 memset(buffer, 0, sizeof(buffer));
393
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700394 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800395 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
396 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
397 return;
398 }
399
400 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
401 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700402 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800403
404 if (ret < 0) {
405 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
406 return;
407 }
408
409 // field 14 is utime
410 // field 15 is stime
411 // field 42 is iotime
412 unsigned long long utime = 0, stime = 0, iotime = 0;
413 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800414 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
415 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
416 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
417 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800418 &utime, &stime, &iotime) != 3) {
419 return;
420 }
421
422 unsigned long long total = utime + stime;
423 if (!total) {
424 return;
425 }
426
427 unsigned permille = (iotime * 1000 + (total / 2)) / total;
428 if (permille > 1000) {
429 permille = 1000;
430 }
431
432 // try to beautify and stabilize columns at <80 characters
433 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
434 if ((name[0] != '[') || utime) {
435 snprcent(buffer, sizeof(buffer), 57, utime);
436 }
437 snprcent(buffer, sizeof(buffer), 65, stime);
438 if ((name[0] != '[') || iotime) {
439 snprcent(buffer, sizeof(buffer), 73, iotime);
440 }
441 if (iotime) {
442 snprdec(buffer, sizeof(buffer), 79, permille);
443 }
444 puts(buffer); // adds a trailing newline
445
Colin Crossf45fa6b2012-03-26 12:38:26 -0700446 return;
447}
448
449void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800450 const char *title = "KERNEL LOG (dmesg)";
451 DurationReporter duration_reporter(title);
452 printf("------ %s ------\n", title);
453
Felipe Lemed402e7d2016-08-03 09:22:27 -0700454 if (is_dry_run()) return;
455
Elliott Hughes5f87b312012-09-17 11:43:40 -0700456 /* Get size of kernel buffer */
457 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700458 if (size <= 0) {
459 printf("Unexpected klogctl return value: %d\n\n", size);
460 return;
461 }
462 char *buf = (char *) malloc(size + 1);
463 if (buf == NULL) {
464 printf("memory allocation failed\n\n");
465 return;
466 }
467 int retval = klogctl(KLOG_READ_ALL, buf, size);
468 if (retval < 0) {
469 printf("klogctl failure\n\n");
470 free(buf);
471 return;
472 }
473 buf[retval] = '\0';
474 printf("%s\n\n", buf);
475 free(buf);
476 return;
477}
478
479void do_showmap(int pid, const char *name) {
480 char title[255];
481 char arg[255];
482
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700483 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
484 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700485 runCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700486}
487
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800488static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700489 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800490 printf("------ %s (%s", title, path);
491
Colin Crossf45fa6b2012-03-26 12:38:26 -0700492 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800493 // Only show the modification time of non-device files.
494 size_t path_len = strlen(path);
495 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
496 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
497 (path_len < 3 || memcmp(path, "/d/", 3)) &&
498 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700499 char stamp[80];
500 time_t mtime = st.st_mtime;
501 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
502 printf(": %s", stamp);
503 }
504 printf(") ------\n");
505 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700506 if (is_dry_run()) {
507 update_progress(WEIGHT_FILE);
508 close(fd);
509 return 0;
510 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700511
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800512 bool newline = false;
513 fd_set read_set;
514 struct timeval tm;
515 while (1) {
516 FD_ZERO(&read_set);
517 FD_SET(fd, &read_set);
518 /* Timeout if no data is read for 30 seconds. */
519 tm.tv_sec = 30;
520 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800521 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800522 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
523 if (ret == -1) {
524 printf("*** %s: select failed: %s\n", path, strerror(errno));
525 newline = true;
526 break;
527 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800528 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800529 printf("*** %s: Timed out after %.3fs\n", path,
530 (float) elapsed / NANOS_PER_SEC);
531 newline = true;
532 break;
533 } else {
534 char buffer[65536];
535 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
536 if (bytes_read > 0) {
537 fwrite(buffer, bytes_read, 1, stdout);
538 newline = (buffer[bytes_read-1] == '\n');
539 } else {
540 if (bytes_read == -1) {
541 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
542 newline = true;
543 }
544 break;
545 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700546 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700547 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800548 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700549 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700550
Colin Crossf45fa6b2012-03-26 12:38:26 -0700551 if (!newline) printf("\n");
552 if (title) printf("\n");
553 return 0;
554}
555
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800556int dump_file(const char *title, const char *path) {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700557 return dumpFile(title, path);
558}
559
560int dumpFile(const char* title, const std::string& path) {
561 DurationReporter durationReporter(title);
562 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800563 if (fd < 0) {
564 int err = errno;
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700565 printf("*** %s: %s\n", path.c_str(), strerror(err));
566 if (title != nullptr) printf("\n");
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800567 return -1;
568 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700569 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800570}
571
Felipe Leme71a74ac2016-03-17 15:43:25 -0700572int read_file_as_long(const char *path, long int *output) {
573 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
574 if (fd < 0) {
575 int err = errno;
576 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
577 return -1;
578 }
579 char buffer[50];
580 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
581 if (bytes_read == -1) {
582 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
583 return -2;
584 }
585 if (bytes_read == 0) {
586 MYLOGE("File %s is empty\n", path);
587 return -3;
588 }
589 *output = atoi(buffer);
590 return 0;
591}
592
Mark Salyzyn326842f2015-04-30 09:49:41 -0700593/* calls skip to gate calling dump_from_fd recursively
594 * in the specified directory. dump_from_fd defaults to
595 * dump_file_from_fd above when set to NULL. skip defaults
596 * to false when set to NULL. dump_from_fd will always be
597 * called with title NULL.
598 */
599int dump_files(const char *title, const char *dir,
600 bool (*skip)(const char *path),
601 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800602 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700603 DIR *dirp;
604 struct dirent *d;
605 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800606 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700607 int fd, retval = 0;
608
609 if (title) {
610 printf("------ %s (%s) ------\n", title, dir);
611 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700612 if (is_dry_run()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700613
614 if (dir[strlen(dir) - 1] == '/') {
615 ++slash;
616 }
617 dirp = opendir(dir);
618 if (dirp == NULL) {
619 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800620 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700621 return retval;
622 }
623
624 if (!dump_from_fd) {
625 dump_from_fd = dump_file_from_fd;
626 }
627 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
628 if ((d->d_name[0] == '.')
629 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
630 || (d->d_name[1] == '\0'))) {
631 continue;
632 }
633 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
634 (d->d_type == DT_DIR) ? "/" : "");
635 if (!newpath) {
636 retval = -errno;
637 continue;
638 }
639 if (skip && (*skip)(newpath)) {
640 continue;
641 }
642 if (d->d_type == DT_DIR) {
643 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
644 if (ret < 0) {
645 retval = ret;
646 }
647 continue;
648 }
649 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
650 if (fd < 0) {
651 retval = fd;
652 printf("*** %s: %s\n", newpath, strerror(errno));
653 continue;
654 }
655 (*dump_from_fd)(NULL, newpath, fd);
656 }
657 closedir(dirp);
658 if (title) {
659 printf("\n");
660 }
661 return retval;
662}
663
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800664/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
665 * it's possible to avoid issues where opening the file itself can get
666 * stuck.
667 */
668int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700669 if (is_dry_run()) return 0;
670
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800671 int flags = fcntl(fd, F_GETFL);
672 if (flags == -1) {
673 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800674 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800675 return -1;
676 } else if (!(flags & O_NONBLOCK)) {
677 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800678 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800679 return -1;
680 }
681 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700682}
683
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800684bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
685 sigset_t child_mask, old_mask;
686 sigemptyset(&child_mask);
687 sigaddset(&child_mask, SIGCHLD);
688
689 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
690 printf("*** sigprocmask failed: %s\n", strerror(errno));
691 return false;
692 }
693
694 struct timespec ts;
695 ts.tv_sec = timeout_seconds;
696 ts.tv_nsec = 0;
697 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
698 int saved_errno = errno;
699 // Set the signals back the way they were.
700 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
701 printf("*** sigprocmask failed: %s\n", strerror(errno));
702 if (ret == 0) {
703 return false;
704 }
705 }
706 if (ret == -1) {
707 errno = saved_errno;
708 if (errno == EAGAIN) {
709 errno = ETIMEDOUT;
710 } else {
711 printf("*** sigtimedwait failed: %s\n", strerror(errno));
712 }
713 return false;
714 }
715
716 pid_t child_pid = waitpid(pid, status, WNOHANG);
717 if (child_pid != pid) {
718 if (child_pid != -1) {
719 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
720 } else {
721 printf("*** waitpid failed: %s\n", strerror(errno));
722 }
723 return false;
724 }
725 return true;
726}
727
Felipe Leme30dbfa12016-09-02 12:43:26 -0700728int run_command(const char* title, int timeout_seconds, const char* command, ...) {
729 std::vector<std::string> fullCommand = {command};
Felipe Leme93d705b2015-11-10 20:10:25 -0800730 size_t arg;
731 va_list ap;
732 va_start(ap, command);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700733 for (arg = 0; arg < MAX_ARGS_ARRAY_SIZE; ++arg) {
734 const char* ptr = va_arg(ap, const char*);
735 if (ptr == nullptr) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800736 break;
737 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700738 fullCommand.push_back(ptr);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700739 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800740 va_end(ap);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700741
742 return runCommand(title, fullCommand, CommandOptions::WithTimeout(timeout_seconds).Build());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800743}
744
Felipe Leme30dbfa12016-09-02 12:43:26 -0700745int runCommand(const char* title, const std::vector<std::string>& fullCommand,
746 const CommandOptions& options) {
747 if (fullCommand.empty()) {
748 MYLOGE("No arguments on command '%s'\n", title);
749 return -1;
750 }
751 DurationReporter durationReporter(title);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800752
Felipe Leme30dbfa12016-09-02 12:43:26 -0700753 int size = fullCommand.size() + 1; // null terminated
754 if (options.RootMode() == SU_ROOT) {
755 size += 2; // "su" "root"
756 }
757
758 const char* args[size];
759
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700760 if (title) {
761 printf("------ %s (", title);
762 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700763
764 std::string commandString;
765 int i = 0;
766 if (options.RootMode() == SU_ROOT) {
767 args[0] = SU_PATH;
768 commandString += SU_PATH;
769 args[1] = "root";
770 commandString += " root ";
771 }
772 for (auto arg = fullCommand.begin(); arg < fullCommand.end(); arg++) {
773 args[i++] = arg->c_str();
774 commandString += arg->c_str();
775 if (arg != fullCommand.end() - 1) {
776 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800777 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800778 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700779 args[i] = nullptr;
780 const char* path = args[0];
781 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700782
783 if (title) {
784 printf("%s) ------\n", command);
785 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700786
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800787 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700788
789 const std::string& loggingMessage = options.LoggingMessage();
790 if (!loggingMessage.empty()) {
791 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800792 }
793
Felipe Leme30dbfa12016-09-02 12:43:26 -0700794 if (is_dry_run() && !options.Always()) {
795 update_progress(options.Timeout());
796 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700797 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800798
Felipe Leme30dbfa12016-09-02 12:43:26 -0700799 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700800
Felipe Leme30dbfa12016-09-02 12:43:26 -0700801 /* TODO: for now we're simplifying the progress calculation by using the
802 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
803 * where its weight should be much higher proportionally to its timeout.
804 * Ideally, it should use a options.EstimatedDuration() instead...*/
805 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800806
Felipe Leme78f2c862015-12-21 09:55:22 -0800807 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700808 pid_t pid = fork();
809
810 /* handle error case */
811 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700812 if (!silent) printf("*** fork: %s\n", strerror(errno));
813 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700814 return pid;
815 }
816
817 /* handle child case */
818 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700819 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
820 if (!silent)
821 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700822 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700823 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800824 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700825
Felipe Leme29c39712016-04-01 10:02:00 -0700826 if (silent) {
827 // Redirect stderr to stdout
828 dup2(STDERR_FILENO, STDOUT_FILENO);
829 }
830
John Michelaue7b6cf12013-03-07 15:35:35 -0600831 /* make sure the child dies when dumpstate dies */
832 prctl(PR_SET_PDEATHSIG, SIGKILL);
833
Andres Morales2e671bb2014-08-21 12:38:22 -0700834 /* just ignore SIGPIPE, will go down with parent's */
835 struct sigaction sigact;
836 memset(&sigact, 0, sizeof(sigact));
837 sigact.sa_handler = SIG_IGN;
838 sigaction(SIGPIPE, &sigact, NULL);
839
Felipe Leme30dbfa12016-09-02 12:43:26 -0700840 execvp(path, (char**)args);
841 // execvp's result will be handled after waitpid_with_timeout() below, but
842 // if it failed, it's safer to exit dumpstate.
843 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700844 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700845 // Must call _exit (instead of exit), otherwise it will corrupt the zip
846 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700847 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700848 }
849
850 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800851 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700852 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800853 uint64_t elapsed = DurationReporter::nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800854 if (!ret) {
855 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700856 if (!silent)
857 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
858 (float)elapsed / NANOS_PER_SEC, pid);
859 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", command,
860 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800861 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700862 if (!silent)
863 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
864 (float)elapsed / NANOS_PER_SEC, pid);
865 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
866 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800867 }
868 kill(pid, SIGTERM);
869 if (!waitpid_with_timeout(pid, 5, NULL)) {
870 kill(pid, SIGKILL);
871 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700872 if (!silent)
873 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
874 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700875 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700876 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700877 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800878 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700879 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800880
881 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700882 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
883 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800884 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700885 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
886 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800887 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800888
Felipe Leme71bbfc52015-11-23 14:14:51 -0800889 if (weight > 0) {
890 update_progress(weight);
891 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800892 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700893}
894
Felipe Leme30dbfa12016-09-02 12:43:26 -0700895void runDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
896 const CommandOptions& options) {
897 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t",
898 std::to_string(options.Timeout())};
899 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
900 runCommand(title.c_str(), dumpsys, options);
901}
902
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800903bool drop_root_user() {
904 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
905 MYLOGD("drop_root_user(): already running as Shell");
906 return true;
907 }
908 /* ensure we will keep capabilities when we drop root */
909 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
910 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
911 return false;
912 }
913
914 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700915 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
916 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800917 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
918 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
919 return false;
920 }
921 if (setgid(AID_SHELL) != 0) {
922 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
923 return false;
924 }
925 if (setuid(AID_SHELL) != 0) {
926 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
927 return false;
928 }
929
930 struct __user_cap_header_struct capheader;
931 struct __user_cap_data_struct capdata[2];
932 memset(&capheader, 0, sizeof(capheader));
933 memset(&capdata, 0, sizeof(capdata));
934 capheader.version = _LINUX_CAPABILITY_VERSION_3;
935 capheader.pid = 0;
936
Wei Liuf87959e2016-08-26 14:51:42 -0700937 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
938 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
939 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
940 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800941 capdata[0].inheritable = 0;
942 capdata[1].inheritable = 0;
943
944 if (capset(&capheader, &capdata[0]) < 0) {
945 MYLOGE("capset failed: %s\n", strerror(errno));
946 return false;
947 }
948
949 return true;
950}
951
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800952void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700953 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
954
955 am.insert(am.end(), args.begin(), args.end());
956
957 runCommand(nullptr, am, CommandOptions::WithTimeout(20)
958 .Log("Sending broadcast: '%s'\n")
959 .Always()
960 .DropRoot()
961 .RedirectStderr()
962 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800963}
964
Colin Crossf45fa6b2012-03-26 12:38:26 -0700965size_t num_props = 0;
966static char* props[2000];
967
968static void print_prop(const char *key, const char *name, void *user) {
969 (void) user;
970 if (num_props < sizeof(props) / sizeof(props[0])) {
971 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
972 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
973 props[num_props++] = strdup(buf);
974 }
975}
976
977static int compare_prop(const void *a, const void *b) {
978 return strcmp(*(char * const *) a, *(char * const *) b);
979}
980
981/* prints all the system properties */
982void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800983 const char* title = "SYSTEM PROPERTIES";
984 DurationReporter duration_reporter(title);
985 printf("------ %s ------\n", title);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700986 if (is_dry_run()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700987 size_t i;
988 num_props = 0;
989 property_list(print_prop, NULL);
990 qsort(&props, num_props, sizeof(props[0]), compare_prop);
991
Colin Crossf45fa6b2012-03-26 12:38:26 -0700992 for (i = 0; i < num_props; ++i) {
993 fputs(props[i], stdout);
994 free(props[i]);
995 }
996 printf("\n");
997}
998
Felipe Leme2628e9e2016-04-12 16:36:51 -0700999int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001000 int s = android_get_control_socket(service);
1001 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001002 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001003 exit(1);
1004 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001005 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001006 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001007 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001008 exit(1);
1009 }
1010
1011 struct sockaddr addr;
1012 socklen_t alen = sizeof(addr);
1013 int fd = accept(s, &addr, &alen);
1014 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001015 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001016 exit(1);
1017 }
1018
Felipe Leme2628e9e2016-04-12 16:36:51 -07001019 return fd;
1020}
1021
1022/* redirect output to a service control socket */
1023void redirect_to_socket(FILE *redirect, const char *service) {
1024 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001025 fflush(redirect);
1026 dup2(fd, fileno(redirect));
1027 close(fd);
1028}
1029
Felipe Leme2628e9e2016-04-12 16:36:51 -07001030// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001031void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001032 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001033
1034 /* skip initial slash */
1035 if (chp[0] == '/')
1036 chp++;
1037
1038 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001039 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001040 while (chp && chp[0]) {
1041 chp = strchr(chp, '/');
1042 if (chp) {
1043 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001044 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001045 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001046 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001047 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001048 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001049 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001050 }
1051 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001052 *chp++ = '/';
1053 }
1054 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001055}
1056
Felipe Leme0f3fb202016-06-10 17:10:53 -07001057void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001058 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001059
Felipe Leme0f3fb202016-06-10 17:10:53 -07001060 int fd = TEMP_FAILURE_RETRY(open(path,
1061 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001062 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001063 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001064 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001065 exit(1);
1066 }
1067
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001068 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001069 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001070}
1071
Felipe Leme0f3fb202016-06-10 17:10:53 -07001072void redirect_to_file(FILE *redirect, char *path) {
1073 _redirect_to_file(redirect, path, O_TRUNC);
1074}
1075
1076void redirect_to_existing_file(FILE *redirect, char *path) {
1077 _redirect_to_file(redirect, path, O_APPEND);
1078}
1079
Jeff Brownbf7f4922012-06-07 16:40:01 -07001080static bool should_dump_native_traces(const char* path) {
1081 for (const char** p = native_processes_to_dump; *p; p++) {
1082 if (!strcmp(*p, path)) {
1083 return true;
1084 }
1085 }
1086 return false;
1087}
1088
1089/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1090const char *dump_traces() {
Felipe Leme608385d2016-02-01 10:35:38 -08001091 DurationReporter duration_reporter("DUMP TRACES", NULL);
Felipe Lemed402e7d2016-08-03 09:22:27 -07001092 if (is_dry_run()) return NULL;
1093
Jeff Brownbf7f4922012-06-07 16:40:01 -07001094 const char* result = NULL;
1095
Colin Crossf45fa6b2012-03-26 12:38:26 -07001096 char traces_path[PROPERTY_VALUE_MAX] = "";
1097 property_get("dalvik.vm.stack-trace-file", traces_path, "");
1098 if (!traces_path[0]) return NULL;
1099
1100 /* move the old traces.txt (if any) out of the way temporarily */
1101 char anr_traces_path[PATH_MAX];
1102 strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
1103 strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
1104 if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001105 MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001106 return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
1107 }
1108
Colin Crossf45fa6b2012-03-26 12:38:26 -07001109 /* create a new, empty traces.txt file to receive stack dumps */
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001110 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 -08001111 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001112 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001113 MYLOGE("%s: %s\n", traces_path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001114 return NULL;
1115 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001116 int chmod_ret = fchmod(fd, 0666);
1117 if (chmod_ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001118 MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001119 close(fd);
1120 return NULL;
1121 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001122
Felipe Leme8620bb42015-11-10 11:04:45 -08001123 /* Variables below must be initialized before 'goto' statements */
1124 int dalvik_found = 0;
1125 int ifd, wfd = -1;
1126
Colin Crossf45fa6b2012-03-26 12:38:26 -07001127 /* walk /proc and kill -QUIT all Dalvik processes */
1128 DIR *proc = opendir("/proc");
1129 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001130 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001131 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001132 }
1133
1134 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001135 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001136 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001137 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001138 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001139 }
1140
Felipe Leme8620bb42015-11-10 11:04:45 -08001141 wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001142 if (wfd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001143 MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001144 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001145 }
1146
1147 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001148 while ((d = readdir(proc))) {
1149 int pid = atoi(d->d_name);
1150 if (pid <= 0) continue;
1151
Jeff Brownbf7f4922012-06-07 16:40:01 -07001152 char path[PATH_MAX];
1153 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001154 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001155 ssize_t len = readlink(path, data, sizeof(data) - 1);
1156 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001157 continue;
1158 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001159 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001160
Colin Cross0d6180f2014-07-16 19:00:46 -07001161 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001162 /* skip zygote -- it won't dump its stack anyway */
1163 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001164 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001165 len = read(cfd, data, sizeof(data) - 1);
1166 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001167 if (len <= 0) {
1168 continue;
1169 }
1170 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001171 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001172 continue;
1173 }
1174
1175 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -08001176 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001177 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001178 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001179 continue;
1180 }
1181
1182 /* wait for the writable-close notification from inotify */
1183 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001184 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001185 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001186 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001187 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001188 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001189 } else {
1190 struct inotify_event ie;
1191 read(ifd, &ie, sizeof(ie));
1192 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001193
1194 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001195 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001196 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001197 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001198 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001199 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001200 } else if (should_dump_native_traces(data)) {
1201 /* dump native process if appropriate */
1202 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001203 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001204 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001205 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -08001206 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001207
1208 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1209 if (timeout_failures == 3) {
1210 dprintf(fd, "too many stack dump failures, skipping...\n");
1211 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1212 dprintf(fd, "dumping failed, likely due to a timeout\n");
1213 timeout_failures++;
1214 } else {
1215 timeout_failures = 0;
1216 }
1217 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001218 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001219 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001220 }
1221 }
1222
Colin Crossf45fa6b2012-03-26 12:38:26 -07001223 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001224 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001225 }
1226
1227 static char dump_traces_path[PATH_MAX];
1228 strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
1229 strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
1230 if (rename(traces_path, dump_traces_path)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001231 MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001232 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001233 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001234 result = dump_traces_path;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001235
1236 /* replace the saved [ANR] traces.txt file */
1237 rename(anr_traces_path, traces_path);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001238
1239error_close_ifd:
1240 close(ifd);
1241error_close_fd:
1242 close(fd);
1243 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001244}
1245
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001246void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001247 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001248 if (is_dry_run()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001249 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1250 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001251 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001252 if (!fp) {
1253 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1254 return;
1255 }
1256 char table[16];
1257 // Each line has an integer (the table number), a space, and a string (the table name). We only
1258 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1259 // Add a fixed max limit so this doesn't go awry.
1260 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001261 runCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1262 runCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001263 }
1264 fclose(fp);
1265}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001266
1267/* overall progress */
1268int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001269int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001270int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001271
1272// TODO: make this function thread safe if sections are generated in parallel.
1273void update_progress(int delta) {
1274 if (!do_update_progress) return;
1275
1276 progress += delta;
1277
1278 char key[PROPERTY_KEY_MAX];
1279 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001280
1281 // adjusts max on the fly
1282 if (progress > weight_total) {
1283 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001284 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001285 weight_total = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001286 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
1287 snprintf(value, sizeof(value), "%d", weight_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001288 int status = property_set(key, value);
1289 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001290 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001291 key, value, status);
1292 }
1293 }
1294
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001295 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
1296 snprintf(value, sizeof(value), "%d", progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001297
Felipe Leme107a05f2016-03-08 15:11:15 -08001298 if (progress % 100 == 0) {
1299 // We don't want to spam logcat, so only log multiples of 100.
1300 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1301 } else {
1302 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1303 // directly for debuggging.
1304 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1305 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001306
Felipe Leme02b7e002016-07-22 12:03:20 -07001307 if (control_socket_fd >= 0) {
1308 dprintf(control_socket_fd, "PROGRESS:%d/%d\n", progress, weight_total);
1309 fsync(control_socket_fd);
1310 }
1311
Felipe Leme71bbfc52015-11-23 14:14:51 -08001312 int status = property_set(key, value);
1313 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001314 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001315 key, value, status);
1316 }
1317}
Felipe Lemee338bf62015-12-07 14:03:50 -08001318
Felipe Leme3634a1e2015-12-09 10:11:47 -08001319void take_screenshot(const std::string& path) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001320 runCommand(nullptr, {"/system/bin/screencap", "-p", path},
1321 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001322}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001323
Felipe Leme0c80cf02016-01-05 13:25:34 -08001324void vibrate(FILE* vibrator, int ms) {
1325 fprintf(vibrator, "%d\n", ms);
1326 fflush(vibrator);
1327}
1328
1329bool is_dir(const char* pathname) {
1330 struct stat info;
1331 if (stat(pathname, &info) == -1) {
1332 return false;
1333 }
1334 return S_ISDIR(info.st_mode);
1335}
1336
1337time_t get_mtime(int fd, time_t default_mtime) {
1338 struct stat info;
1339 if (fstat(fd, &info) == -1) {
1340 return default_mtime;
1341 }
1342 return info.st_mtime;
1343}
1344
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001345void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001346 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001347 struct hex {
1348 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001349 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001350 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1351 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1352 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1353 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1354
1355 std::string buffer;
1356 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1357 return;
1358 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001359
1360 printf("------ %s Extended CSD ------\n", ext_csd_path);
1361
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001362 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1363 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001364 return;
1365 }
1366
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001367 int ext_csd_rev = 0;
1368 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1369 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1370 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1371 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001372 return;
1373 }
1374
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001375 static const char *ver_str[] = {
1376 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1377 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001378 printf("rev 1.%d (MMC %s)\n",
1379 ext_csd_rev,
1380 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1381 ver_str[ext_csd_rev] :
1382 "Unknown");
1383 if (ext_csd_rev < 7) {
1384 printf("\n");
1385 return;
1386 }
1387
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001388 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1389 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001390 return;
1391 }
1392
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001393 int ext_pre_eol_info = 0;
1394 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1395 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1396 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1397 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001398 return;
1399 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001400
1401 static const char *eol_str[] = {
1402 "Undefined",
1403 "Normal",
1404 "Warning (consumed 80% of reserve)",
1405 "Urgent (consumed 90% of reserve)"
1406 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001407 printf("PRE_EOL_INFO %d (MMC %s)\n",
1408 ext_pre_eol_info,
1409 eol_str[(ext_pre_eol_info < (int)
1410 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1411 ext_pre_eol_info : 0]);
1412
1413 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1414 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001415 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001416 int ext_device_life_time_est;
1417 static const char *est_str[] = {
1418 "Undefined",
1419 "0-10% of device lifetime used",
1420 "10-20% of device lifetime used",
1421 "20-30% of device lifetime used",
1422 "30-40% of device lifetime used",
1423 "40-50% of device lifetime used",
1424 "50-60% of device lifetime used",
1425 "60-70% of device lifetime used",
1426 "70-80% of device lifetime used",
1427 "80-90% of device lifetime used",
1428 "90-100% of device lifetime used",
1429 "Exceeded the maximum estimated device lifetime",
1430 };
1431
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001432 if (buffer.length() < (lifetime + sizeof(hex))) {
1433 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001434 break;
1435 }
1436
1437 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001438 sub = buffer.substr(lifetime, sizeof(hex));
1439 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1440 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001441 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001442 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1443 sizeof(hex)) + 'A',
1444 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001445 continue;
1446 }
1447 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001448 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1449 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001450 ext_device_life_time_est,
1451 est_str[(ext_device_life_time_est < (int)
1452 (sizeof(est_str) / sizeof(est_str[0]))) ?
1453 ext_device_life_time_est : 0]);
1454 }
1455
1456 printf("\n");
1457}