blob: 476392e10ae4bb9edadcecc07c30d76f5c3c5292 [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
Felipe Lemee844a9d2016-09-21 15:01:39 -070057// TODO: temporary variables and functions used during C++ refactoring
58static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme678727a2016-09-21 17:22:11 -070059static int RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
60 const CommandOptions& options = CommandOptions::DEFAULT) {
61 return ds.RunCommand(title, fullCommand, options);
62}
Felipe Lemee844a9d2016-09-21 15:01:39 -070063
Jeff Brownbf7f4922012-06-07 16:40:01 -070064/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070065// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070066static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080067 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080068 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070069 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070070 "/system/bin/mediacodec", // media.codec
71 "/system/bin/mediadrmserver",
72 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070073 "/system/bin/mediaserver",
74 "/system/bin/sdcard",
75 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070076 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070077 NULL,
78};
79
Felipe Lemee844a9d2016-09-21 15:01:39 -070080/* Most simple commands have 10 as timeout, so 5 is a good estimate */
81static const int WEIGHT_FILE = 5;
82
Felipe Leme30dbfa12016-09-02 12:43:26 -070083CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
84CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
85CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
86CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
87CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
88
Felipe Lemeb0f669d2016-09-26 18:26:11 -070089CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values_(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -070090}
91
92CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -070093 values_.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -070094 return *this;
95}
96
97CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -070098 values_.rootMode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -070099 return *this;
100}
101
102CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700103 values_.rootMode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700104 return *this;
105}
106
107CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700108 values_.stdoutMode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700109 return *this;
110}
111
112CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
113 const std::string& message) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700114 values_.loggingMessage_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700115 return *this;
116}
117
118CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700119 return CommandOptions(values_);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700120}
121
122CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700123 : timeout_(timeout),
124 always_(false),
125 rootMode_(DONT_DROP_ROOT),
126 stdoutMode_(NORMAL_STDOUT),
127 loggingMessage_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700128}
129
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700130CommandOptions::CommandOptions(const CommandOptionsValues& values) : values_(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700131}
132
133long CommandOptions::Timeout() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700134 return values_.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700135}
136
137bool CommandOptions::Always() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700138 return values_.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700139}
140
141RootMode CommandOptions::RootMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700142 return values_.rootMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700143}
144
145StdoutMode CommandOptions::StdoutMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700146 return values_.stdoutMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700147}
148
149std::string CommandOptions::LoggingMessage() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700150 return values_.loggingMessage_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700151}
152
153CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
154 return CommandOptions::CommandOptionsBuilder(timeout);
155}
156
Felipe Lemee844a9d2016-09-21 15:01:39 -0700157Dumpstate::Dumpstate() {
158}
159
160Dumpstate& Dumpstate::GetInstance() {
161 static Dumpstate sSingleton;
162 return sSingleton;
163}
164
Felipe Leme678727a2016-09-21 17:22:11 -0700165DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
166}
Felipe Leme608385d2016-02-01 10:35:38 -0800167
Felipe Leme678727a2016-09-21 17:22:11 -0700168DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
169 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700170 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800171 }
172}
173
174DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700175 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700176 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800177 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700178 if (out_ != nullptr) {
179 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700180 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800181 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700182 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800183 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800184 }
185}
186
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700187uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800188 struct timespec ts;
189 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800190 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800191}
192
Felipe Lemee844a9d2016-09-21 15:01:39 -0700193// TODO: temporary function used during the C++ refactoring
194static bool is_dry_run() {
195 return Dumpstate::GetInstance().IsDryRun();
196}
197
John Spurlock5ecd4be2014-01-29 14:14:40 -0500198void for_each_userid(void (*func)(int), const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700199 if (is_dry_run()) return;
200
John Spurlock5ecd4be2014-01-29 14:14:40 -0500201 DIR *d;
202 struct dirent *de;
203
204 if (header) printf("\n------ %s ------\n", header);
205 func(0);
206
207 if (!(d = opendir("/data/system/users"))) {
208 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
209 return;
210 }
211
212 while ((de = readdir(d))) {
213 int userid;
214 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
215 continue;
216 }
217 func(userid);
218 }
219
220 closedir(d);
221}
222
Colin Cross0c22e8b2012-11-02 15:46:56 -0700223static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700224 DIR *d;
225 struct dirent *de;
226
227 if (!(d = opendir("/proc"))) {
228 printf("Failed to open /proc (%s)\n", strerror(errno));
229 return;
230 }
231
Felipe Leme635ca312016-01-05 14:23:02 -0800232 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700233 while ((de = readdir(d))) {
234 int pid;
235 int fd;
236 char cmdpath[255];
237 char cmdline[255];
238
239 if (!(pid = atoi(de->d_name))) {
240 continue;
241 }
242
Colin Crossf45fa6b2012-03-26 12:38:26 -0700243 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800244
245 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
246 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
247 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700248 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800249 if (cmdline[0]) {
250 helper(pid, cmdline, arg);
251 continue;
252 }
253 }
254
255 // if no cmdline, a kernel thread has comm
256 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
257 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
258 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
259 close(fd);
260 if (cmdline[1]) {
261 cmdline[0] = '[';
262 size_t len = strcspn(cmdline, "\f\b\r\n");
263 cmdline[len] = ']';
264 cmdline[len+1] = '\0';
265 }
266 }
267 if (!cmdline[0]) {
268 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700269 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700270 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700271 }
272
273 closedir(d);
274}
275
Colin Cross0c22e8b2012-11-02 15:46:56 -0700276static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800277 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700278 func(pid, cmdline);
279}
280
281void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700282 if (is_dry_run()) return;
283
Felipe Leme515eb0d2015-12-14 15:09:56 -0800284 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700285}
286
287static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
288 DIR *d;
289 struct dirent *de;
290 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800291 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700292
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700293 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700294
295 if (!(d = opendir(taskpath))) {
296 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
297 return;
298 }
299
300 func(pid, pid, cmdline);
301
302 while ((de = readdir(d))) {
303 int tid;
304 int fd;
305 char commpath[255];
306 char comm[255];
307
308 if (!(tid = atoi(de->d_name))) {
309 continue;
310 }
311
312 if (tid == pid)
313 continue;
314
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700315 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800316 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700317 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700318 strcpy(comm, "N/A");
319 } else {
320 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800321 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700322 close(fd);
323
324 c = strrchr(comm, '\n');
325 if (c) {
326 *c = '\0';
327 }
328 }
329 func(pid, tid, comm);
330 }
331
332 closedir(d);
333}
334
335void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700336 if (is_dry_run()) return;
337
Felipe Leme8620bb42015-11-10 11:04:45 -0800338 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700339}
340
341void show_wchan(int pid, int tid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700342 if (is_dry_run()) return;
343
Colin Crossf45fa6b2012-03-26 12:38:26 -0700344 char path[255];
345 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800346 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700347 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700348
349 memset(buffer, 0, sizeof(buffer));
350
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700351 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700352 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700353 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
354 return;
355 }
356
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800357 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
358 save_errno = errno;
359 close(fd);
360
361 if (ret < 0) {
362 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
363 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700364 }
365
Colin Cross0c22e8b2012-11-02 15:46:56 -0700366 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
367 pid == tid ? 0 : 3, "", name);
368
369 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700370
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800371 return;
372}
373
374// print time in centiseconds
375static void snprcent(char *buffer, size_t len, size_t spc,
376 unsigned long long time) {
377 static long hz; // cache discovered hz
378
379 if (hz <= 0) {
380 hz = sysconf(_SC_CLK_TCK);
381 if (hz <= 0) {
382 hz = 1000;
383 }
384 }
385
386 // convert to centiseconds
387 time = (time * 100 + (hz / 2)) / hz;
388
389 char str[16];
390
391 snprintf(str, sizeof(str), " %llu.%02u",
392 time / 100, (unsigned)(time % 100));
393 size_t offset = strlen(buffer);
394 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
395 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
396}
397
398// print permille as a percent
399static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
400 char str[16];
401
402 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
403 size_t offset = strlen(buffer);
404 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
405 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
406}
407
408void show_showtime(int pid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700409 if (is_dry_run()) return;
410
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800411 char path[255];
412 char buffer[1023];
413 int fd, ret, save_errno;
414
415 memset(buffer, 0, sizeof(buffer));
416
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700417 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800418 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
419 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
420 return;
421 }
422
423 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
424 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700425 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800426
427 if (ret < 0) {
428 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
429 return;
430 }
431
432 // field 14 is utime
433 // field 15 is stime
434 // field 42 is iotime
435 unsigned long long utime = 0, stime = 0, iotime = 0;
436 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800437 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
438 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
439 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
440 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800441 &utime, &stime, &iotime) != 3) {
442 return;
443 }
444
445 unsigned long long total = utime + stime;
446 if (!total) {
447 return;
448 }
449
450 unsigned permille = (iotime * 1000 + (total / 2)) / total;
451 if (permille > 1000) {
452 permille = 1000;
453 }
454
455 // try to beautify and stabilize columns at <80 characters
456 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
457 if ((name[0] != '[') || utime) {
458 snprcent(buffer, sizeof(buffer), 57, utime);
459 }
460 snprcent(buffer, sizeof(buffer), 65, stime);
461 if ((name[0] != '[') || iotime) {
462 snprcent(buffer, sizeof(buffer), 73, iotime);
463 }
464 if (iotime) {
465 snprdec(buffer, sizeof(buffer), 79, permille);
466 }
467 puts(buffer); // adds a trailing newline
468
Colin Crossf45fa6b2012-03-26 12:38:26 -0700469 return;
470}
471
472void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800473 const char *title = "KERNEL LOG (dmesg)";
474 DurationReporter duration_reporter(title);
475 printf("------ %s ------\n", title);
476
Felipe Lemed402e7d2016-08-03 09:22:27 -0700477 if (is_dry_run()) return;
478
Elliott Hughes5f87b312012-09-17 11:43:40 -0700479 /* Get size of kernel buffer */
480 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700481 if (size <= 0) {
482 printf("Unexpected klogctl return value: %d\n\n", size);
483 return;
484 }
485 char *buf = (char *) malloc(size + 1);
486 if (buf == NULL) {
487 printf("memory allocation failed\n\n");
488 return;
489 }
490 int retval = klogctl(KLOG_READ_ALL, buf, size);
491 if (retval < 0) {
492 printf("klogctl failure\n\n");
493 free(buf);
494 return;
495 }
496 buf[retval] = '\0';
497 printf("%s\n\n", buf);
498 free(buf);
499 return;
500}
501
502void do_showmap(int pid, const char *name) {
503 char title[255];
504 char arg[255];
505
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700506 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
507 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700508 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700509}
510
Felipe Leme678727a2016-09-21 17:22:11 -0700511static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
512 if (!title.empty()) {
513 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800514
Colin Crossf45fa6b2012-03-26 12:38:26 -0700515 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800516 // Only show the modification time of non-device files.
517 size_t path_len = strlen(path);
518 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
519 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
520 (path_len < 3 || memcmp(path, "/d/", 3)) &&
521 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700522 char stamp[80];
523 time_t mtime = st.st_mtime;
524 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
525 printf(": %s", stamp);
526 }
527 printf(") ------\n");
528 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700529 if (is_dry_run()) {
530 update_progress(WEIGHT_FILE);
531 close(fd);
532 return 0;
533 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700534
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800535 bool newline = false;
536 fd_set read_set;
537 struct timeval tm;
538 while (1) {
539 FD_ZERO(&read_set);
540 FD_SET(fd, &read_set);
541 /* Timeout if no data is read for 30 seconds. */
542 tm.tv_sec = 30;
543 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700544 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800545 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
546 if (ret == -1) {
547 printf("*** %s: select failed: %s\n", path, strerror(errno));
548 newline = true;
549 break;
550 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700551 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800552 printf("*** %s: Timed out after %.3fs\n", path,
553 (float) elapsed / NANOS_PER_SEC);
554 newline = true;
555 break;
556 } else {
557 char buffer[65536];
558 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
559 if (bytes_read > 0) {
560 fwrite(buffer, bytes_read, 1, stdout);
561 newline = (buffer[bytes_read-1] == '\n');
562 } else {
563 if (bytes_read == -1) {
564 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
565 newline = true;
566 }
567 break;
568 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700569 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700570 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800571 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700572 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700573
Colin Crossf45fa6b2012-03-26 12:38:26 -0700574 if (!newline) printf("\n");
Felipe Leme678727a2016-09-21 17:22:11 -0700575 if (!title.empty()) printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700576 return 0;
577}
578
Felipe Leme678727a2016-09-21 17:22:11 -0700579// DEPRECATED: will be removed once device-specific implementations use dumpFile
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800580int dump_file(const char *title, const char *path) {
Felipe Leme678727a2016-09-21 17:22:11 -0700581 return ds.DumpFile(title, path);
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700582}
583
Felipe Leme678727a2016-09-21 17:22:11 -0700584int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700585 DurationReporter durationReporter(title);
586 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800587 if (fd < 0) {
588 int err = errno;
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700589 printf("*** %s: %s\n", path.c_str(), strerror(err));
Felipe Leme678727a2016-09-21 17:22:11 -0700590 if (!title.empty()) printf("\n");
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800591 return -1;
592 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700593 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800594}
595
Felipe Leme71a74ac2016-03-17 15:43:25 -0700596int read_file_as_long(const char *path, long int *output) {
597 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
598 if (fd < 0) {
599 int err = errno;
600 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
601 return -1;
602 }
603 char buffer[50];
604 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
605 if (bytes_read == -1) {
606 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
607 return -2;
608 }
609 if (bytes_read == 0) {
610 MYLOGE("File %s is empty\n", path);
611 return -3;
612 }
613 *output = atoi(buffer);
614 return 0;
615}
616
Mark Salyzyn326842f2015-04-30 09:49:41 -0700617/* calls skip to gate calling dump_from_fd recursively
618 * in the specified directory. dump_from_fd defaults to
619 * dump_file_from_fd above when set to NULL. skip defaults
620 * to false when set to NULL. dump_from_fd will always be
621 * called with title NULL.
622 */
Felipe Leme678727a2016-09-21 17:22:11 -0700623int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
624 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800625 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700626 DIR *dirp;
627 struct dirent *d;
628 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800629 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700630 int fd, retval = 0;
631
Felipe Leme678727a2016-09-21 17:22:11 -0700632 if (!title.empty()) {
633 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700634 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700635 if (is_dry_run()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700636
637 if (dir[strlen(dir) - 1] == '/') {
638 ++slash;
639 }
640 dirp = opendir(dir);
641 if (dirp == NULL) {
642 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800643 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700644 return retval;
645 }
646
647 if (!dump_from_fd) {
648 dump_from_fd = dump_file_from_fd;
649 }
650 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
651 if ((d->d_name[0] == '.')
652 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
653 || (d->d_name[1] == '\0'))) {
654 continue;
655 }
656 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
657 (d->d_type == DT_DIR) ? "/" : "");
658 if (!newpath) {
659 retval = -errno;
660 continue;
661 }
662 if (skip && (*skip)(newpath)) {
663 continue;
664 }
665 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700666 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700667 if (ret < 0) {
668 retval = ret;
669 }
670 continue;
671 }
672 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
673 if (fd < 0) {
674 retval = fd;
675 printf("*** %s: %s\n", newpath, strerror(errno));
676 continue;
677 }
678 (*dump_from_fd)(NULL, newpath, fd);
679 }
680 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700681 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700682 printf("\n");
683 }
684 return retval;
685}
686
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800687/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
688 * it's possible to avoid issues where opening the file itself can get
689 * stuck.
690 */
691int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700692 if (is_dry_run()) return 0;
693
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800694 int flags = fcntl(fd, F_GETFL);
695 if (flags == -1) {
696 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800697 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800698 return -1;
699 } else if (!(flags & O_NONBLOCK)) {
700 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800701 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800702 return -1;
703 }
704 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700705}
706
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800707bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
708 sigset_t child_mask, old_mask;
709 sigemptyset(&child_mask);
710 sigaddset(&child_mask, SIGCHLD);
711
712 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
713 printf("*** sigprocmask failed: %s\n", strerror(errno));
714 return false;
715 }
716
717 struct timespec ts;
718 ts.tv_sec = timeout_seconds;
719 ts.tv_nsec = 0;
720 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
721 int saved_errno = errno;
722 // Set the signals back the way they were.
723 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
724 printf("*** sigprocmask failed: %s\n", strerror(errno));
725 if (ret == 0) {
726 return false;
727 }
728 }
729 if (ret == -1) {
730 errno = saved_errno;
731 if (errno == EAGAIN) {
732 errno = ETIMEDOUT;
733 } else {
734 printf("*** sigtimedwait failed: %s\n", strerror(errno));
735 }
736 return false;
737 }
738
739 pid_t child_pid = waitpid(pid, status, WNOHANG);
740 if (child_pid != pid) {
741 if (child_pid != -1) {
742 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
743 } else {
744 printf("*** waitpid failed: %s\n", strerror(errno));
745 }
746 return false;
747 }
748 return true;
749}
750
Felipe Leme678727a2016-09-21 17:22:11 -0700751// DEPRECATED: will be removed once device-specific implementations use RunCommand
Felipe Leme30dbfa12016-09-02 12:43:26 -0700752int run_command(const char* title, int timeout_seconds, const char* command, ...) {
753 std::vector<std::string> fullCommand = {command};
Felipe Leme93d705b2015-11-10 20:10:25 -0800754 size_t arg;
755 va_list ap;
756 va_start(ap, command);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700757 for (arg = 0; arg < MAX_ARGS_ARRAY_SIZE; ++arg) {
758 const char* ptr = va_arg(ap, const char*);
759 if (ptr == nullptr) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800760 break;
761 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700762 fullCommand.push_back(ptr);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700763 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800764 va_end(ap);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700765
Felipe Leme678727a2016-09-21 17:22:11 -0700766 return ds.RunCommand(title, fullCommand, CommandOptions::WithTimeout(timeout_seconds).Build());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800767}
768
Felipe Leme678727a2016-09-21 17:22:11 -0700769int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
770 const CommandOptions& options) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700771 if (fullCommand.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700772 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700773 return -1;
774 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800775
Felipe Leme30dbfa12016-09-02 12:43:26 -0700776 int size = fullCommand.size() + 1; // null terminated
Felipe Leme6ad9c062016-09-28 11:58:36 -0700777 int startingIndex = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700778 if (options.RootMode() == SU_ROOT) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700779 startingIndex = 2; // "su" "root"
780 size += startingIndex;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700781 }
782
Felipe Leme6ad9c062016-09-28 11:58:36 -0700783 std::vector<const char*> args;
784 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700785
786 std::string commandString;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700787 if (options.RootMode() == SU_ROOT) {
788 args[0] = SU_PATH;
789 commandString += SU_PATH;
790 args[1] = "root";
791 commandString += " root ";
792 }
Felipe Leme6ad9c062016-09-28 11:58:36 -0700793 int i = startingIndex;
794 for (auto arg = fullCommand.begin(); arg != fullCommand.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700795 args[i++] = arg->c_str();
796 commandString += arg->c_str();
797 if (arg != fullCommand.end() - 1) {
798 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800799 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800800 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700801 args[i] = nullptr;
802 const char* path = args[0];
803 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700804
Felipe Leme6ad9c062016-09-28 11:58:36 -0700805 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
806 printf("Skipping '%s' on user build.\n", command);
807 return 0;
808 }
809
Felipe Leme678727a2016-09-21 17:22:11 -0700810 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700811 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700812 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700813
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800814 fflush(stdout);
Felipe Leme6ad9c062016-09-28 11:58:36 -0700815 DurationReporter durationReporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700816
817 const std::string& loggingMessage = options.LoggingMessage();
818 if (!loggingMessage.empty()) {
819 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800820 }
821
Felipe Leme30dbfa12016-09-02 12:43:26 -0700822 if (is_dry_run() && !options.Always()) {
823 update_progress(options.Timeout());
824 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700825 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800826
Felipe Leme30dbfa12016-09-02 12:43:26 -0700827 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700828
Felipe Leme30dbfa12016-09-02 12:43:26 -0700829 /* TODO: for now we're simplifying the progress calculation by using the
830 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
831 * where its weight should be much higher proportionally to its timeout.
832 * Ideally, it should use a options.EstimatedDuration() instead...*/
833 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800834
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700835 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700836 pid_t pid = fork();
837
838 /* handle error case */
839 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700840 if (!silent) printf("*** fork: %s\n", strerror(errno));
841 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700842 return pid;
843 }
844
845 /* handle child case */
846 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700847 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
848 if (!silent)
849 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700850 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700851 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800852 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700853
Felipe Leme29c39712016-04-01 10:02:00 -0700854 if (silent) {
855 // Redirect stderr to stdout
856 dup2(STDERR_FILENO, STDOUT_FILENO);
857 }
858
John Michelaue7b6cf12013-03-07 15:35:35 -0600859 /* make sure the child dies when dumpstate dies */
860 prctl(PR_SET_PDEATHSIG, SIGKILL);
861
Andres Morales2e671bb2014-08-21 12:38:22 -0700862 /* just ignore SIGPIPE, will go down with parent's */
863 struct sigaction sigact;
864 memset(&sigact, 0, sizeof(sigact));
865 sigact.sa_handler = SIG_IGN;
866 sigaction(SIGPIPE, &sigact, NULL);
867
Felipe Leme6ad9c062016-09-28 11:58:36 -0700868 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700869 // execvp's result will be handled after waitpid_with_timeout() below, but
870 // if it failed, it's safer to exit dumpstate.
871 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700872 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700873 // Must call _exit (instead of exit), otherwise it will corrupt the zip
874 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700875 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700876 }
877
878 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800879 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700880 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700881 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800882 if (!ret) {
883 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700884 if (!silent)
885 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
886 (float)elapsed / NANOS_PER_SEC, pid);
887 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", command,
888 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800889 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700890 if (!silent)
891 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
892 (float)elapsed / NANOS_PER_SEC, pid);
893 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
894 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800895 }
896 kill(pid, SIGTERM);
897 if (!waitpid_with_timeout(pid, 5, NULL)) {
898 kill(pid, SIGKILL);
899 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700900 if (!silent)
901 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
902 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700903 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700904 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700905 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800906 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700907 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800908
909 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700910 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
911 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800912 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700913 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
914 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800915 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800916
Felipe Leme71bbfc52015-11-23 14:14:51 -0800917 if (weight > 0) {
918 update_progress(weight);
919 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800920 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700921}
922
Felipe Leme678727a2016-09-21 17:22:11 -0700923void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
924 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700925 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
926 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme30dbfa12016-09-02 12:43:26 -0700927 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700928 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700929}
930
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800931bool drop_root_user() {
932 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
933 MYLOGD("drop_root_user(): already running as Shell");
934 return true;
935 }
936 /* ensure we will keep capabilities when we drop root */
937 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
938 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
939 return false;
940 }
941
942 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700943 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
944 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800945 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
946 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
947 return false;
948 }
949 if (setgid(AID_SHELL) != 0) {
950 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
951 return false;
952 }
953 if (setuid(AID_SHELL) != 0) {
954 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
955 return false;
956 }
957
958 struct __user_cap_header_struct capheader;
959 struct __user_cap_data_struct capdata[2];
960 memset(&capheader, 0, sizeof(capheader));
961 memset(&capdata, 0, sizeof(capdata));
962 capheader.version = _LINUX_CAPABILITY_VERSION_3;
963 capheader.pid = 0;
964
Wei Liuf87959e2016-08-26 14:51:42 -0700965 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
966 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
967 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
968 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800969 capdata[0].inheritable = 0;
970 capdata[1].inheritable = 0;
971
972 if (capset(&capheader, &capdata[0]) < 0) {
973 MYLOGE("capset failed: %s\n", strerror(errno));
974 return false;
975 }
976
977 return true;
978}
979
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800980void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700981 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
982
983 am.insert(am.end(), args.begin(), args.end());
984
Felipe Leme678727a2016-09-21 17:22:11 -0700985 RunCommand("", am, CommandOptions::WithTimeout(20)
986 .Log("Sending broadcast: '%s'\n")
987 .Always()
988 .DropRoot()
989 .RedirectStderr()
990 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800991}
992
Colin Crossf45fa6b2012-03-26 12:38:26 -0700993size_t num_props = 0;
994static char* props[2000];
995
996static void print_prop(const char *key, const char *name, void *user) {
997 (void) user;
998 if (num_props < sizeof(props) / sizeof(props[0])) {
999 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
1000 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
1001 props[num_props++] = strdup(buf);
1002 }
1003}
1004
1005static int compare_prop(const void *a, const void *b) {
1006 return strcmp(*(char * const *) a, *(char * const *) b);
1007}
1008
1009/* prints all the system properties */
1010void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001011 const char* title = "SYSTEM PROPERTIES";
1012 DurationReporter duration_reporter(title);
1013 printf("------ %s ------\n", title);
Felipe Lemed402e7d2016-08-03 09:22:27 -07001014 if (is_dry_run()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001015 size_t i;
1016 num_props = 0;
1017 property_list(print_prop, NULL);
1018 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1019
Colin Crossf45fa6b2012-03-26 12:38:26 -07001020 for (i = 0; i < num_props; ++i) {
1021 fputs(props[i], stdout);
1022 free(props[i]);
1023 }
1024 printf("\n");
1025}
1026
Felipe Leme2628e9e2016-04-12 16:36:51 -07001027int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001028 int s = android_get_control_socket(service);
1029 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001030 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001031 exit(1);
1032 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001033 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001034 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001035 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001036 exit(1);
1037 }
1038
1039 struct sockaddr addr;
1040 socklen_t alen = sizeof(addr);
1041 int fd = accept(s, &addr, &alen);
1042 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001043 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001044 exit(1);
1045 }
1046
Felipe Leme2628e9e2016-04-12 16:36:51 -07001047 return fd;
1048}
1049
1050/* redirect output to a service control socket */
1051void redirect_to_socket(FILE *redirect, const char *service) {
1052 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001053 fflush(redirect);
1054 dup2(fd, fileno(redirect));
1055 close(fd);
1056}
1057
Felipe Leme2628e9e2016-04-12 16:36:51 -07001058// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001059void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001060 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001061
1062 /* skip initial slash */
1063 if (chp[0] == '/')
1064 chp++;
1065
1066 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001067 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001068 while (chp && chp[0]) {
1069 chp = strchr(chp, '/');
1070 if (chp) {
1071 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001072 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001073 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001074 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001075 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001076 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001077 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001078 }
1079 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001080 *chp++ = '/';
1081 }
1082 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001083}
1084
Felipe Leme0f3fb202016-06-10 17:10:53 -07001085void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001086 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001087
Felipe Leme0f3fb202016-06-10 17:10:53 -07001088 int fd = TEMP_FAILURE_RETRY(open(path,
1089 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001090 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001091 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001092 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001093 exit(1);
1094 }
1095
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001096 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001097 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001098}
1099
Felipe Leme0f3fb202016-06-10 17:10:53 -07001100void redirect_to_file(FILE *redirect, char *path) {
1101 _redirect_to_file(redirect, path, O_TRUNC);
1102}
1103
1104void redirect_to_existing_file(FILE *redirect, char *path) {
1105 _redirect_to_file(redirect, path, O_APPEND);
1106}
1107
Jeff Brownbf7f4922012-06-07 16:40:01 -07001108static bool should_dump_native_traces(const char* path) {
1109 for (const char** p = native_processes_to_dump; *p; p++) {
1110 if (!strcmp(*p, path)) {
1111 return true;
1112 }
1113 }
1114 return false;
1115}
1116
1117/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1118const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001119 DurationReporter duration_reporter("DUMP TRACES", nullptr);
1120 if (is_dry_run()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001121
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001122 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001123
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001124 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1125 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001126
1127 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001128 std::string anrTracesPath = tracesPath + ".anr";
1129 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1130 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1131 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001132 }
1133
Colin Crossf45fa6b2012-03-26 12:38:26 -07001134 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001135 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1136 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1137 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001138 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001139 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1140 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001141 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001142 int chmod_ret = fchmod(fd, 0666);
1143 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001144 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001145 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001146 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001147 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001148
Felipe Leme8620bb42015-11-10 11:04:45 -08001149 /* Variables below must be initialized before 'goto' statements */
1150 int dalvik_found = 0;
1151 int ifd, wfd = -1;
1152
Colin Crossf45fa6b2012-03-26 12:38:26 -07001153 /* walk /proc and kill -QUIT all Dalvik processes */
1154 DIR *proc = opendir("/proc");
1155 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001156 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001157 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001158 }
1159
1160 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001161 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001162 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001163 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001164 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001165 }
1166
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001167 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001168 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001169 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001170 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001171 }
1172
1173 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001174 while ((d = readdir(proc))) {
1175 int pid = atoi(d->d_name);
1176 if (pid <= 0) continue;
1177
Jeff Brownbf7f4922012-06-07 16:40:01 -07001178 char path[PATH_MAX];
1179 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001180 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001181 ssize_t len = readlink(path, data, sizeof(data) - 1);
1182 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001183 continue;
1184 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001185 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001186
Colin Cross0d6180f2014-07-16 19:00:46 -07001187 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001188 /* skip zygote -- it won't dump its stack anyway */
1189 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001190 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001191 len = read(cfd, data, sizeof(data) - 1);
1192 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001193 if (len <= 0) {
1194 continue;
1195 }
1196 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001197 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001198 continue;
1199 }
1200
1201 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001202 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001203 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001204 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001205 continue;
1206 }
1207
1208 /* wait for the writable-close notification from inotify */
1209 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001210 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001211 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001212 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001213 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001214 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001215 } else {
1216 struct inotify_event ie;
1217 read(ifd, &ie, sizeof(ie));
1218 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001219
1220 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001221 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001222 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001223 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1224 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001225 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001226 } else if (should_dump_native_traces(data)) {
1227 /* dump native process if appropriate */
1228 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001229 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001230 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001231 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001232 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001233
1234 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1235 if (timeout_failures == 3) {
1236 dprintf(fd, "too many stack dump failures, skipping...\n");
1237 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1238 dprintf(fd, "dumping failed, likely due to a timeout\n");
1239 timeout_failures++;
1240 } else {
1241 timeout_failures = 0;
1242 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001243 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1244 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001245 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001246 }
1247 }
1248
Colin Crossf45fa6b2012-03-26 12:38:26 -07001249 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001250 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001251 }
1252
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001253 static std::string dumpTracesPath = tracesPath + ".bugreport";
1254 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1255 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001256 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001257 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001258 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001259
1260 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001261 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001262
1263error_close_ifd:
1264 close(ifd);
1265error_close_fd:
1266 close(fd);
1267 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001268}
1269
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001270void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001271 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001272 if (is_dry_run()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001273 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1274 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001275 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001276 if (!fp) {
1277 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1278 return;
1279 }
1280 char table[16];
1281 // Each line has an integer (the table number), a space, and a string (the table name). We only
1282 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1283 // Add a fixed max limit so this doesn't go awry.
1284 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001285 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1286 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001287 }
1288 fclose(fp);
1289}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001290
Felipe Leme71bbfc52015-11-23 14:14:51 -08001291// TODO: make this function thread safe if sections are generated in parallel.
1292void update_progress(int delta) {
Felipe Lemee844a9d2016-09-21 15:01:39 -07001293 if (!ds.updateProgress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001294
Felipe Lemee844a9d2016-09-21 15:01:39 -07001295 ds.progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001296
1297 char key[PROPERTY_KEY_MAX];
1298 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001299
1300 // adjusts max on the fly
Felipe Lemee844a9d2016-09-21 15:01:39 -07001301 if (ds.progress_ > ds.weightTotal_) {
1302 int newTotal = ds.weightTotal_ * 1.2;
1303 MYLOGD("Adjusting total weight from %d to %d\n", ds.weightTotal_, newTotal);
1304 ds.weightTotal_ = newTotal;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001305 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001306 snprintf(value, sizeof(value), "%d", ds.weightTotal_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001307 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001308 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001309 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001310 key, value, status);
1311 }
1312 }
1313
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001314 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001315 snprintf(value, sizeof(value), "%d", ds.progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001316
Felipe Lemee844a9d2016-09-21 15:01:39 -07001317 if (ds.progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001318 // We don't want to spam logcat, so only log multiples of 100.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001319 MYLOGD("Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001320 } else {
1321 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1322 // directly for debuggging.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001323 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001324 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001325
Felipe Lemee844a9d2016-09-21 15:01:39 -07001326 if (ds.controlSocketFd_ >= 0) {
1327 dprintf(ds.controlSocketFd_, "PROGRESS:%d/%d\n", ds.progress_, ds.weightTotal_);
1328 fsync(ds.controlSocketFd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001329 }
1330
Felipe Leme71bbfc52015-11-23 14:14:51 -08001331 int status = property_set(key, value);
1332 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001333 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001334 key, value, status);
1335 }
1336}
Felipe Lemee338bf62015-12-07 14:03:50 -08001337
Felipe Leme3634a1e2015-12-09 10:11:47 -08001338void take_screenshot(const std::string& path) {
Felipe Leme678727a2016-09-21 17:22:11 -07001339 RunCommand("", {"/system/bin/screencap", "-p", path},
Felipe Leme30dbfa12016-09-02 12:43:26 -07001340 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001341}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001342
Felipe Leme0c80cf02016-01-05 13:25:34 -08001343void vibrate(FILE* vibrator, int ms) {
1344 fprintf(vibrator, "%d\n", ms);
1345 fflush(vibrator);
1346}
1347
1348bool is_dir(const char* pathname) {
1349 struct stat info;
1350 if (stat(pathname, &info) == -1) {
1351 return false;
1352 }
1353 return S_ISDIR(info.st_mode);
1354}
1355
1356time_t get_mtime(int fd, time_t default_mtime) {
1357 struct stat info;
1358 if (fstat(fd, &info) == -1) {
1359 return default_mtime;
1360 }
1361 return info.st_mtime;
1362}
1363
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001364void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001365 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001366 struct hex {
1367 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001368 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001369 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1370 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1371 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1372 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1373
1374 std::string buffer;
1375 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1376 return;
1377 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001378
1379 printf("------ %s Extended CSD ------\n", ext_csd_path);
1380
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001381 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1382 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001383 return;
1384 }
1385
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001386 int ext_csd_rev = 0;
1387 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1388 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1389 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1390 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001391 return;
1392 }
1393
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001394 static const char *ver_str[] = {
1395 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1396 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001397 printf("rev 1.%d (MMC %s)\n",
1398 ext_csd_rev,
1399 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1400 ver_str[ext_csd_rev] :
1401 "Unknown");
1402 if (ext_csd_rev < 7) {
1403 printf("\n");
1404 return;
1405 }
1406
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001407 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1408 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001409 return;
1410 }
1411
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001412 int ext_pre_eol_info = 0;
1413 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1414 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1415 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1416 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001417 return;
1418 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001419
1420 static const char *eol_str[] = {
1421 "Undefined",
1422 "Normal",
1423 "Warning (consumed 80% of reserve)",
1424 "Urgent (consumed 90% of reserve)"
1425 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001426 printf("PRE_EOL_INFO %d (MMC %s)\n",
1427 ext_pre_eol_info,
1428 eol_str[(ext_pre_eol_info < (int)
1429 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1430 ext_pre_eol_info : 0]);
1431
1432 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1433 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001434 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001435 int ext_device_life_time_est;
1436 static const char *est_str[] = {
1437 "Undefined",
1438 "0-10% of device lifetime used",
1439 "10-20% of device lifetime used",
1440 "20-30% of device lifetime used",
1441 "30-40% of device lifetime used",
1442 "40-50% of device lifetime used",
1443 "50-60% of device lifetime used",
1444 "60-70% of device lifetime used",
1445 "70-80% of device lifetime used",
1446 "80-90% of device lifetime used",
1447 "90-100% of device lifetime used",
1448 "Exceeded the maximum estimated device lifetime",
1449 };
1450
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001451 if (buffer.length() < (lifetime + sizeof(hex))) {
1452 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001453 break;
1454 }
1455
1456 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001457 sub = buffer.substr(lifetime, sizeof(hex));
1458 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1459 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001460 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001461 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1462 sizeof(hex)) + 'A',
1463 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001464 continue;
1465 }
1466 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001467 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1468 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001469 ext_device_life_time_est,
1470 est_str[(ext_device_life_time_est < (int)
1471 (sizeof(est_str) / sizeof(est_str[0]))) ?
1472 ext_device_life_time_est : 0]);
1473 }
1474
1475 printf("\n");
1476}