blob: 55316c5fa36b0ce726a6c142dfabb88d23e11ceb [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 Leme4c2d6632016-09-28 14:32:00 -070063static bool IsDryRun() {
64 return Dumpstate::GetInstance().IsDryRun();
65}
Felipe Lemee844a9d2016-09-21 15:01:39 -070066
Jeff Brownbf7f4922012-06-07 16:40:01 -070067/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070068// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070069static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080070 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080071 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070072 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070073 "/system/bin/mediacodec", // media.codec
74 "/system/bin/mediadrmserver",
75 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070076 "/system/bin/mediaserver",
77 "/system/bin/sdcard",
78 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070079 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070080 NULL,
81};
82
Felipe Lemee844a9d2016-09-21 15:01:39 -070083/* Most simple commands have 10 as timeout, so 5 is a good estimate */
84static const int WEIGHT_FILE = 5;
85
Felipe Leme30dbfa12016-09-02 12:43:26 -070086CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
87CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
88CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
89CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
90CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
91
Felipe Lemeb0f669d2016-09-26 18:26:11 -070092CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values_(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -070093}
94
95CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -070096 values_.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -070097 return *this;
98}
99
100CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700101 values_.rootMode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700102 return *this;
103}
104
105CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700106 values_.rootMode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700107 return *this;
108}
109
110CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700111 values_.stdoutMode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700112 return *this;
113}
114
115CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
116 const std::string& message) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700117 values_.loggingMessage_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700118 return *this;
119}
120
121CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700122 return CommandOptions(values_);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700123}
124
125CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700126 : timeout_(timeout),
127 always_(false),
128 rootMode_(DONT_DROP_ROOT),
129 stdoutMode_(NORMAL_STDOUT),
130 loggingMessage_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700131}
132
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700133CommandOptions::CommandOptions(const CommandOptionsValues& values) : values_(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700134}
135
136long CommandOptions::Timeout() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700137 return values_.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700138}
139
140bool CommandOptions::Always() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700141 return values_.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700142}
143
144RootMode CommandOptions::RootMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700145 return values_.rootMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700146}
147
148StdoutMode CommandOptions::StdoutMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700149 return values_.stdoutMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700150}
151
152std::string CommandOptions::LoggingMessage() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700153 return values_.loggingMessage_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700154}
155
156CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
157 return CommandOptions::CommandOptionsBuilder(timeout);
158}
159
Felipe Leme4c2d6632016-09-28 14:32:00 -0700160Dumpstate::Dumpstate(bool dryRun) : dryRun_(dryRun) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700161}
162
163Dumpstate& Dumpstate::GetInstance() {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700164 static Dumpstate sSingleton(android::base::GetBoolProperty("dumpstate.dry_run", false));
Felipe Lemee844a9d2016-09-21 15:01:39 -0700165 return sSingleton;
166}
167
Felipe Leme678727a2016-09-21 17:22:11 -0700168DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
169}
Felipe Leme608385d2016-02-01 10:35:38 -0800170
Felipe Leme678727a2016-09-21 17:22:11 -0700171DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
172 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700173 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800174 }
175}
176
177DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700178 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700179 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800180 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700181 if (out_ != nullptr) {
182 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700183 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800184 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700185 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800186 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800187 }
188}
189
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700190uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800191 struct timespec ts;
192 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800193 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800194}
195
Felipe Leme4c2d6632016-09-28 14:32:00 -0700196bool Dumpstate::IsDryRun() {
197 return dryRun_;
198}
199
200bool Dumpstate::IsUserBuild() {
201 return "user" == buildType_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700202}
203
John Spurlock5ecd4be2014-01-29 14:14:40 -0500204void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700205 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700206
John Spurlock5ecd4be2014-01-29 14:14:40 -0500207 DIR *d;
208 struct dirent *de;
209
210 if (header) printf("\n------ %s ------\n", header);
211 func(0);
212
213 if (!(d = opendir("/data/system/users"))) {
214 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
215 return;
216 }
217
218 while ((de = readdir(d))) {
219 int userid;
220 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
221 continue;
222 }
223 func(userid);
224 }
225
226 closedir(d);
227}
228
Colin Cross0c22e8b2012-11-02 15:46:56 -0700229static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700230 DIR *d;
231 struct dirent *de;
232
233 if (!(d = opendir("/proc"))) {
234 printf("Failed to open /proc (%s)\n", strerror(errno));
235 return;
236 }
237
Felipe Leme635ca312016-01-05 14:23:02 -0800238 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700239 while ((de = readdir(d))) {
240 int pid;
241 int fd;
242 char cmdpath[255];
243 char cmdline[255];
244
245 if (!(pid = atoi(de->d_name))) {
246 continue;
247 }
248
Colin Crossf45fa6b2012-03-26 12:38:26 -0700249 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800250
251 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
252 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
253 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700254 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800255 if (cmdline[0]) {
256 helper(pid, cmdline, arg);
257 continue;
258 }
259 }
260
261 // if no cmdline, a kernel thread has comm
262 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
263 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
264 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
265 close(fd);
266 if (cmdline[1]) {
267 cmdline[0] = '[';
268 size_t len = strcspn(cmdline, "\f\b\r\n");
269 cmdline[len] = ']';
270 cmdline[len+1] = '\0';
271 }
272 }
273 if (!cmdline[0]) {
274 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700275 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700276 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700277 }
278
279 closedir(d);
280}
281
Colin Cross0c22e8b2012-11-02 15:46:56 -0700282static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800283 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700284 func(pid, cmdline);
285}
286
287void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700288 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700289
Felipe Leme515eb0d2015-12-14 15:09:56 -0800290 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700291}
292
293static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
294 DIR *d;
295 struct dirent *de;
296 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800297 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700298
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700299 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700300
301 if (!(d = opendir(taskpath))) {
302 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
303 return;
304 }
305
306 func(pid, pid, cmdline);
307
308 while ((de = readdir(d))) {
309 int tid;
310 int fd;
311 char commpath[255];
312 char comm[255];
313
314 if (!(tid = atoi(de->d_name))) {
315 continue;
316 }
317
318 if (tid == pid)
319 continue;
320
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700321 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800322 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700323 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700324 strcpy(comm, "N/A");
325 } else {
326 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800327 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700328 close(fd);
329
330 c = strrchr(comm, '\n');
331 if (c) {
332 *c = '\0';
333 }
334 }
335 func(pid, tid, comm);
336 }
337
338 closedir(d);
339}
340
341void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700342 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700343
Felipe Leme8620bb42015-11-10 11:04:45 -0800344 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700345}
346
347void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700348 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700349
Colin Crossf45fa6b2012-03-26 12:38:26 -0700350 char path[255];
351 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800352 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700353 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700354
355 memset(buffer, 0, sizeof(buffer));
356
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700357 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700358 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700359 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
360 return;
361 }
362
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800363 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
364 save_errno = errno;
365 close(fd);
366
367 if (ret < 0) {
368 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
369 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700370 }
371
Colin Cross0c22e8b2012-11-02 15:46:56 -0700372 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
373 pid == tid ? 0 : 3, "", name);
374
375 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700376
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800377 return;
378}
379
380// print time in centiseconds
381static void snprcent(char *buffer, size_t len, size_t spc,
382 unsigned long long time) {
383 static long hz; // cache discovered hz
384
385 if (hz <= 0) {
386 hz = sysconf(_SC_CLK_TCK);
387 if (hz <= 0) {
388 hz = 1000;
389 }
390 }
391
392 // convert to centiseconds
393 time = (time * 100 + (hz / 2)) / hz;
394
395 char str[16];
396
397 snprintf(str, sizeof(str), " %llu.%02u",
398 time / 100, (unsigned)(time % 100));
399 size_t offset = strlen(buffer);
400 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
401 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
402}
403
404// print permille as a percent
405static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
406 char str[16];
407
408 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
409 size_t offset = strlen(buffer);
410 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
411 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
412}
413
414void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700415 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700416
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800417 char path[255];
418 char buffer[1023];
419 int fd, ret, save_errno;
420
421 memset(buffer, 0, sizeof(buffer));
422
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700423 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800424 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
425 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
426 return;
427 }
428
429 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
430 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700431 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800432
433 if (ret < 0) {
434 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
435 return;
436 }
437
438 // field 14 is utime
439 // field 15 is stime
440 // field 42 is iotime
441 unsigned long long utime = 0, stime = 0, iotime = 0;
442 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800443 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
444 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
445 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
446 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800447 &utime, &stime, &iotime) != 3) {
448 return;
449 }
450
451 unsigned long long total = utime + stime;
452 if (!total) {
453 return;
454 }
455
456 unsigned permille = (iotime * 1000 + (total / 2)) / total;
457 if (permille > 1000) {
458 permille = 1000;
459 }
460
461 // try to beautify and stabilize columns at <80 characters
462 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
463 if ((name[0] != '[') || utime) {
464 snprcent(buffer, sizeof(buffer), 57, utime);
465 }
466 snprcent(buffer, sizeof(buffer), 65, stime);
467 if ((name[0] != '[') || iotime) {
468 snprcent(buffer, sizeof(buffer), 73, iotime);
469 }
470 if (iotime) {
471 snprdec(buffer, sizeof(buffer), 79, permille);
472 }
473 puts(buffer); // adds a trailing newline
474
Colin Crossf45fa6b2012-03-26 12:38:26 -0700475 return;
476}
477
478void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800479 const char *title = "KERNEL LOG (dmesg)";
480 DurationReporter duration_reporter(title);
481 printf("------ %s ------\n", title);
482
Felipe Leme4c2d6632016-09-28 14:32:00 -0700483 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700484
Elliott Hughes5f87b312012-09-17 11:43:40 -0700485 /* Get size of kernel buffer */
486 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700487 if (size <= 0) {
488 printf("Unexpected klogctl return value: %d\n\n", size);
489 return;
490 }
491 char *buf = (char *) malloc(size + 1);
492 if (buf == NULL) {
493 printf("memory allocation failed\n\n");
494 return;
495 }
496 int retval = klogctl(KLOG_READ_ALL, buf, size);
497 if (retval < 0) {
498 printf("klogctl failure\n\n");
499 free(buf);
500 return;
501 }
502 buf[retval] = '\0';
503 printf("%s\n\n", buf);
504 free(buf);
505 return;
506}
507
508void do_showmap(int pid, const char *name) {
509 char title[255];
510 char arg[255];
511
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700512 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
513 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700514 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700515}
516
Felipe Leme678727a2016-09-21 17:22:11 -0700517static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
518 if (!title.empty()) {
519 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800520
Colin Crossf45fa6b2012-03-26 12:38:26 -0700521 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800522 // Only show the modification time of non-device files.
523 size_t path_len = strlen(path);
524 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
525 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
526 (path_len < 3 || memcmp(path, "/d/", 3)) &&
527 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700528 char stamp[80];
529 time_t mtime = st.st_mtime;
530 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
531 printf(": %s", stamp);
532 }
533 printf(") ------\n");
534 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700535 if (IsDryRun()) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700536 update_progress(WEIGHT_FILE);
537 close(fd);
538 return 0;
539 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700540
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800541 bool newline = false;
542 fd_set read_set;
543 struct timeval tm;
544 while (1) {
545 FD_ZERO(&read_set);
546 FD_SET(fd, &read_set);
547 /* Timeout if no data is read for 30 seconds. */
548 tm.tv_sec = 30;
549 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700550 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800551 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
552 if (ret == -1) {
553 printf("*** %s: select failed: %s\n", path, strerror(errno));
554 newline = true;
555 break;
556 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700557 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800558 printf("*** %s: Timed out after %.3fs\n", path,
559 (float) elapsed / NANOS_PER_SEC);
560 newline = true;
561 break;
562 } else {
563 char buffer[65536];
564 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
565 if (bytes_read > 0) {
566 fwrite(buffer, bytes_read, 1, stdout);
567 newline = (buffer[bytes_read-1] == '\n');
568 } else {
569 if (bytes_read == -1) {
570 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
571 newline = true;
572 }
573 break;
574 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700575 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700576 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800577 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700578 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700579
Colin Crossf45fa6b2012-03-26 12:38:26 -0700580 if (!newline) printf("\n");
Felipe Leme678727a2016-09-21 17:22:11 -0700581 if (!title.empty()) printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700582 return 0;
583}
584
Felipe Leme678727a2016-09-21 17:22:11 -0700585int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700586 DurationReporter durationReporter(title);
587 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800588 if (fd < 0) {
589 int err = errno;
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700590 printf("*** %s: %s\n", path.c_str(), strerror(err));
Felipe Leme678727a2016-09-21 17:22:11 -0700591 if (!title.empty()) printf("\n");
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800592 return -1;
593 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700594 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800595}
596
Felipe Leme71a74ac2016-03-17 15:43:25 -0700597int read_file_as_long(const char *path, long int *output) {
598 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
599 if (fd < 0) {
600 int err = errno;
601 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
602 return -1;
603 }
604 char buffer[50];
605 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
606 if (bytes_read == -1) {
607 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
608 return -2;
609 }
610 if (bytes_read == 0) {
611 MYLOGE("File %s is empty\n", path);
612 return -3;
613 }
614 *output = atoi(buffer);
615 return 0;
616}
617
Mark Salyzyn326842f2015-04-30 09:49:41 -0700618/* calls skip to gate calling dump_from_fd recursively
619 * in the specified directory. dump_from_fd defaults to
620 * dump_file_from_fd above when set to NULL. skip defaults
621 * to false when set to NULL. dump_from_fd will always be
622 * called with title NULL.
623 */
Felipe Leme678727a2016-09-21 17:22:11 -0700624int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
625 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800626 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700627 DIR *dirp;
628 struct dirent *d;
629 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800630 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700631 int fd, retval = 0;
632
Felipe Leme678727a2016-09-21 17:22:11 -0700633 if (!title.empty()) {
634 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700635 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700636 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700637
638 if (dir[strlen(dir) - 1] == '/') {
639 ++slash;
640 }
641 dirp = opendir(dir);
642 if (dirp == NULL) {
643 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800644 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700645 return retval;
646 }
647
648 if (!dump_from_fd) {
649 dump_from_fd = dump_file_from_fd;
650 }
651 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
652 if ((d->d_name[0] == '.')
653 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
654 || (d->d_name[1] == '\0'))) {
655 continue;
656 }
657 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
658 (d->d_type == DT_DIR) ? "/" : "");
659 if (!newpath) {
660 retval = -errno;
661 continue;
662 }
663 if (skip && (*skip)(newpath)) {
664 continue;
665 }
666 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700667 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700668 if (ret < 0) {
669 retval = ret;
670 }
671 continue;
672 }
673 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
674 if (fd < 0) {
675 retval = fd;
676 printf("*** %s: %s\n", newpath, strerror(errno));
677 continue;
678 }
679 (*dump_from_fd)(NULL, newpath, fd);
680 }
681 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700682 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700683 printf("\n");
684 }
685 return retval;
686}
687
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800688/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
689 * it's possible to avoid issues where opening the file itself can get
690 * stuck.
691 */
692int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700693 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700694
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800695 int flags = fcntl(fd, F_GETFL);
696 if (flags == -1) {
697 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800698 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800699 return -1;
700 } else if (!(flags & O_NONBLOCK)) {
701 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800702 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800703 return -1;
704 }
705 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700706}
707
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800708bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
709 sigset_t child_mask, old_mask;
710 sigemptyset(&child_mask);
711 sigaddset(&child_mask, SIGCHLD);
712
713 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
714 printf("*** sigprocmask failed: %s\n", strerror(errno));
715 return false;
716 }
717
718 struct timespec ts;
719 ts.tv_sec = timeout_seconds;
720 ts.tv_nsec = 0;
721 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
722 int saved_errno = errno;
723 // Set the signals back the way they were.
724 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
725 printf("*** sigprocmask failed: %s\n", strerror(errno));
726 if (ret == 0) {
727 return false;
728 }
729 }
730 if (ret == -1) {
731 errno = saved_errno;
732 if (errno == EAGAIN) {
733 errno = ETIMEDOUT;
734 } else {
735 printf("*** sigtimedwait failed: %s\n", strerror(errno));
736 }
737 return false;
738 }
739
740 pid_t child_pid = waitpid(pid, status, WNOHANG);
741 if (child_pid != pid) {
742 if (child_pid != -1) {
743 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
744 } else {
745 printf("*** waitpid failed: %s\n", strerror(errno));
746 }
747 return false;
748 }
749 return true;
750}
751
Felipe Leme678727a2016-09-21 17:22:11 -0700752int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
753 const CommandOptions& options) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700754 if (fullCommand.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700755 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700756 return -1;
757 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800758
Felipe Leme30dbfa12016-09-02 12:43:26 -0700759 int size = fullCommand.size() + 1; // null terminated
Felipe Leme6ad9c062016-09-28 11:58:36 -0700760 int startingIndex = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700761 if (options.RootMode() == SU_ROOT) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700762 startingIndex = 2; // "su" "root"
763 size += startingIndex;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700764 }
765
Felipe Leme6ad9c062016-09-28 11:58:36 -0700766 std::vector<const char*> args;
767 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700768
769 std::string commandString;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700770 if (options.RootMode() == SU_ROOT) {
771 args[0] = SU_PATH;
772 commandString += SU_PATH;
773 args[1] = "root";
774 commandString += " root ";
775 }
Felipe Leme6ad9c062016-09-28 11:58:36 -0700776 int i = startingIndex;
777 for (auto arg = fullCommand.begin(); arg != fullCommand.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700778 args[i++] = arg->c_str();
779 commandString += arg->c_str();
780 if (arg != fullCommand.end() - 1) {
781 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800782 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800783 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700784 args[i] = nullptr;
785 const char* path = args[0];
786 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700787
Felipe Leme6ad9c062016-09-28 11:58:36 -0700788 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
789 printf("Skipping '%s' on user build.\n", command);
790 return 0;
791 }
792
Felipe Leme678727a2016-09-21 17:22:11 -0700793 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700794 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700795 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700796
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800797 fflush(stdout);
Felipe Leme6ad9c062016-09-28 11:58:36 -0700798 DurationReporter durationReporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700799
800 const std::string& loggingMessage = options.LoggingMessage();
801 if (!loggingMessage.empty()) {
802 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800803 }
804
Felipe Leme4c2d6632016-09-28 14:32:00 -0700805 if (IsDryRun() && !options.Always()) {
806 if (!title.empty()) {
807 printf("\t(skipped on dry run)\n");
808 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700809 update_progress(options.Timeout());
810 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700811 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800812
Felipe Leme30dbfa12016-09-02 12:43:26 -0700813 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700814
Felipe Leme30dbfa12016-09-02 12:43:26 -0700815 /* TODO: for now we're simplifying the progress calculation by using the
816 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
817 * where its weight should be much higher proportionally to its timeout.
818 * Ideally, it should use a options.EstimatedDuration() instead...*/
819 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800820
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700821 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700822 pid_t pid = fork();
823
824 /* handle error case */
825 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700826 if (!silent) printf("*** fork: %s\n", strerror(errno));
827 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700828 return pid;
829 }
830
831 /* handle child case */
832 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700833 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
834 if (!silent)
835 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700836 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700837 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800838 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700839
Felipe Leme29c39712016-04-01 10:02:00 -0700840 if (silent) {
841 // Redirect stderr to stdout
842 dup2(STDERR_FILENO, STDOUT_FILENO);
843 }
844
John Michelaue7b6cf12013-03-07 15:35:35 -0600845 /* make sure the child dies when dumpstate dies */
846 prctl(PR_SET_PDEATHSIG, SIGKILL);
847
Andres Morales2e671bb2014-08-21 12:38:22 -0700848 /* just ignore SIGPIPE, will go down with parent's */
849 struct sigaction sigact;
850 memset(&sigact, 0, sizeof(sigact));
851 sigact.sa_handler = SIG_IGN;
852 sigaction(SIGPIPE, &sigact, NULL);
853
Felipe Leme6ad9c062016-09-28 11:58:36 -0700854 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700855 // execvp's result will be handled after waitpid_with_timeout() below, but
856 // if it failed, it's safer to exit dumpstate.
857 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700858 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700859 // Must call _exit (instead of exit), otherwise it will corrupt the zip
860 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700861 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700862 }
863
864 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800865 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700866 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700867 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800868 if (!ret) {
869 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700870 if (!silent)
871 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
872 (float)elapsed / NANOS_PER_SEC, pid);
873 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", command,
874 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800875 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700876 if (!silent)
877 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
878 (float)elapsed / NANOS_PER_SEC, pid);
879 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
880 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800881 }
882 kill(pid, SIGTERM);
883 if (!waitpid_with_timeout(pid, 5, NULL)) {
884 kill(pid, SIGKILL);
885 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700886 if (!silent)
887 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
888 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700889 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700890 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700891 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800892 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700893 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800894
895 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700896 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
897 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800898 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700899 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
900 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800901 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800902
Felipe Leme71bbfc52015-11-23 14:14:51 -0800903 if (weight > 0) {
904 update_progress(weight);
905 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800906 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700907}
908
Felipe Leme678727a2016-09-21 17:22:11 -0700909void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
910 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700911 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
912 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme30dbfa12016-09-02 12:43:26 -0700913 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700914 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700915}
916
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800917bool drop_root_user() {
918 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
919 MYLOGD("drop_root_user(): already running as Shell");
920 return true;
921 }
922 /* ensure we will keep capabilities when we drop root */
923 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
924 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
925 return false;
926 }
927
928 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700929 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
930 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800931 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
932 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
933 return false;
934 }
935 if (setgid(AID_SHELL) != 0) {
936 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
937 return false;
938 }
939 if (setuid(AID_SHELL) != 0) {
940 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
941 return false;
942 }
943
944 struct __user_cap_header_struct capheader;
945 struct __user_cap_data_struct capdata[2];
946 memset(&capheader, 0, sizeof(capheader));
947 memset(&capdata, 0, sizeof(capdata));
948 capheader.version = _LINUX_CAPABILITY_VERSION_3;
949 capheader.pid = 0;
950
Wei Liuf87959e2016-08-26 14:51:42 -0700951 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
952 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
953 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
954 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800955 capdata[0].inheritable = 0;
956 capdata[1].inheritable = 0;
957
958 if (capset(&capheader, &capdata[0]) < 0) {
959 MYLOGE("capset failed: %s\n", strerror(errno));
960 return false;
961 }
962
963 return true;
964}
965
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800966void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700967 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
968
969 am.insert(am.end(), args.begin(), args.end());
970
Felipe Leme678727a2016-09-21 17:22:11 -0700971 RunCommand("", am, CommandOptions::WithTimeout(20)
972 .Log("Sending broadcast: '%s'\n")
973 .Always()
974 .DropRoot()
975 .RedirectStderr()
976 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800977}
978
Colin Crossf45fa6b2012-03-26 12:38:26 -0700979size_t num_props = 0;
980static char* props[2000];
981
982static void print_prop(const char *key, const char *name, void *user) {
983 (void) user;
984 if (num_props < sizeof(props) / sizeof(props[0])) {
985 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
986 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
987 props[num_props++] = strdup(buf);
988 }
989}
990
991static int compare_prop(const void *a, const void *b) {
992 return strcmp(*(char * const *) a, *(char * const *) b);
993}
994
995/* prints all the system properties */
996void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800997 const char* title = "SYSTEM PROPERTIES";
998 DurationReporter duration_reporter(title);
999 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001000 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001001 size_t i;
1002 num_props = 0;
1003 property_list(print_prop, NULL);
1004 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1005
Colin Crossf45fa6b2012-03-26 12:38:26 -07001006 for (i = 0; i < num_props; ++i) {
1007 fputs(props[i], stdout);
1008 free(props[i]);
1009 }
1010 printf("\n");
1011}
1012
Felipe Leme2628e9e2016-04-12 16:36:51 -07001013int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001014 int s = android_get_control_socket(service);
1015 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001016 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001017 exit(1);
1018 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001019 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001020 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001021 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001022 exit(1);
1023 }
1024
1025 struct sockaddr addr;
1026 socklen_t alen = sizeof(addr);
1027 int fd = accept(s, &addr, &alen);
1028 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001029 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001030 exit(1);
1031 }
1032
Felipe Leme2628e9e2016-04-12 16:36:51 -07001033 return fd;
1034}
1035
1036/* redirect output to a service control socket */
1037void redirect_to_socket(FILE *redirect, const char *service) {
1038 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001039 fflush(redirect);
1040 dup2(fd, fileno(redirect));
1041 close(fd);
1042}
1043
Felipe Leme2628e9e2016-04-12 16:36:51 -07001044// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001045void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001046 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001047
1048 /* skip initial slash */
1049 if (chp[0] == '/')
1050 chp++;
1051
1052 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001053 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001054 while (chp && chp[0]) {
1055 chp = strchr(chp, '/');
1056 if (chp) {
1057 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001058 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001059 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001060 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001061 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001062 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001063 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001064 }
1065 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001066 *chp++ = '/';
1067 }
1068 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001069}
1070
Felipe Leme0f3fb202016-06-10 17:10:53 -07001071void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001072 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001073
Felipe Leme0f3fb202016-06-10 17:10:53 -07001074 int fd = TEMP_FAILURE_RETRY(open(path,
1075 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001076 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001077 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001078 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001079 exit(1);
1080 }
1081
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001082 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001083 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001084}
1085
Felipe Leme0f3fb202016-06-10 17:10:53 -07001086void redirect_to_file(FILE *redirect, char *path) {
1087 _redirect_to_file(redirect, path, O_TRUNC);
1088}
1089
1090void redirect_to_existing_file(FILE *redirect, char *path) {
1091 _redirect_to_file(redirect, path, O_APPEND);
1092}
1093
Jeff Brownbf7f4922012-06-07 16:40:01 -07001094static bool should_dump_native_traces(const char* path) {
1095 for (const char** p = native_processes_to_dump; *p; p++) {
1096 if (!strcmp(*p, path)) {
1097 return true;
1098 }
1099 }
1100 return false;
1101}
1102
1103/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1104const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001105 DurationReporter duration_reporter("DUMP TRACES", nullptr);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001106 if (IsDryRun()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001107
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001108 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001109
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001110 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1111 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001112
1113 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001114 std::string anrTracesPath = tracesPath + ".anr";
1115 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1116 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1117 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001118 }
1119
Colin Crossf45fa6b2012-03-26 12:38:26 -07001120 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001121 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1122 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1123 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001124 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001125 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1126 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001127 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001128 int chmod_ret = fchmod(fd, 0666);
1129 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001130 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001131 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001132 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001133 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001134
Felipe Leme8620bb42015-11-10 11:04:45 -08001135 /* Variables below must be initialized before 'goto' statements */
1136 int dalvik_found = 0;
1137 int ifd, wfd = -1;
1138
Colin Crossf45fa6b2012-03-26 12:38:26 -07001139 /* walk /proc and kill -QUIT all Dalvik processes */
1140 DIR *proc = opendir("/proc");
1141 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001142 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001143 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001144 }
1145
1146 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001147 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001148 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001149 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001150 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001151 }
1152
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001153 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001154 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001155 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001156 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001157 }
1158
1159 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001160 while ((d = readdir(proc))) {
1161 int pid = atoi(d->d_name);
1162 if (pid <= 0) continue;
1163
Jeff Brownbf7f4922012-06-07 16:40:01 -07001164 char path[PATH_MAX];
1165 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001166 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001167 ssize_t len = readlink(path, data, sizeof(data) - 1);
1168 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169 continue;
1170 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001171 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001172
Colin Cross0d6180f2014-07-16 19:00:46 -07001173 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001174 /* skip zygote -- it won't dump its stack anyway */
1175 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001176 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001177 len = read(cfd, data, sizeof(data) - 1);
1178 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001179 if (len <= 0) {
1180 continue;
1181 }
1182 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001183 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001184 continue;
1185 }
1186
1187 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001188 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001189 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001190 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001191 continue;
1192 }
1193
1194 /* wait for the writable-close notification from inotify */
1195 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001196 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001197 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001198 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001199 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001200 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001201 } else {
1202 struct inotify_event ie;
1203 read(ifd, &ie, sizeof(ie));
1204 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001205
1206 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001207 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001208 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001209 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1210 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001211 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001212 } else if (should_dump_native_traces(data)) {
1213 /* dump native process if appropriate */
1214 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001215 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001216 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001217 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001218 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001219
1220 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1221 if (timeout_failures == 3) {
1222 dprintf(fd, "too many stack dump failures, skipping...\n");
1223 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1224 dprintf(fd, "dumping failed, likely due to a timeout\n");
1225 timeout_failures++;
1226 } else {
1227 timeout_failures = 0;
1228 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001229 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1230 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001231 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001232 }
1233 }
1234
Colin Crossf45fa6b2012-03-26 12:38:26 -07001235 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001236 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001237 }
1238
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001239 static std::string dumpTracesPath = tracesPath + ".bugreport";
1240 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1241 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001242 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001243 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001244 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001245
1246 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001247 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001248
1249error_close_ifd:
1250 close(ifd);
1251error_close_fd:
1252 close(fd);
1253 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001254}
1255
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001256void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001257 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001258 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001259 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001260 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001261 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001262 if (!fp) {
1263 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1264 return;
1265 }
1266 char table[16];
1267 // Each line has an integer (the table number), a space, and a string (the table name). We only
1268 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1269 // Add a fixed max limit so this doesn't go awry.
1270 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001271 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1272 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001273 }
1274 fclose(fp);
1275}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001276
Felipe Leme71bbfc52015-11-23 14:14:51 -08001277// TODO: make this function thread safe if sections are generated in parallel.
1278void update_progress(int delta) {
Felipe Lemee844a9d2016-09-21 15:01:39 -07001279 if (!ds.updateProgress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001280
Felipe Lemee844a9d2016-09-21 15:01:39 -07001281 ds.progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001282
1283 char key[PROPERTY_KEY_MAX];
1284 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001285
1286 // adjusts max on the fly
Felipe Lemee844a9d2016-09-21 15:01:39 -07001287 if (ds.progress_ > ds.weightTotal_) {
1288 int newTotal = ds.weightTotal_ * 1.2;
1289 MYLOGD("Adjusting total weight from %d to %d\n", ds.weightTotal_, newTotal);
1290 ds.weightTotal_ = newTotal;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001291 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001292 snprintf(value, sizeof(value), "%d", ds.weightTotal_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001293 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001294 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001295 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001296 key, value, status);
1297 }
1298 }
1299
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001300 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001301 snprintf(value, sizeof(value), "%d", ds.progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001302
Felipe Lemee844a9d2016-09-21 15:01:39 -07001303 if (ds.progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001304 // We don't want to spam logcat, so only log multiples of 100.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001305 MYLOGD("Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001306 } else {
1307 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1308 // directly for debuggging.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001309 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001310 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001311
Felipe Lemee844a9d2016-09-21 15:01:39 -07001312 if (ds.controlSocketFd_ >= 0) {
1313 dprintf(ds.controlSocketFd_, "PROGRESS:%d/%d\n", ds.progress_, ds.weightTotal_);
1314 fsync(ds.controlSocketFd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001315 }
1316
Felipe Leme71bbfc52015-11-23 14:14:51 -08001317 int status = property_set(key, value);
1318 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001319 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001320 key, value, status);
1321 }
1322}
Felipe Lemee338bf62015-12-07 14:03:50 -08001323
Felipe Leme3634a1e2015-12-09 10:11:47 -08001324void take_screenshot(const std::string& path) {
Felipe Leme678727a2016-09-21 17:22:11 -07001325 RunCommand("", {"/system/bin/screencap", "-p", path},
Felipe Leme30dbfa12016-09-02 12:43:26 -07001326 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001327}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001328
Felipe Leme0c80cf02016-01-05 13:25:34 -08001329void vibrate(FILE* vibrator, int ms) {
1330 fprintf(vibrator, "%d\n", ms);
1331 fflush(vibrator);
1332}
1333
1334bool is_dir(const char* pathname) {
1335 struct stat info;
1336 if (stat(pathname, &info) == -1) {
1337 return false;
1338 }
1339 return S_ISDIR(info.st_mode);
1340}
1341
1342time_t get_mtime(int fd, time_t default_mtime) {
1343 struct stat info;
1344 if (fstat(fd, &info) == -1) {
1345 return default_mtime;
1346 }
1347 return info.st_mtime;
1348}
1349
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001350void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001351 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001352 struct hex {
1353 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001354 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001355 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1356 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1357 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1358 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1359
1360 std::string buffer;
1361 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1362 return;
1363 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001364
1365 printf("------ %s Extended CSD ------\n", ext_csd_path);
1366
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001367 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1368 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001369 return;
1370 }
1371
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001372 int ext_csd_rev = 0;
1373 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1374 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1375 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1376 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001377 return;
1378 }
1379
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001380 static const char *ver_str[] = {
1381 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1382 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001383 printf("rev 1.%d (MMC %s)\n",
1384 ext_csd_rev,
1385 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1386 ver_str[ext_csd_rev] :
1387 "Unknown");
1388 if (ext_csd_rev < 7) {
1389 printf("\n");
1390 return;
1391 }
1392
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001393 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1394 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001395 return;
1396 }
1397
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001398 int ext_pre_eol_info = 0;
1399 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1400 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1401 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1402 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001403 return;
1404 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001405
1406 static const char *eol_str[] = {
1407 "Undefined",
1408 "Normal",
1409 "Warning (consumed 80% of reserve)",
1410 "Urgent (consumed 90% of reserve)"
1411 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001412 printf("PRE_EOL_INFO %d (MMC %s)\n",
1413 ext_pre_eol_info,
1414 eol_str[(ext_pre_eol_info < (int)
1415 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1416 ext_pre_eol_info : 0]);
1417
1418 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1419 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001420 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001421 int ext_device_life_time_est;
1422 static const char *est_str[] = {
1423 "Undefined",
1424 "0-10% of device lifetime used",
1425 "10-20% of device lifetime used",
1426 "20-30% of device lifetime used",
1427 "30-40% of device lifetime used",
1428 "40-50% of device lifetime used",
1429 "50-60% of device lifetime used",
1430 "60-70% of device lifetime used",
1431 "70-80% of device lifetime used",
1432 "80-90% of device lifetime used",
1433 "90-100% of device lifetime used",
1434 "Exceeded the maximum estimated device lifetime",
1435 };
1436
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001437 if (buffer.length() < (lifetime + sizeof(hex))) {
1438 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001439 break;
1440 }
1441
1442 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001443 sub = buffer.substr(lifetime, sizeof(hex));
1444 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1445 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001446 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001447 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1448 sizeof(hex)) + 'A',
1449 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001450 continue;
1451 }
1452 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001453 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1454 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001455 ext_device_life_time_est,
1456 est_str[(ext_device_life_time_est < (int)
1457 (sizeof(est_str) / sizeof(est_str[0]))) ?
1458 ext_device_life_time_est : 0]);
1459 }
1460
1461 printf("\n");
1462}