blob: b347ce8f8bab9c2b4f5e514519ae50776a78fb53 [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
Felipe Lemefd8affa2016-09-30 17:38:57 -070053#define SU_PATH "/system/xbin/su"
54
Jeff Brown1dc94e32014-09-11 14:15:27 -070055static const int64_t NANOS_PER_SEC = 1000000000;
56
Felipe Leme61884122016-06-13 09:23:30 -070057static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
58
Felipe Lemee844a9d2016-09-21 15:01:39 -070059// TODO: temporary variables and functions used during C++ refactoring
60static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme678727a2016-09-21 17:22:11 -070061static int RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
62 const CommandOptions& options = CommandOptions::DEFAULT) {
63 return ds.RunCommand(title, fullCommand, options);
64}
Felipe Leme4c2d6632016-09-28 14:32:00 -070065static bool IsDryRun() {
66 return Dumpstate::GetInstance().IsDryRun();
67}
Felipe Lemee844a9d2016-09-21 15:01:39 -070068
Jeff Brownbf7f4922012-06-07 16:40:01 -070069/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070070// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070071static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080072 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080073 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070074 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070075 "/system/bin/mediacodec", // media.codec
76 "/system/bin/mediadrmserver",
77 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070078 "/system/bin/mediaserver",
79 "/system/bin/sdcard",
80 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070081 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070082 NULL,
83};
84
Felipe Lemee844a9d2016-09-21 15:01:39 -070085/* Most simple commands have 10 as timeout, so 5 is a good estimate */
86static const int WEIGHT_FILE = 5;
87
Felipe Leme30dbfa12016-09-02 12:43:26 -070088CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
89CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
90CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
91CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
92CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
93
Felipe Lemeb0f669d2016-09-26 18:26:11 -070094CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values_(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -070095}
96
97CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -070098 values_.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -070099 return *this;
100}
101
102CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700103 values_.rootMode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700104 return *this;
105}
106
107CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700108 values_.rootMode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700109 return *this;
110}
111
112CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700113 values_.stdoutMode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700114 return *this;
115}
116
117CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
118 const std::string& message) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700119 values_.loggingMessage_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700120 return *this;
121}
122
123CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700124 return CommandOptions(values_);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700125}
126
127CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700128 : timeout_(timeout),
129 always_(false),
130 rootMode_(DONT_DROP_ROOT),
131 stdoutMode_(NORMAL_STDOUT),
132 loggingMessage_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700133}
134
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700135CommandOptions::CommandOptions(const CommandOptionsValues& values) : values_(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700136}
137
138long CommandOptions::Timeout() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700139 return values_.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700140}
141
142bool CommandOptions::Always() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700143 return values_.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700144}
145
146RootMode CommandOptions::RootMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700147 return values_.rootMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700148}
149
150StdoutMode CommandOptions::StdoutMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700151 return values_.stdoutMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700152}
153
154std::string CommandOptions::LoggingMessage() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700155 return values_.loggingMessage_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700156}
157
158CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
159 return CommandOptions::CommandOptionsBuilder(timeout);
160}
161
Felipe Leme4c2d6632016-09-28 14:32:00 -0700162Dumpstate::Dumpstate(bool dryRun) : dryRun_(dryRun) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700163}
164
165Dumpstate& Dumpstate::GetInstance() {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700166 static Dumpstate sSingleton(android::base::GetBoolProperty("dumpstate.dry_run", false));
Felipe Lemee844a9d2016-09-21 15:01:39 -0700167 return sSingleton;
168}
169
Felipe Leme678727a2016-09-21 17:22:11 -0700170DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
171}
Felipe Leme608385d2016-02-01 10:35:38 -0800172
Felipe Leme678727a2016-09-21 17:22:11 -0700173DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
174 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700175 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800176 }
177}
178
179DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700180 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700181 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800182 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700183 if (out_ != nullptr) {
184 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700185 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800186 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700187 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800188 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800189 }
190}
191
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700192uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800193 struct timespec ts;
194 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800195 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800196}
197
Felipe Leme4c2d6632016-09-28 14:32:00 -0700198bool Dumpstate::IsDryRun() {
199 return dryRun_;
200}
201
202bool Dumpstate::IsUserBuild() {
203 return "user" == buildType_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700204}
205
John Spurlock5ecd4be2014-01-29 14:14:40 -0500206void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700207 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700208
John Spurlock5ecd4be2014-01-29 14:14:40 -0500209 DIR *d;
210 struct dirent *de;
211
212 if (header) printf("\n------ %s ------\n", header);
213 func(0);
214
215 if (!(d = opendir("/data/system/users"))) {
216 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
217 return;
218 }
219
220 while ((de = readdir(d))) {
221 int userid;
222 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
223 continue;
224 }
225 func(userid);
226 }
227
228 closedir(d);
229}
230
Colin Cross0c22e8b2012-11-02 15:46:56 -0700231static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700232 DIR *d;
233 struct dirent *de;
234
235 if (!(d = opendir("/proc"))) {
236 printf("Failed to open /proc (%s)\n", strerror(errno));
237 return;
238 }
239
Felipe Leme635ca312016-01-05 14:23:02 -0800240 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700241 while ((de = readdir(d))) {
242 int pid;
243 int fd;
244 char cmdpath[255];
245 char cmdline[255];
246
247 if (!(pid = atoi(de->d_name))) {
248 continue;
249 }
250
Colin Crossf45fa6b2012-03-26 12:38:26 -0700251 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800252
253 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
254 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
255 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700256 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800257 if (cmdline[0]) {
258 helper(pid, cmdline, arg);
259 continue;
260 }
261 }
262
263 // if no cmdline, a kernel thread has comm
264 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
265 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
266 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
267 close(fd);
268 if (cmdline[1]) {
269 cmdline[0] = '[';
270 size_t len = strcspn(cmdline, "\f\b\r\n");
271 cmdline[len] = ']';
272 cmdline[len+1] = '\0';
273 }
274 }
275 if (!cmdline[0]) {
276 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700277 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700278 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700279 }
280
281 closedir(d);
282}
283
Colin Cross0c22e8b2012-11-02 15:46:56 -0700284static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800285 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700286 func(pid, cmdline);
287}
288
289void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700290 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700291
Felipe Leme515eb0d2015-12-14 15:09:56 -0800292 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700293}
294
295static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
296 DIR *d;
297 struct dirent *de;
298 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800299 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700300
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700301 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700302
303 if (!(d = opendir(taskpath))) {
304 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
305 return;
306 }
307
308 func(pid, pid, cmdline);
309
310 while ((de = readdir(d))) {
311 int tid;
312 int fd;
313 char commpath[255];
314 char comm[255];
315
316 if (!(tid = atoi(de->d_name))) {
317 continue;
318 }
319
320 if (tid == pid)
321 continue;
322
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700323 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800324 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700325 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700326 strcpy(comm, "N/A");
327 } else {
328 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800329 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700330 close(fd);
331
332 c = strrchr(comm, '\n');
333 if (c) {
334 *c = '\0';
335 }
336 }
337 func(pid, tid, comm);
338 }
339
340 closedir(d);
341}
342
343void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700344 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700345
Felipe Leme8620bb42015-11-10 11:04:45 -0800346 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700347}
348
349void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700350 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700351
Colin Crossf45fa6b2012-03-26 12:38:26 -0700352 char path[255];
353 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800354 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700355 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700356
357 memset(buffer, 0, sizeof(buffer));
358
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700359 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700360 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700361 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
362 return;
363 }
364
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800365 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
366 save_errno = errno;
367 close(fd);
368
369 if (ret < 0) {
370 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
371 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700372 }
373
Colin Cross0c22e8b2012-11-02 15:46:56 -0700374 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
375 pid == tid ? 0 : 3, "", name);
376
377 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700378
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800379 return;
380}
381
382// print time in centiseconds
383static void snprcent(char *buffer, size_t len, size_t spc,
384 unsigned long long time) {
385 static long hz; // cache discovered hz
386
387 if (hz <= 0) {
388 hz = sysconf(_SC_CLK_TCK);
389 if (hz <= 0) {
390 hz = 1000;
391 }
392 }
393
394 // convert to centiseconds
395 time = (time * 100 + (hz / 2)) / hz;
396
397 char str[16];
398
399 snprintf(str, sizeof(str), " %llu.%02u",
400 time / 100, (unsigned)(time % 100));
401 size_t offset = strlen(buffer);
402 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
403 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
404}
405
406// print permille as a percent
407static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
408 char str[16];
409
410 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
411 size_t offset = strlen(buffer);
412 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
413 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
414}
415
416void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700417 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700418
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800419 char path[255];
420 char buffer[1023];
421 int fd, ret, save_errno;
422
423 memset(buffer, 0, sizeof(buffer));
424
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700425 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800426 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
427 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
428 return;
429 }
430
431 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
432 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700433 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800434
435 if (ret < 0) {
436 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
437 return;
438 }
439
440 // field 14 is utime
441 // field 15 is stime
442 // field 42 is iotime
443 unsigned long long utime = 0, stime = 0, iotime = 0;
444 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800445 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
446 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
447 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
448 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800449 &utime, &stime, &iotime) != 3) {
450 return;
451 }
452
453 unsigned long long total = utime + stime;
454 if (!total) {
455 return;
456 }
457
458 unsigned permille = (iotime * 1000 + (total / 2)) / total;
459 if (permille > 1000) {
460 permille = 1000;
461 }
462
463 // try to beautify and stabilize columns at <80 characters
464 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
465 if ((name[0] != '[') || utime) {
466 snprcent(buffer, sizeof(buffer), 57, utime);
467 }
468 snprcent(buffer, sizeof(buffer), 65, stime);
469 if ((name[0] != '[') || iotime) {
470 snprcent(buffer, sizeof(buffer), 73, iotime);
471 }
472 if (iotime) {
473 snprdec(buffer, sizeof(buffer), 79, permille);
474 }
475 puts(buffer); // adds a trailing newline
476
Colin Crossf45fa6b2012-03-26 12:38:26 -0700477 return;
478}
479
480void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800481 const char *title = "KERNEL LOG (dmesg)";
482 DurationReporter duration_reporter(title);
483 printf("------ %s ------\n", title);
484
Felipe Leme4c2d6632016-09-28 14:32:00 -0700485 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700486
Elliott Hughes5f87b312012-09-17 11:43:40 -0700487 /* Get size of kernel buffer */
488 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700489 if (size <= 0) {
490 printf("Unexpected klogctl return value: %d\n\n", size);
491 return;
492 }
493 char *buf = (char *) malloc(size + 1);
494 if (buf == NULL) {
495 printf("memory allocation failed\n\n");
496 return;
497 }
498 int retval = klogctl(KLOG_READ_ALL, buf, size);
499 if (retval < 0) {
500 printf("klogctl failure\n\n");
501 free(buf);
502 return;
503 }
504 buf[retval] = '\0';
505 printf("%s\n\n", buf);
506 free(buf);
507 return;
508}
509
510void do_showmap(int pid, const char *name) {
511 char title[255];
512 char arg[255];
513
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700514 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
515 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700516 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700517}
518
Felipe Leme678727a2016-09-21 17:22:11 -0700519static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
520 if (!title.empty()) {
521 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800522
Colin Crossf45fa6b2012-03-26 12:38:26 -0700523 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800524 // Only show the modification time of non-device files.
525 size_t path_len = strlen(path);
526 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
527 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
528 (path_len < 3 || memcmp(path, "/d/", 3)) &&
529 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700530 char stamp[80];
531 time_t mtime = st.st_mtime;
532 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
533 printf(": %s", stamp);
534 }
535 printf(") ------\n");
536 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700537 if (IsDryRun()) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700538 update_progress(WEIGHT_FILE);
539 close(fd);
540 return 0;
541 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700542
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800543 bool newline = false;
544 fd_set read_set;
545 struct timeval tm;
546 while (1) {
547 FD_ZERO(&read_set);
548 FD_SET(fd, &read_set);
549 /* Timeout if no data is read for 30 seconds. */
550 tm.tv_sec = 30;
551 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700552 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800553 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
554 if (ret == -1) {
555 printf("*** %s: select failed: %s\n", path, strerror(errno));
556 newline = true;
557 break;
558 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700559 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800560 printf("*** %s: Timed out after %.3fs\n", path,
561 (float) elapsed / NANOS_PER_SEC);
562 newline = true;
563 break;
564 } else {
565 char buffer[65536];
566 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
567 if (bytes_read > 0) {
568 fwrite(buffer, bytes_read, 1, stdout);
569 newline = (buffer[bytes_read-1] == '\n');
570 } else {
571 if (bytes_read == -1) {
572 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
573 newline = true;
574 }
575 break;
576 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700577 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700578 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800579 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700580 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700581
Colin Crossf45fa6b2012-03-26 12:38:26 -0700582 if (!newline) printf("\n");
Felipe Leme678727a2016-09-21 17:22:11 -0700583 if (!title.empty()) printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700584 return 0;
585}
586
Felipe Leme678727a2016-09-21 17:22:11 -0700587int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700588 DurationReporter durationReporter(title);
589 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800590 if (fd < 0) {
591 int err = errno;
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700592 printf("*** %s: %s\n", path.c_str(), strerror(err));
Felipe Leme678727a2016-09-21 17:22:11 -0700593 if (!title.empty()) printf("\n");
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800594 return -1;
595 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700596 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800597}
598
Felipe Leme71a74ac2016-03-17 15:43:25 -0700599int read_file_as_long(const char *path, long int *output) {
600 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
601 if (fd < 0) {
602 int err = errno;
603 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
604 return -1;
605 }
606 char buffer[50];
607 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
608 if (bytes_read == -1) {
609 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
610 return -2;
611 }
612 if (bytes_read == 0) {
613 MYLOGE("File %s is empty\n", path);
614 return -3;
615 }
616 *output = atoi(buffer);
617 return 0;
618}
619
Mark Salyzyn326842f2015-04-30 09:49:41 -0700620/* calls skip to gate calling dump_from_fd recursively
621 * in the specified directory. dump_from_fd defaults to
622 * dump_file_from_fd above when set to NULL. skip defaults
623 * to false when set to NULL. dump_from_fd will always be
624 * called with title NULL.
625 */
Felipe Leme678727a2016-09-21 17:22:11 -0700626int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
627 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800628 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700629 DIR *dirp;
630 struct dirent *d;
631 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800632 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700633 int fd, retval = 0;
634
Felipe Leme678727a2016-09-21 17:22:11 -0700635 if (!title.empty()) {
636 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700637 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700638 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700639
640 if (dir[strlen(dir) - 1] == '/') {
641 ++slash;
642 }
643 dirp = opendir(dir);
644 if (dirp == NULL) {
645 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800646 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700647 return retval;
648 }
649
650 if (!dump_from_fd) {
651 dump_from_fd = dump_file_from_fd;
652 }
653 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
654 if ((d->d_name[0] == '.')
655 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
656 || (d->d_name[1] == '\0'))) {
657 continue;
658 }
659 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
660 (d->d_type == DT_DIR) ? "/" : "");
661 if (!newpath) {
662 retval = -errno;
663 continue;
664 }
665 if (skip && (*skip)(newpath)) {
666 continue;
667 }
668 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700669 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700670 if (ret < 0) {
671 retval = ret;
672 }
673 continue;
674 }
675 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
676 if (fd < 0) {
677 retval = fd;
678 printf("*** %s: %s\n", newpath, strerror(errno));
679 continue;
680 }
681 (*dump_from_fd)(NULL, newpath, fd);
682 }
683 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700684 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700685 printf("\n");
686 }
687 return retval;
688}
689
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800690/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
691 * it's possible to avoid issues where opening the file itself can get
692 * stuck.
693 */
694int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700695 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700696
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800697 int flags = fcntl(fd, F_GETFL);
698 if (flags == -1) {
699 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800700 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800701 return -1;
702 } else if (!(flags & O_NONBLOCK)) {
703 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800704 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800705 return -1;
706 }
707 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700708}
709
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800710bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
711 sigset_t child_mask, old_mask;
712 sigemptyset(&child_mask);
713 sigaddset(&child_mask, SIGCHLD);
714
715 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
716 printf("*** sigprocmask failed: %s\n", strerror(errno));
717 return false;
718 }
719
720 struct timespec ts;
721 ts.tv_sec = timeout_seconds;
722 ts.tv_nsec = 0;
723 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
724 int saved_errno = errno;
725 // Set the signals back the way they were.
726 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
727 printf("*** sigprocmask failed: %s\n", strerror(errno));
728 if (ret == 0) {
729 return false;
730 }
731 }
732 if (ret == -1) {
733 errno = saved_errno;
734 if (errno == EAGAIN) {
735 errno = ETIMEDOUT;
736 } else {
737 printf("*** sigtimedwait failed: %s\n", strerror(errno));
738 }
739 return false;
740 }
741
742 pid_t child_pid = waitpid(pid, status, WNOHANG);
743 if (child_pid != pid) {
744 if (child_pid != -1) {
745 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
746 } else {
747 printf("*** waitpid failed: %s\n", strerror(errno));
748 }
749 return false;
750 }
751 return true;
752}
753
Felipe Leme678727a2016-09-21 17:22:11 -0700754int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
755 const CommandOptions& options) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700756 if (fullCommand.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700757 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700758 return -1;
759 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800760
Felipe Leme30dbfa12016-09-02 12:43:26 -0700761 int size = fullCommand.size() + 1; // null terminated
Felipe Leme6ad9c062016-09-28 11:58:36 -0700762 int startingIndex = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700763 if (options.RootMode() == SU_ROOT) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700764 startingIndex = 2; // "su" "root"
765 size += startingIndex;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700766 }
767
Felipe Leme6ad9c062016-09-28 11:58:36 -0700768 std::vector<const char*> args;
769 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700770
771 std::string commandString;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700772 if (options.RootMode() == SU_ROOT) {
773 args[0] = SU_PATH;
774 commandString += SU_PATH;
775 args[1] = "root";
776 commandString += " root ";
777 }
Felipe Leme6ad9c062016-09-28 11:58:36 -0700778 int i = startingIndex;
779 for (auto arg = fullCommand.begin(); arg != fullCommand.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700780 args[i++] = arg->c_str();
781 commandString += arg->c_str();
782 if (arg != fullCommand.end() - 1) {
783 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800784 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800785 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700786 args[i] = nullptr;
787 const char* path = args[0];
788 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700789
Felipe Leme6ad9c062016-09-28 11:58:36 -0700790 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
791 printf("Skipping '%s' on user build.\n", command);
792 return 0;
793 }
794
Felipe Leme678727a2016-09-21 17:22:11 -0700795 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700796 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700797 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700798
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800799 fflush(stdout);
Felipe Leme6ad9c062016-09-28 11:58:36 -0700800 DurationReporter durationReporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700801
802 const std::string& loggingMessage = options.LoggingMessage();
803 if (!loggingMessage.empty()) {
804 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800805 }
806
Felipe Leme4c2d6632016-09-28 14:32:00 -0700807 if (IsDryRun() && !options.Always()) {
808 if (!title.empty()) {
809 printf("\t(skipped on dry run)\n");
810 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700811 update_progress(options.Timeout());
812 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700813 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800814
Felipe Leme30dbfa12016-09-02 12:43:26 -0700815 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700816
Felipe Leme30dbfa12016-09-02 12:43:26 -0700817 /* TODO: for now we're simplifying the progress calculation by using the
818 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
819 * where its weight should be much higher proportionally to its timeout.
820 * Ideally, it should use a options.EstimatedDuration() instead...*/
821 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800822
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700823 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700824 pid_t pid = fork();
825
826 /* handle error case */
827 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700828 if (!silent) printf("*** fork: %s\n", strerror(errno));
829 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700830 return pid;
831 }
832
833 /* handle child case */
834 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700835 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
836 if (!silent)
837 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700838 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700839 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800840 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700841
Felipe Leme29c39712016-04-01 10:02:00 -0700842 if (silent) {
843 // Redirect stderr to stdout
844 dup2(STDERR_FILENO, STDOUT_FILENO);
845 }
846
John Michelaue7b6cf12013-03-07 15:35:35 -0600847 /* make sure the child dies when dumpstate dies */
848 prctl(PR_SET_PDEATHSIG, SIGKILL);
849
Andres Morales2e671bb2014-08-21 12:38:22 -0700850 /* just ignore SIGPIPE, will go down with parent's */
851 struct sigaction sigact;
852 memset(&sigact, 0, sizeof(sigact));
853 sigact.sa_handler = SIG_IGN;
854 sigaction(SIGPIPE, &sigact, NULL);
855
Felipe Leme6ad9c062016-09-28 11:58:36 -0700856 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700857 // execvp's result will be handled after waitpid_with_timeout() below, but
858 // if it failed, it's safer to exit dumpstate.
859 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700860 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700861 // Must call _exit (instead of exit), otherwise it will corrupt the zip
862 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700863 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700864 }
865
866 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800867 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700868 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700869 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800870 if (!ret) {
871 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700872 if (!silent)
873 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
874 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700875 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -0700876 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800877 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700878 if (!silent)
879 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
880 (float)elapsed / NANOS_PER_SEC, pid);
881 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
882 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800883 }
884 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700885 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800886 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700887 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700888 if (!silent)
889 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
890 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700891 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700892 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700893 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800894 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700895 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800896
897 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700898 if (!silent)
899 printf("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
900 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800901 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700902 status = WEXITSTATUS(status);
903 if (!silent) printf("*** command '%s' failed: exit code %d\n", command, status);
904 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800905 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800906
Felipe Leme71bbfc52015-11-23 14:14:51 -0800907 if (weight > 0) {
908 update_progress(weight);
909 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800910 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700911}
912
Felipe Leme678727a2016-09-21 17:22:11 -0700913void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
914 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700915 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
916 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme30dbfa12016-09-02 12:43:26 -0700917 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700918 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700919}
920
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800921bool drop_root_user() {
922 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
923 MYLOGD("drop_root_user(): already running as Shell");
924 return true;
925 }
926 /* ensure we will keep capabilities when we drop root */
927 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
928 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
929 return false;
930 }
931
932 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700933 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
934 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800935 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
936 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
937 return false;
938 }
939 if (setgid(AID_SHELL) != 0) {
940 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
941 return false;
942 }
943 if (setuid(AID_SHELL) != 0) {
944 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
945 return false;
946 }
947
948 struct __user_cap_header_struct capheader;
949 struct __user_cap_data_struct capdata[2];
950 memset(&capheader, 0, sizeof(capheader));
951 memset(&capdata, 0, sizeof(capdata));
952 capheader.version = _LINUX_CAPABILITY_VERSION_3;
953 capheader.pid = 0;
954
Wei Liuf87959e2016-08-26 14:51:42 -0700955 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
956 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
957 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
958 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800959 capdata[0].inheritable = 0;
960 capdata[1].inheritable = 0;
961
962 if (capset(&capheader, &capdata[0]) < 0) {
963 MYLOGE("capset failed: %s\n", strerror(errno));
964 return false;
965 }
966
967 return true;
968}
969
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800970void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700971 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
972
973 am.insert(am.end(), args.begin(), args.end());
974
Felipe Leme678727a2016-09-21 17:22:11 -0700975 RunCommand("", am, CommandOptions::WithTimeout(20)
976 .Log("Sending broadcast: '%s'\n")
977 .Always()
978 .DropRoot()
979 .RedirectStderr()
980 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800981}
982
Colin Crossf45fa6b2012-03-26 12:38:26 -0700983size_t num_props = 0;
984static char* props[2000];
985
986static void print_prop(const char *key, const char *name, void *user) {
987 (void) user;
988 if (num_props < sizeof(props) / sizeof(props[0])) {
989 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
990 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
991 props[num_props++] = strdup(buf);
992 }
993}
994
995static int compare_prop(const void *a, const void *b) {
996 return strcmp(*(char * const *) a, *(char * const *) b);
997}
998
999/* prints all the system properties */
1000void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001001 const char* title = "SYSTEM PROPERTIES";
1002 DurationReporter duration_reporter(title);
1003 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001004 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001005 size_t i;
1006 num_props = 0;
1007 property_list(print_prop, NULL);
1008 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1009
Colin Crossf45fa6b2012-03-26 12:38:26 -07001010 for (i = 0; i < num_props; ++i) {
1011 fputs(props[i], stdout);
1012 free(props[i]);
1013 }
1014 printf("\n");
1015}
1016
Felipe Leme2628e9e2016-04-12 16:36:51 -07001017int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001018 int s = android_get_control_socket(service);
1019 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001020 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001021 exit(1);
1022 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001023 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001024 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001025 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026 exit(1);
1027 }
1028
1029 struct sockaddr addr;
1030 socklen_t alen = sizeof(addr);
1031 int fd = accept(s, &addr, &alen);
1032 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001033 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001034 exit(1);
1035 }
1036
Felipe Leme2628e9e2016-04-12 16:36:51 -07001037 return fd;
1038}
1039
1040/* redirect output to a service control socket */
1041void redirect_to_socket(FILE *redirect, const char *service) {
1042 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001043 fflush(redirect);
1044 dup2(fd, fileno(redirect));
1045 close(fd);
1046}
1047
Felipe Leme2628e9e2016-04-12 16:36:51 -07001048// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001049void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001050 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001051
1052 /* skip initial slash */
1053 if (chp[0] == '/')
1054 chp++;
1055
1056 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001057 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001058 while (chp && chp[0]) {
1059 chp = strchr(chp, '/');
1060 if (chp) {
1061 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001062 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001063 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001064 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001065 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001066 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001067 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001068 }
1069 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001070 *chp++ = '/';
1071 }
1072 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001073}
1074
Felipe Leme0f3fb202016-06-10 17:10:53 -07001075void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001076 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001077
Felipe Leme0f3fb202016-06-10 17:10:53 -07001078 int fd = TEMP_FAILURE_RETRY(open(path,
1079 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001080 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001081 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001082 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001083 exit(1);
1084 }
1085
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001086 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001087 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001088}
1089
Felipe Leme0f3fb202016-06-10 17:10:53 -07001090void redirect_to_file(FILE *redirect, char *path) {
1091 _redirect_to_file(redirect, path, O_TRUNC);
1092}
1093
1094void redirect_to_existing_file(FILE *redirect, char *path) {
1095 _redirect_to_file(redirect, path, O_APPEND);
1096}
1097
Jeff Brownbf7f4922012-06-07 16:40:01 -07001098static bool should_dump_native_traces(const char* path) {
1099 for (const char** p = native_processes_to_dump; *p; p++) {
1100 if (!strcmp(*p, path)) {
1101 return true;
1102 }
1103 }
1104 return false;
1105}
1106
1107/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1108const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001109 DurationReporter duration_reporter("DUMP TRACES", nullptr);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001110 if (IsDryRun()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001111
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001112 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001113
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001114 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1115 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001116
1117 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001118 std::string anrTracesPath = tracesPath + ".anr";
1119 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1120 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1121 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001122 }
1123
Colin Crossf45fa6b2012-03-26 12:38:26 -07001124 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001125 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1126 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1127 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001128 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001129 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1130 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001131 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001132 int chmod_ret = fchmod(fd, 0666);
1133 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001134 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001135 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001136 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001137 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001138
Felipe Leme8620bb42015-11-10 11:04:45 -08001139 /* Variables below must be initialized before 'goto' statements */
1140 int dalvik_found = 0;
1141 int ifd, wfd = -1;
1142
Colin Crossf45fa6b2012-03-26 12:38:26 -07001143 /* walk /proc and kill -QUIT all Dalvik processes */
1144 DIR *proc = opendir("/proc");
1145 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001146 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001147 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001148 }
1149
1150 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001151 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001152 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001153 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001154 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001155 }
1156
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001157 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001158 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001159 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001160 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001161 }
1162
1163 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001164 while ((d = readdir(proc))) {
1165 int pid = atoi(d->d_name);
1166 if (pid <= 0) continue;
1167
Jeff Brownbf7f4922012-06-07 16:40:01 -07001168 char path[PATH_MAX];
1169 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001170 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001171 ssize_t len = readlink(path, data, sizeof(data) - 1);
1172 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001173 continue;
1174 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001175 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001176
Colin Cross0d6180f2014-07-16 19:00:46 -07001177 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001178 /* skip zygote -- it won't dump its stack anyway */
1179 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001180 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001181 len = read(cfd, data, sizeof(data) - 1);
1182 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001183 if (len <= 0) {
1184 continue;
1185 }
1186 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001187 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001188 continue;
1189 }
1190
1191 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001192 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001193 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001194 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001195 continue;
1196 }
1197
1198 /* wait for the writable-close notification from inotify */
1199 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001200 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001201 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001202 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001203 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001204 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001205 } else {
1206 struct inotify_event ie;
1207 read(ifd, &ie, sizeof(ie));
1208 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001209
1210 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001211 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001212 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001213 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1214 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001215 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001216 } else if (should_dump_native_traces(data)) {
1217 /* dump native process if appropriate */
1218 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001219 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001220 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001221 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001222 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001223
1224 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1225 if (timeout_failures == 3) {
1226 dprintf(fd, "too many stack dump failures, skipping...\n");
1227 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1228 dprintf(fd, "dumping failed, likely due to a timeout\n");
1229 timeout_failures++;
1230 } else {
1231 timeout_failures = 0;
1232 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001233 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1234 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001235 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001236 }
1237 }
1238
Colin Crossf45fa6b2012-03-26 12:38:26 -07001239 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001240 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001241 }
1242
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001243 static std::string dumpTracesPath = tracesPath + ".bugreport";
1244 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1245 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001246 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001247 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001248 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001249
1250 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001251 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001252
1253error_close_ifd:
1254 close(ifd);
1255error_close_fd:
1256 close(fd);
1257 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001258}
1259
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001260void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001261 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001262 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001263 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001264 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001265 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001266 if (!fp) {
1267 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1268 return;
1269 }
1270 char table[16];
1271 // Each line has an integer (the table number), a space, and a string (the table name). We only
1272 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1273 // Add a fixed max limit so this doesn't go awry.
1274 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001275 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1276 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001277 }
1278 fclose(fp);
1279}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001280
Felipe Leme71bbfc52015-11-23 14:14:51 -08001281// TODO: make this function thread safe if sections are generated in parallel.
1282void update_progress(int delta) {
Felipe Lemee844a9d2016-09-21 15:01:39 -07001283 if (!ds.updateProgress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001284
Felipe Lemee844a9d2016-09-21 15:01:39 -07001285 ds.progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001286
1287 char key[PROPERTY_KEY_MAX];
1288 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001289
1290 // adjusts max on the fly
Felipe Lemee844a9d2016-09-21 15:01:39 -07001291 if (ds.progress_ > ds.weightTotal_) {
1292 int newTotal = ds.weightTotal_ * 1.2;
1293 MYLOGD("Adjusting total weight from %d to %d\n", ds.weightTotal_, newTotal);
1294 ds.weightTotal_ = newTotal;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001295 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001296 snprintf(value, sizeof(value), "%d", ds.weightTotal_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001297 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001298 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001299 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001300 key, value, status);
1301 }
1302 }
1303
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001304 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001305 snprintf(value, sizeof(value), "%d", ds.progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001306
Felipe Lemee844a9d2016-09-21 15:01:39 -07001307 if (ds.progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001308 // We don't want to spam logcat, so only log multiples of 100.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001309 MYLOGD("Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001310 } else {
1311 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1312 // directly for debuggging.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001313 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001314 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001315
Felipe Lemee844a9d2016-09-21 15:01:39 -07001316 if (ds.controlSocketFd_ >= 0) {
1317 dprintf(ds.controlSocketFd_, "PROGRESS:%d/%d\n", ds.progress_, ds.weightTotal_);
1318 fsync(ds.controlSocketFd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001319 }
1320
Felipe Leme71bbfc52015-11-23 14:14:51 -08001321 int status = property_set(key, value);
1322 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001323 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001324 key, value, status);
1325 }
1326}
Felipe Lemee338bf62015-12-07 14:03:50 -08001327
Felipe Leme3634a1e2015-12-09 10:11:47 -08001328void take_screenshot(const std::string& path) {
Felipe Leme678727a2016-09-21 17:22:11 -07001329 RunCommand("", {"/system/bin/screencap", "-p", path},
Felipe Leme30dbfa12016-09-02 12:43:26 -07001330 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001331}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001332
Felipe Leme0c80cf02016-01-05 13:25:34 -08001333void vibrate(FILE* vibrator, int ms) {
1334 fprintf(vibrator, "%d\n", ms);
1335 fflush(vibrator);
1336}
1337
1338bool is_dir(const char* pathname) {
1339 struct stat info;
1340 if (stat(pathname, &info) == -1) {
1341 return false;
1342 }
1343 return S_ISDIR(info.st_mode);
1344}
1345
1346time_t get_mtime(int fd, time_t default_mtime) {
1347 struct stat info;
1348 if (fstat(fd, &info) == -1) {
1349 return default_mtime;
1350 }
1351 return info.st_mtime;
1352}
1353
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001354void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001355 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001356 struct hex {
1357 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001358 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001359 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1360 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1361 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1362 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1363
1364 std::string buffer;
1365 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1366 return;
1367 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001368
1369 printf("------ %s Extended CSD ------\n", ext_csd_path);
1370
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001371 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1372 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001373 return;
1374 }
1375
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001376 int ext_csd_rev = 0;
1377 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1378 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1379 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1380 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001381 return;
1382 }
1383
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001384 static const char *ver_str[] = {
1385 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1386 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001387 printf("rev 1.%d (MMC %s)\n",
1388 ext_csd_rev,
1389 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1390 ver_str[ext_csd_rev] :
1391 "Unknown");
1392 if (ext_csd_rev < 7) {
1393 printf("\n");
1394 return;
1395 }
1396
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001397 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1398 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001399 return;
1400 }
1401
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001402 int ext_pre_eol_info = 0;
1403 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1404 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1405 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1406 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001407 return;
1408 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001409
1410 static const char *eol_str[] = {
1411 "Undefined",
1412 "Normal",
1413 "Warning (consumed 80% of reserve)",
1414 "Urgent (consumed 90% of reserve)"
1415 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001416 printf("PRE_EOL_INFO %d (MMC %s)\n",
1417 ext_pre_eol_info,
1418 eol_str[(ext_pre_eol_info < (int)
1419 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1420 ext_pre_eol_info : 0]);
1421
1422 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1423 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001424 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001425 int ext_device_life_time_est;
1426 static const char *est_str[] = {
1427 "Undefined",
1428 "0-10% of device lifetime used",
1429 "10-20% of device lifetime used",
1430 "20-30% of device lifetime used",
1431 "30-40% of device lifetime used",
1432 "40-50% of device lifetime used",
1433 "50-60% of device lifetime used",
1434 "60-70% of device lifetime used",
1435 "70-80% of device lifetime used",
1436 "80-90% of device lifetime used",
1437 "90-100% of device lifetime used",
1438 "Exceeded the maximum estimated device lifetime",
1439 };
1440
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001441 if (buffer.length() < (lifetime + sizeof(hex))) {
1442 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001443 break;
1444 }
1445
1446 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001447 sub = buffer.substr(lifetime, sizeof(hex));
1448 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1449 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001450 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001451 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1452 sizeof(hex)) + 'A',
1453 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001454 continue;
1455 }
1456 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001457 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1458 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001459 ext_device_life_time_est,
1460 est_str[(ext_device_life_time_est < (int)
1461 (sizeof(est_str) / sizeof(est_str[0]))) ?
1462 ext_device_life_time_est : 0]);
1463 }
1464
1465 printf("\n");
1466}