blob: 9cf52b2c440a20bcdd4c9f56ff9779286aea10f5 [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>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070042#include <android-base/properties.h>
Jeff Brownbf7f4922012-06-07 16:40:01 -070043#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080044#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070045#include <cutils/properties.h>
46#include <cutils/sockets.h>
47#include <private/android_filesystem_config.h>
48
Robert Craig95798372013-04-04 06:33:10 -040049#include <selinux/android.h>
50
Colin Crossf45fa6b2012-03-26 12:38:26 -070051#include "dumpstate.h"
52
Jeff Brown1dc94e32014-09-11 14:15:27 -070053static const int64_t NANOS_PER_SEC = 1000000000;
54
Felipe Leme61884122016-06-13 09:23:30 -070055static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
56
Jeff Brownbf7f4922012-06-07 16:40:01 -070057/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070058// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070059static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080060 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080061 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070062 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070063 "/system/bin/mediacodec", // media.codec
64 "/system/bin/mediadrmserver",
65 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070066 "/system/bin/mediaserver",
67 "/system/bin/sdcard",
68 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070069 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070070 NULL,
71};
72
Felipe Leme30dbfa12016-09-02 12:43:26 -070073CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
74CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
75CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
76CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
77CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
78
79CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : mValues(timeout) {
80}
81
82CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
83 mValues.mAlways = true;
84 return *this;
85}
86
87CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
88 mValues.mRootMode = SU_ROOT;
89 return *this;
90}
91
92CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
93 mValues.mRootMode = DROP_ROOT;
94 return *this;
95}
96
97CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
98 mValues.mStdoutMode = REDIRECT_TO_STDERR;
99 return *this;
100}
101
102CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
103 const std::string& message) {
104 mValues.mLoggingMessage = message;
105 return *this;
106}
107
108CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
109 return CommandOptions(mValues);
110}
111
112CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
113 : mTimeout(timeout),
114 mAlways(false),
115 mRootMode(DONT_DROP_ROOT),
116 mStdoutMode(NORMAL_STDOUT),
117 mLoggingMessage("") {
118}
119
120CommandOptions::CommandOptions(const CommandOptionsValues& values) : mValues(values) {
121}
122
123long CommandOptions::Timeout() const {
124 return mValues.mTimeout;
125}
126
127bool CommandOptions::Always() const {
128 return mValues.mAlways;
129}
130
131RootMode CommandOptions::RootMode() const {
132 return mValues.mRootMode;
133}
134
135StdoutMode CommandOptions::StdoutMode() const {
136 return mValues.mStdoutMode;
137}
138
139std::string CommandOptions::LoggingMessage() const {
140 return mValues.mLoggingMessage;
141}
142
143CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
144 return CommandOptions::CommandOptionsBuilder(timeout);
145}
146
Felipe Leme608385d2016-02-01 10:35:38 -0800147DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
148
149DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700150 mTitle = title;
151 if (title != nullptr) {
152 mStarted = DurationReporter::nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800153 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700154 mOut = out;
Felipe Leme78f2c862015-12-21 09:55:22 -0800155}
156
157DurationReporter::~DurationReporter() {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700158 if (mTitle != nullptr) {
159 uint64_t elapsed = DurationReporter::nanotime() - mStarted;
Felipe Leme78f2c862015-12-21 09:55:22 -0800160 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Leme30dbfa12016-09-02 12:43:26 -0700161 if (mOut != nullptr) {
162 fprintf(mOut, "------ %.3fs was the duration of '%s' ------\n",
163 (float)elapsed / NANOS_PER_SEC, mTitle);
Felipe Leme608385d2016-02-01 10:35:38 -0800164 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700165 MYLOGD("Duration of '%s': %.3fs\n", mTitle, (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800166 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800167 }
168}
169
170uint64_t DurationReporter::DurationReporter::nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800171 struct timespec ts;
172 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800173 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800174}
175
John Spurlock5ecd4be2014-01-29 14:14:40 -0500176void for_each_userid(void (*func)(int), const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700177 if (is_dry_run()) return;
178
John Spurlock5ecd4be2014-01-29 14:14:40 -0500179 DIR *d;
180 struct dirent *de;
181
182 if (header) printf("\n------ %s ------\n", header);
183 func(0);
184
185 if (!(d = opendir("/data/system/users"))) {
186 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
187 return;
188 }
189
190 while ((de = readdir(d))) {
191 int userid;
192 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
193 continue;
194 }
195 func(userid);
196 }
197
198 closedir(d);
199}
200
Colin Cross0c22e8b2012-11-02 15:46:56 -0700201static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700202 DIR *d;
203 struct dirent *de;
204
205 if (!(d = opendir("/proc"))) {
206 printf("Failed to open /proc (%s)\n", strerror(errno));
207 return;
208 }
209
Felipe Leme635ca312016-01-05 14:23:02 -0800210 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700211 while ((de = readdir(d))) {
212 int pid;
213 int fd;
214 char cmdpath[255];
215 char cmdline[255];
216
217 if (!(pid = atoi(de->d_name))) {
218 continue;
219 }
220
Colin Crossf45fa6b2012-03-26 12:38:26 -0700221 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800222
223 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
224 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
225 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700226 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800227 if (cmdline[0]) {
228 helper(pid, cmdline, arg);
229 continue;
230 }
231 }
232
233 // if no cmdline, a kernel thread has comm
234 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
235 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
236 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
237 close(fd);
238 if (cmdline[1]) {
239 cmdline[0] = '[';
240 size_t len = strcspn(cmdline, "\f\b\r\n");
241 cmdline[len] = ']';
242 cmdline[len+1] = '\0';
243 }
244 }
245 if (!cmdline[0]) {
246 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700247 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700248 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700249 }
250
251 closedir(d);
252}
253
Colin Cross0c22e8b2012-11-02 15:46:56 -0700254static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800255 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700256 func(pid, cmdline);
257}
258
259void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700260 if (is_dry_run()) return;
261
Felipe Leme515eb0d2015-12-14 15:09:56 -0800262 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700263}
264
265static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
266 DIR *d;
267 struct dirent *de;
268 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800269 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700270
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700271 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700272
273 if (!(d = opendir(taskpath))) {
274 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
275 return;
276 }
277
278 func(pid, pid, cmdline);
279
280 while ((de = readdir(d))) {
281 int tid;
282 int fd;
283 char commpath[255];
284 char comm[255];
285
286 if (!(tid = atoi(de->d_name))) {
287 continue;
288 }
289
290 if (tid == pid)
291 continue;
292
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700293 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800294 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700295 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700296 strcpy(comm, "N/A");
297 } else {
298 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800299 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700300 close(fd);
301
302 c = strrchr(comm, '\n');
303 if (c) {
304 *c = '\0';
305 }
306 }
307 func(pid, tid, comm);
308 }
309
310 closedir(d);
311}
312
313void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700314 if (is_dry_run()) return;
315
Felipe Leme8620bb42015-11-10 11:04:45 -0800316 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700317}
318
319void show_wchan(int pid, int tid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700320 if (is_dry_run()) return;
321
Colin Crossf45fa6b2012-03-26 12:38:26 -0700322 char path[255];
323 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800324 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700325 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700326
327 memset(buffer, 0, sizeof(buffer));
328
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700329 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700330 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700331 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
332 return;
333 }
334
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800335 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
336 save_errno = errno;
337 close(fd);
338
339 if (ret < 0) {
340 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
341 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700342 }
343
Colin Cross0c22e8b2012-11-02 15:46:56 -0700344 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
345 pid == tid ? 0 : 3, "", name);
346
347 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700348
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800349 return;
350}
351
352// print time in centiseconds
353static void snprcent(char *buffer, size_t len, size_t spc,
354 unsigned long long time) {
355 static long hz; // cache discovered hz
356
357 if (hz <= 0) {
358 hz = sysconf(_SC_CLK_TCK);
359 if (hz <= 0) {
360 hz = 1000;
361 }
362 }
363
364 // convert to centiseconds
365 time = (time * 100 + (hz / 2)) / hz;
366
367 char str[16];
368
369 snprintf(str, sizeof(str), " %llu.%02u",
370 time / 100, (unsigned)(time % 100));
371 size_t offset = strlen(buffer);
372 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
373 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
374}
375
376// print permille as a percent
377static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
378 char str[16];
379
380 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
381 size_t offset = strlen(buffer);
382 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
383 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
384}
385
386void show_showtime(int pid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700387 if (is_dry_run()) return;
388
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800389 char path[255];
390 char buffer[1023];
391 int fd, ret, save_errno;
392
393 memset(buffer, 0, sizeof(buffer));
394
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700395 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800396 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
397 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
398 return;
399 }
400
401 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
402 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700403 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800404
405 if (ret < 0) {
406 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
407 return;
408 }
409
410 // field 14 is utime
411 // field 15 is stime
412 // field 42 is iotime
413 unsigned long long utime = 0, stime = 0, iotime = 0;
414 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800415 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
416 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
417 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
418 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800419 &utime, &stime, &iotime) != 3) {
420 return;
421 }
422
423 unsigned long long total = utime + stime;
424 if (!total) {
425 return;
426 }
427
428 unsigned permille = (iotime * 1000 + (total / 2)) / total;
429 if (permille > 1000) {
430 permille = 1000;
431 }
432
433 // try to beautify and stabilize columns at <80 characters
434 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
435 if ((name[0] != '[') || utime) {
436 snprcent(buffer, sizeof(buffer), 57, utime);
437 }
438 snprcent(buffer, sizeof(buffer), 65, stime);
439 if ((name[0] != '[') || iotime) {
440 snprcent(buffer, sizeof(buffer), 73, iotime);
441 }
442 if (iotime) {
443 snprdec(buffer, sizeof(buffer), 79, permille);
444 }
445 puts(buffer); // adds a trailing newline
446
Colin Crossf45fa6b2012-03-26 12:38:26 -0700447 return;
448}
449
450void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800451 const char *title = "KERNEL LOG (dmesg)";
452 DurationReporter duration_reporter(title);
453 printf("------ %s ------\n", title);
454
Felipe Lemed402e7d2016-08-03 09:22:27 -0700455 if (is_dry_run()) return;
456
Elliott Hughes5f87b312012-09-17 11:43:40 -0700457 /* Get size of kernel buffer */
458 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700459 if (size <= 0) {
460 printf("Unexpected klogctl return value: %d\n\n", size);
461 return;
462 }
463 char *buf = (char *) malloc(size + 1);
464 if (buf == NULL) {
465 printf("memory allocation failed\n\n");
466 return;
467 }
468 int retval = klogctl(KLOG_READ_ALL, buf, size);
469 if (retval < 0) {
470 printf("klogctl failure\n\n");
471 free(buf);
472 return;
473 }
474 buf[retval] = '\0';
475 printf("%s\n\n", buf);
476 free(buf);
477 return;
478}
479
480void do_showmap(int pid, const char *name) {
481 char title[255];
482 char arg[255];
483
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700484 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
485 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700486 runCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700487}
488
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800489static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700490 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800491 printf("------ %s (%s", title, path);
492
Colin Crossf45fa6b2012-03-26 12:38:26 -0700493 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800494 // Only show the modification time of non-device files.
495 size_t path_len = strlen(path);
496 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
497 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
498 (path_len < 3 || memcmp(path, "/d/", 3)) &&
499 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700500 char stamp[80];
501 time_t mtime = st.st_mtime;
502 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
503 printf(": %s", stamp);
504 }
505 printf(") ------\n");
506 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700507 if (is_dry_run()) {
508 update_progress(WEIGHT_FILE);
509 close(fd);
510 return 0;
511 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700512
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800513 bool newline = false;
514 fd_set read_set;
515 struct timeval tm;
516 while (1) {
517 FD_ZERO(&read_set);
518 FD_SET(fd, &read_set);
519 /* Timeout if no data is read for 30 seconds. */
520 tm.tv_sec = 30;
521 tm.tv_usec = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -0800522 uint64_t elapsed = DurationReporter::nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800523 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
524 if (ret == -1) {
525 printf("*** %s: select failed: %s\n", path, strerror(errno));
526 newline = true;
527 break;
528 } else if (ret == 0) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800529 elapsed = DurationReporter::nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800530 printf("*** %s: Timed out after %.3fs\n", path,
531 (float) elapsed / NANOS_PER_SEC);
532 newline = true;
533 break;
534 } else {
535 char buffer[65536];
536 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
537 if (bytes_read > 0) {
538 fwrite(buffer, bytes_read, 1, stdout);
539 newline = (buffer[bytes_read-1] == '\n');
540 } else {
541 if (bytes_read == -1) {
542 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
543 newline = true;
544 }
545 break;
546 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700547 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700548 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800549 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700550 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700551
Colin Crossf45fa6b2012-03-26 12:38:26 -0700552 if (!newline) printf("\n");
553 if (title) printf("\n");
554 return 0;
555}
556
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800557int dump_file(const char *title, const char *path) {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700558 return dumpFile(title, path);
559}
560
561int dumpFile(const char* title, const std::string& path) {
562 DurationReporter durationReporter(title);
563 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800564 if (fd < 0) {
565 int err = errno;
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700566 printf("*** %s: %s\n", path.c_str(), strerror(err));
567 if (title != nullptr) printf("\n");
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800568 return -1;
569 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700570 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800571}
572
Felipe Leme71a74ac2016-03-17 15:43:25 -0700573int read_file_as_long(const char *path, long int *output) {
574 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
575 if (fd < 0) {
576 int err = errno;
577 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
578 return -1;
579 }
580 char buffer[50];
581 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
582 if (bytes_read == -1) {
583 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
584 return -2;
585 }
586 if (bytes_read == 0) {
587 MYLOGE("File %s is empty\n", path);
588 return -3;
589 }
590 *output = atoi(buffer);
591 return 0;
592}
593
Mark Salyzyn326842f2015-04-30 09:49:41 -0700594/* calls skip to gate calling dump_from_fd recursively
595 * in the specified directory. dump_from_fd defaults to
596 * dump_file_from_fd above when set to NULL. skip defaults
597 * to false when set to NULL. dump_from_fd will always be
598 * called with title NULL.
599 */
600int dump_files(const char *title, const char *dir,
601 bool (*skip)(const char *path),
602 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800603 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700604 DIR *dirp;
605 struct dirent *d;
606 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800607 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700608 int fd, retval = 0;
609
610 if (title) {
611 printf("------ %s (%s) ------\n", title, dir);
612 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700613 if (is_dry_run()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700614
615 if (dir[strlen(dir) - 1] == '/') {
616 ++slash;
617 }
618 dirp = opendir(dir);
619 if (dirp == NULL) {
620 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800621 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700622 return retval;
623 }
624
625 if (!dump_from_fd) {
626 dump_from_fd = dump_file_from_fd;
627 }
628 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
629 if ((d->d_name[0] == '.')
630 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
631 || (d->d_name[1] == '\0'))) {
632 continue;
633 }
634 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
635 (d->d_type == DT_DIR) ? "/" : "");
636 if (!newpath) {
637 retval = -errno;
638 continue;
639 }
640 if (skip && (*skip)(newpath)) {
641 continue;
642 }
643 if (d->d_type == DT_DIR) {
644 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
645 if (ret < 0) {
646 retval = ret;
647 }
648 continue;
649 }
650 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
651 if (fd < 0) {
652 retval = fd;
653 printf("*** %s: %s\n", newpath, strerror(errno));
654 continue;
655 }
656 (*dump_from_fd)(NULL, newpath, fd);
657 }
658 closedir(dirp);
659 if (title) {
660 printf("\n");
661 }
662 return retval;
663}
664
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800665/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
666 * it's possible to avoid issues where opening the file itself can get
667 * stuck.
668 */
669int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700670 if (is_dry_run()) return 0;
671
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800672 int flags = fcntl(fd, F_GETFL);
673 if (flags == -1) {
674 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800675 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800676 return -1;
677 } else if (!(flags & O_NONBLOCK)) {
678 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800679 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800680 return -1;
681 }
682 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700683}
684
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800685bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
686 sigset_t child_mask, old_mask;
687 sigemptyset(&child_mask);
688 sigaddset(&child_mask, SIGCHLD);
689
690 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
691 printf("*** sigprocmask failed: %s\n", strerror(errno));
692 return false;
693 }
694
695 struct timespec ts;
696 ts.tv_sec = timeout_seconds;
697 ts.tv_nsec = 0;
698 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
699 int saved_errno = errno;
700 // Set the signals back the way they were.
701 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
702 printf("*** sigprocmask failed: %s\n", strerror(errno));
703 if (ret == 0) {
704 return false;
705 }
706 }
707 if (ret == -1) {
708 errno = saved_errno;
709 if (errno == EAGAIN) {
710 errno = ETIMEDOUT;
711 } else {
712 printf("*** sigtimedwait failed: %s\n", strerror(errno));
713 }
714 return false;
715 }
716
717 pid_t child_pid = waitpid(pid, status, WNOHANG);
718 if (child_pid != pid) {
719 if (child_pid != -1) {
720 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
721 } else {
722 printf("*** waitpid failed: %s\n", strerror(errno));
723 }
724 return false;
725 }
726 return true;
727}
728
Felipe Leme30dbfa12016-09-02 12:43:26 -0700729int run_command(const char* title, int timeout_seconds, const char* command, ...) {
730 std::vector<std::string> fullCommand = {command};
Felipe Leme93d705b2015-11-10 20:10:25 -0800731 size_t arg;
732 va_list ap;
733 va_start(ap, command);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700734 for (arg = 0; arg < MAX_ARGS_ARRAY_SIZE; ++arg) {
735 const char* ptr = va_arg(ap, const char*);
736 if (ptr == nullptr) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800737 break;
738 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700739 fullCommand.push_back(ptr);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700740 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800741 va_end(ap);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700742
743 return runCommand(title, fullCommand, CommandOptions::WithTimeout(timeout_seconds).Build());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800744}
745
Felipe Leme30dbfa12016-09-02 12:43:26 -0700746int runCommand(const char* title, const std::vector<std::string>& fullCommand,
747 const CommandOptions& options) {
748 if (fullCommand.empty()) {
749 MYLOGE("No arguments on command '%s'\n", title);
750 return -1;
751 }
752 DurationReporter durationReporter(title);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800753
Felipe Leme30dbfa12016-09-02 12:43:26 -0700754 int size = fullCommand.size() + 1; // null terminated
755 if (options.RootMode() == SU_ROOT) {
756 size += 2; // "su" "root"
757 }
758
759 const char* args[size];
760
761 printf("------");
762 if (title) printf(" %s", title);
763 printf(" (");
764
765 std::string commandString;
766 int i = 0;
767 if (options.RootMode() == SU_ROOT) {
768 args[0] = SU_PATH;
769 commandString += SU_PATH;
770 args[1] = "root";
771 commandString += " root ";
772 }
773 for (auto arg = fullCommand.begin(); arg < fullCommand.end(); arg++) {
774 args[i++] = arg->c_str();
775 commandString += arg->c_str();
776 if (arg != fullCommand.end() - 1) {
777 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800778 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800779 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700780 args[i] = nullptr;
781 const char* path = args[0];
782 const char* command = commandString.c_str();
783 printf("%s)\n", command);
784
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800785 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700786
787 const std::string& loggingMessage = options.LoggingMessage();
788 if (!loggingMessage.empty()) {
789 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800790 }
791
Felipe Leme30dbfa12016-09-02 12:43:26 -0700792 if (is_dry_run() && !options.Always()) {
793 update_progress(options.Timeout());
794 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700795 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800796
Felipe Leme30dbfa12016-09-02 12:43:26 -0700797 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700798
Felipe Leme30dbfa12016-09-02 12:43:26 -0700799 /* TODO: for now we're simplifying the progress calculation by using the
800 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
801 * where its weight should be much higher proportionally to its timeout.
802 * Ideally, it should use a options.EstimatedDuration() instead...*/
803 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800804
Felipe Leme78f2c862015-12-21 09:55:22 -0800805 uint64_t start = DurationReporter::nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700806 pid_t pid = fork();
807
808 /* handle error case */
809 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700810 if (!silent) printf("*** fork: %s\n", strerror(errno));
811 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700812 return pid;
813 }
814
815 /* handle child case */
816 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700817 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
818 if (!silent)
819 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700820 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700821 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800822 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700823
Felipe Leme29c39712016-04-01 10:02:00 -0700824 if (silent) {
825 // Redirect stderr to stdout
826 dup2(STDERR_FILENO, STDOUT_FILENO);
827 }
828
John Michelaue7b6cf12013-03-07 15:35:35 -0600829 /* make sure the child dies when dumpstate dies */
830 prctl(PR_SET_PDEATHSIG, SIGKILL);
831
Andres Morales2e671bb2014-08-21 12:38:22 -0700832 /* just ignore SIGPIPE, will go down with parent's */
833 struct sigaction sigact;
834 memset(&sigact, 0, sizeof(sigact));
835 sigact.sa_handler = SIG_IGN;
836 sigaction(SIGPIPE, &sigact, NULL);
837
Felipe Leme30dbfa12016-09-02 12:43:26 -0700838 execvp(path, (char**)args);
839 // execvp's result will be handled after waitpid_with_timeout() below, but
840 // if it failed, it's safer to exit dumpstate.
841 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700842 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700843 // Must call _exit (instead of exit), otherwise it will corrupt the zip
844 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700845 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700846 }
847
848 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800849 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700850 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Leme78f2c862015-12-21 09:55:22 -0800851 uint64_t elapsed = DurationReporter::nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800852 if (!ret) {
853 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700854 if (!silent)
855 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
856 (float)elapsed / NANOS_PER_SEC, pid);
857 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", command,
858 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800859 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700860 if (!silent)
861 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
862 (float)elapsed / NANOS_PER_SEC, pid);
863 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
864 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800865 }
866 kill(pid, SIGTERM);
867 if (!waitpid_with_timeout(pid, 5, NULL)) {
868 kill(pid, SIGKILL);
869 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700870 if (!silent)
871 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
872 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700873 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700874 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700875 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800876 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700877 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800878
879 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700880 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
881 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800882 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700883 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
884 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800885 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800886
Felipe Leme71bbfc52015-11-23 14:14:51 -0800887 if (weight > 0) {
888 update_progress(weight);
889 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800890 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700891}
892
Felipe Leme30dbfa12016-09-02 12:43:26 -0700893void runDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
894 const CommandOptions& options) {
895 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t",
896 std::to_string(options.Timeout())};
897 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
898 runCommand(title.c_str(), dumpsys, options);
899}
900
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800901bool drop_root_user() {
902 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
903 MYLOGD("drop_root_user(): already running as Shell");
904 return true;
905 }
906 /* ensure we will keep capabilities when we drop root */
907 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
908 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
909 return false;
910 }
911
912 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700913 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
914 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800915 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
916 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
917 return false;
918 }
919 if (setgid(AID_SHELL) != 0) {
920 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
921 return false;
922 }
923 if (setuid(AID_SHELL) != 0) {
924 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
925 return false;
926 }
927
928 struct __user_cap_header_struct capheader;
929 struct __user_cap_data_struct capdata[2];
930 memset(&capheader, 0, sizeof(capheader));
931 memset(&capdata, 0, sizeof(capdata));
932 capheader.version = _LINUX_CAPABILITY_VERSION_3;
933 capheader.pid = 0;
934
Wei Liuf87959e2016-08-26 14:51:42 -0700935 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
936 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
937 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
938 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800939 capdata[0].inheritable = 0;
940 capdata[1].inheritable = 0;
941
942 if (capset(&capheader, &capdata[0]) < 0) {
943 MYLOGE("capset failed: %s\n", strerror(errno));
944 return false;
945 }
946
947 return true;
948}
949
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800950void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700951 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
952
953 am.insert(am.end(), args.begin(), args.end());
954
955 runCommand(nullptr, am, CommandOptions::WithTimeout(20)
956 .Log("Sending broadcast: '%s'\n")
957 .Always()
958 .DropRoot()
959 .RedirectStderr()
960 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800961}
962
Colin Crossf45fa6b2012-03-26 12:38:26 -0700963size_t num_props = 0;
964static char* props[2000];
965
966static void print_prop(const char *key, const char *name, void *user) {
967 (void) user;
968 if (num_props < sizeof(props) / sizeof(props[0])) {
969 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
970 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
971 props[num_props++] = strdup(buf);
972 }
973}
974
975static int compare_prop(const void *a, const void *b) {
976 return strcmp(*(char * const *) a, *(char * const *) b);
977}
978
979/* prints all the system properties */
980void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800981 const char* title = "SYSTEM PROPERTIES";
982 DurationReporter duration_reporter(title);
983 printf("------ %s ------\n", title);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700984 if (is_dry_run()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700985 size_t i;
986 num_props = 0;
987 property_list(print_prop, NULL);
988 qsort(&props, num_props, sizeof(props[0]), compare_prop);
989
Colin Crossf45fa6b2012-03-26 12:38:26 -0700990 for (i = 0; i < num_props; ++i) {
991 fputs(props[i], stdout);
992 free(props[i]);
993 }
994 printf("\n");
995}
996
Felipe Leme2628e9e2016-04-12 16:36:51 -0700997int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700998 int s = android_get_control_socket(service);
999 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001000 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001001 exit(1);
1002 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001003 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001004 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001005 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001006 exit(1);
1007 }
1008
1009 struct sockaddr addr;
1010 socklen_t alen = sizeof(addr);
1011 int fd = accept(s, &addr, &alen);
1012 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001013 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001014 exit(1);
1015 }
1016
Felipe Leme2628e9e2016-04-12 16:36:51 -07001017 return fd;
1018}
1019
1020/* redirect output to a service control socket */
1021void redirect_to_socket(FILE *redirect, const char *service) {
1022 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001023 fflush(redirect);
1024 dup2(fd, fileno(redirect));
1025 close(fd);
1026}
1027
Felipe Leme2628e9e2016-04-12 16:36:51 -07001028// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001029void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001030 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001031
1032 /* skip initial slash */
1033 if (chp[0] == '/')
1034 chp++;
1035
1036 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001037 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001038 while (chp && chp[0]) {
1039 chp = strchr(chp, '/');
1040 if (chp) {
1041 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001042 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001043 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001044 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001045 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001046 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001047 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001048 }
1049 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001050 *chp++ = '/';
1051 }
1052 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001053}
1054
Felipe Leme0f3fb202016-06-10 17:10:53 -07001055void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001056 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001057
Felipe Leme0f3fb202016-06-10 17:10:53 -07001058 int fd = TEMP_FAILURE_RETRY(open(path,
1059 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001060 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001061 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001062 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001063 exit(1);
1064 }
1065
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001066 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001067 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001068}
1069
Felipe Leme0f3fb202016-06-10 17:10:53 -07001070void redirect_to_file(FILE *redirect, char *path) {
1071 _redirect_to_file(redirect, path, O_TRUNC);
1072}
1073
1074void redirect_to_existing_file(FILE *redirect, char *path) {
1075 _redirect_to_file(redirect, path, O_APPEND);
1076}
1077
Jeff Brownbf7f4922012-06-07 16:40:01 -07001078static bool should_dump_native_traces(const char* path) {
1079 for (const char** p = native_processes_to_dump; *p; p++) {
1080 if (!strcmp(*p, path)) {
1081 return true;
1082 }
1083 }
1084 return false;
1085}
1086
1087/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1088const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001089 DurationReporter duration_reporter("DUMP TRACES", nullptr);
1090 if (is_dry_run()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001091
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001092 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001093
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001094 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1095 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001096
1097 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001098 std::string anrTracesPath = tracesPath + ".anr";
1099 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1100 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1101 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001102 }
1103
Colin Crossf45fa6b2012-03-26 12:38:26 -07001104 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001105 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1106 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1107 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001108 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001109 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1110 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001111 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001112 int chmod_ret = fchmod(fd, 0666);
1113 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001114 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001115 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001116 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001117 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001118
Felipe Leme8620bb42015-11-10 11:04:45 -08001119 /* Variables below must be initialized before 'goto' statements */
1120 int dalvik_found = 0;
1121 int ifd, wfd = -1;
1122
Colin Crossf45fa6b2012-03-26 12:38:26 -07001123 /* walk /proc and kill -QUIT all Dalvik processes */
1124 DIR *proc = opendir("/proc");
1125 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001126 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001127 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001128 }
1129
1130 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001131 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001132 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001133 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001134 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001135 }
1136
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001137 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001138 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001139 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001140 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001141 }
1142
1143 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001144 while ((d = readdir(proc))) {
1145 int pid = atoi(d->d_name);
1146 if (pid <= 0) continue;
1147
Jeff Brownbf7f4922012-06-07 16:40:01 -07001148 char path[PATH_MAX];
1149 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001150 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001151 ssize_t len = readlink(path, data, sizeof(data) - 1);
1152 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001153 continue;
1154 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001155 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001156
Colin Cross0d6180f2014-07-16 19:00:46 -07001157 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001158 /* skip zygote -- it won't dump its stack anyway */
1159 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001160 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001161 len = read(cfd, data, sizeof(data) - 1);
1162 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001163 if (len <= 0) {
1164 continue;
1165 }
1166 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001167 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001168 continue;
1169 }
1170
1171 ++dalvik_found;
Felipe Leme78f2c862015-12-21 09:55:22 -08001172 uint64_t start = DurationReporter::nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001173 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001174 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001175 continue;
1176 }
1177
1178 /* wait for the writable-close notification from inotify */
1179 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001180 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001181 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001182 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001183 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001184 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001185 } else {
1186 struct inotify_event ie;
1187 read(ifd, &ie, sizeof(ie));
1188 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001189
1190 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001191 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001192 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001193 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001194 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001195 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001196 } else if (should_dump_native_traces(data)) {
1197 /* dump native process if appropriate */
1198 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001199 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001200 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001201 static uint16_t timeout_failures = 0;
Felipe Leme78f2c862015-12-21 09:55:22 -08001202 uint64_t start = DurationReporter::nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001203
1204 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1205 if (timeout_failures == 3) {
1206 dprintf(fd, "too many stack dump failures, skipping...\n");
1207 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1208 dprintf(fd, "dumping failed, likely due to a timeout\n");
1209 timeout_failures++;
1210 } else {
1211 timeout_failures = 0;
1212 }
1213 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
Felipe Leme78f2c862015-12-21 09:55:22 -08001214 pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001215 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001216 }
1217 }
1218
Colin Crossf45fa6b2012-03-26 12:38:26 -07001219 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001220 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001221 }
1222
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001223 static std::string dumpTracesPath = tracesPath + ".bugreport";
1224 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1225 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001226 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001227 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001228 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001229
1230 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001231 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001232
1233error_close_ifd:
1234 close(ifd);
1235error_close_fd:
1236 close(fd);
1237 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001238}
1239
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001240void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001241 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001242 if (is_dry_run()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001243 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1244 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001245 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001246 if (!fp) {
1247 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1248 return;
1249 }
1250 char table[16];
1251 // Each line has an integer (the table number), a space, and a string (the table name). We only
1252 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1253 // Add a fixed max limit so this doesn't go awry.
1254 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001255 runCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1256 runCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001257 }
1258 fclose(fp);
1259}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001260
1261/* overall progress */
1262int progress = 0;
Felipe Leme08b55782015-12-01 08:40:52 -08001263int do_update_progress = 0; // Set by dumpstate.cpp
Felipe Lemead5f6c42015-11-30 14:26:46 -08001264int weight_total = WEIGHT_TOTAL;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001265
1266// TODO: make this function thread safe if sections are generated in parallel.
1267void update_progress(int delta) {
1268 if (!do_update_progress) return;
1269
1270 progress += delta;
1271
1272 char key[PROPERTY_KEY_MAX];
1273 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001274
1275 // adjusts max on the fly
1276 if (progress > weight_total) {
1277 int new_total = weight_total * 1.2;
Felipe Leme107a05f2016-03-08 15:11:15 -08001278 MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001279 weight_total = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001280 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
1281 snprintf(value, sizeof(value), "%d", weight_total);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001282 int status = property_set(key, value);
1283 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001284 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001285 key, value, status);
1286 }
1287 }
1288
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001289 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
1290 snprintf(value, sizeof(value), "%d", progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001291
Felipe Leme107a05f2016-03-08 15:11:15 -08001292 if (progress % 100 == 0) {
1293 // We don't want to spam logcat, so only log multiples of 100.
1294 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1295 } else {
1296 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1297 // directly for debuggging.
1298 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1299 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001300
Felipe Leme02b7e002016-07-22 12:03:20 -07001301 if (control_socket_fd >= 0) {
1302 dprintf(control_socket_fd, "PROGRESS:%d/%d\n", progress, weight_total);
1303 fsync(control_socket_fd);
1304 }
1305
Felipe Leme71bbfc52015-11-23 14:14:51 -08001306 int status = property_set(key, value);
1307 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001308 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001309 key, value, status);
1310 }
1311}
Felipe Lemee338bf62015-12-07 14:03:50 -08001312
Felipe Leme3634a1e2015-12-09 10:11:47 -08001313void take_screenshot(const std::string& path) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001314 runCommand(nullptr, {"/system/bin/screencap", "-p", path},
1315 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001316}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001317
Felipe Leme0c80cf02016-01-05 13:25:34 -08001318void vibrate(FILE* vibrator, int ms) {
1319 fprintf(vibrator, "%d\n", ms);
1320 fflush(vibrator);
1321}
1322
1323bool is_dir(const char* pathname) {
1324 struct stat info;
1325 if (stat(pathname, &info) == -1) {
1326 return false;
1327 }
1328 return S_ISDIR(info.st_mode);
1329}
1330
1331time_t get_mtime(int fd, time_t default_mtime) {
1332 struct stat info;
1333 if (fstat(fd, &info) == -1) {
1334 return default_mtime;
1335 }
1336 return info.st_mtime;
1337}
1338
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001339void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001340 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001341 struct hex {
1342 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001343 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001344 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1345 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1346 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1347 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1348
1349 std::string buffer;
1350 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1351 return;
1352 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001353
1354 printf("------ %s Extended CSD ------\n", ext_csd_path);
1355
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001356 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1357 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001358 return;
1359 }
1360
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001361 int ext_csd_rev = 0;
1362 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1363 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1364 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1365 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001366 return;
1367 }
1368
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001369 static const char *ver_str[] = {
1370 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1371 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001372 printf("rev 1.%d (MMC %s)\n",
1373 ext_csd_rev,
1374 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1375 ver_str[ext_csd_rev] :
1376 "Unknown");
1377 if (ext_csd_rev < 7) {
1378 printf("\n");
1379 return;
1380 }
1381
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001382 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1383 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001384 return;
1385 }
1386
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001387 int ext_pre_eol_info = 0;
1388 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1389 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1390 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1391 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001392 return;
1393 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001394
1395 static const char *eol_str[] = {
1396 "Undefined",
1397 "Normal",
1398 "Warning (consumed 80% of reserve)",
1399 "Urgent (consumed 90% of reserve)"
1400 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001401 printf("PRE_EOL_INFO %d (MMC %s)\n",
1402 ext_pre_eol_info,
1403 eol_str[(ext_pre_eol_info < (int)
1404 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1405 ext_pre_eol_info : 0]);
1406
1407 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1408 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001409 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001410 int ext_device_life_time_est;
1411 static const char *est_str[] = {
1412 "Undefined",
1413 "0-10% of device lifetime used",
1414 "10-20% of device lifetime used",
1415 "20-30% of device lifetime used",
1416 "30-40% of device lifetime used",
1417 "40-50% of device lifetime used",
1418 "50-60% of device lifetime used",
1419 "60-70% of device lifetime used",
1420 "70-80% of device lifetime used",
1421 "80-90% of device lifetime used",
1422 "90-100% of device lifetime used",
1423 "Exceeded the maximum estimated device lifetime",
1424 };
1425
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001426 if (buffer.length() < (lifetime + sizeof(hex))) {
1427 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001428 break;
1429 }
1430
1431 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001432 sub = buffer.substr(lifetime, sizeof(hex));
1433 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1434 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001435 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001436 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1437 sizeof(hex)) + 'A',
1438 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001439 continue;
1440 }
1441 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001442 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1443 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001444 ext_device_life_time_est,
1445 est_str[(ext_device_life_time_est < (int)
1446 (sizeof(est_str) / sizeof(est_str[0]))) ?
1447 ext_device_life_time_est : 0]);
1448 }
1449
1450 printf("\n");
1451}