blob: 36006af5973ea2ec7684323178918a6944c5280f [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 Lemed80e6b62016-10-03 13:08:14 -070068static void UpdateProgress(int delta) {
69 ds.UpdateProgress(delta);
70}
Felipe Lemee844a9d2016-09-21 15:01:39 -070071
Jeff Brownbf7f4922012-06-07 16:40:01 -070072/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070073// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070074static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080075 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080076 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070077 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070078 "/system/bin/mediacodec", // media.codec
79 "/system/bin/mediadrmserver",
80 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070081 "/system/bin/mediaserver",
82 "/system/bin/sdcard",
83 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070084 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070085 NULL,
86};
87
Felipe Lemee844a9d2016-09-21 15:01:39 -070088/* Most simple commands have 10 as timeout, so 5 is a good estimate */
89static const int WEIGHT_FILE = 5;
90
Felipe Leme30dbfa12016-09-02 12:43:26 -070091CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
92CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
93CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
94CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
95CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
96
Felipe Lemeb0f669d2016-09-26 18:26:11 -070097CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values_(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -070098}
99
100CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700101 values_.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700102 return *this;
103}
104
105CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700106 values_.rootMode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700107 return *this;
108}
109
110CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700111 values_.rootMode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700112 return *this;
113}
114
115CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700116 values_.stdoutMode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700117 return *this;
118}
119
120CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
121 const std::string& message) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700122 values_.loggingMessage_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700123 return *this;
124}
125
126CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700127 return CommandOptions(values_);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700128}
129
130CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700131 : timeout_(timeout),
132 always_(false),
133 rootMode_(DONT_DROP_ROOT),
134 stdoutMode_(NORMAL_STDOUT),
135 loggingMessage_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700136}
137
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700138CommandOptions::CommandOptions(const CommandOptionsValues& values) : values_(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700139}
140
141long CommandOptions::Timeout() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700142 return values_.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700143}
144
145bool CommandOptions::Always() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700146 return values_.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700147}
148
149RootMode CommandOptions::RootMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700150 return values_.rootMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700151}
152
153StdoutMode CommandOptions::StdoutMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700154 return values_.stdoutMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700155}
156
157std::string CommandOptions::LoggingMessage() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700158 return values_.loggingMessage_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700159}
160
161CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
162 return CommandOptions::CommandOptionsBuilder(timeout);
163}
164
Felipe Lemed80e6b62016-10-03 13:08:14 -0700165Dumpstate::Dumpstate(bool dryRun, const std::string& buildType)
166 : dryRun_(dryRun), buildType_(buildType) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700167}
168
169Dumpstate& Dumpstate::GetInstance() {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700170 static Dumpstate sSingleton(android::base::GetBoolProperty("dumpstate.dry_run", false),
171 android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Lemee844a9d2016-09-21 15:01:39 -0700172 return sSingleton;
173}
174
Felipe Leme678727a2016-09-21 17:22:11 -0700175DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
176}
Felipe Leme608385d2016-02-01 10:35:38 -0800177
Felipe Leme678727a2016-09-21 17:22:11 -0700178DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
179 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700180 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800181 }
182}
183
184DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700185 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700186 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800187 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700188 if (out_ != nullptr) {
189 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700190 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800191 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700192 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800193 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800194 }
195}
196
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700197uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800198 struct timespec ts;
199 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800200 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800201}
202
Felipe Leme4c2d6632016-09-28 14:32:00 -0700203bool Dumpstate::IsDryRun() {
204 return dryRun_;
205}
206
207bool Dumpstate::IsUserBuild() {
208 return "user" == buildType_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700209}
210
John Spurlock5ecd4be2014-01-29 14:14:40 -0500211void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700212 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700213
John Spurlock5ecd4be2014-01-29 14:14:40 -0500214 DIR *d;
215 struct dirent *de;
216
217 if (header) printf("\n------ %s ------\n", header);
218 func(0);
219
220 if (!(d = opendir("/data/system/users"))) {
221 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
222 return;
223 }
224
225 while ((de = readdir(d))) {
226 int userid;
227 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
228 continue;
229 }
230 func(userid);
231 }
232
233 closedir(d);
234}
235
Colin Cross0c22e8b2012-11-02 15:46:56 -0700236static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700237 DIR *d;
238 struct dirent *de;
239
240 if (!(d = opendir("/proc"))) {
241 printf("Failed to open /proc (%s)\n", strerror(errno));
242 return;
243 }
244
Felipe Leme635ca312016-01-05 14:23:02 -0800245 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700246 while ((de = readdir(d))) {
247 int pid;
248 int fd;
249 char cmdpath[255];
250 char cmdline[255];
251
252 if (!(pid = atoi(de->d_name))) {
253 continue;
254 }
255
Colin Crossf45fa6b2012-03-26 12:38:26 -0700256 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800257
258 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
259 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
260 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700261 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800262 if (cmdline[0]) {
263 helper(pid, cmdline, arg);
264 continue;
265 }
266 }
267
268 // if no cmdline, a kernel thread has comm
269 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
270 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
271 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
272 close(fd);
273 if (cmdline[1]) {
274 cmdline[0] = '[';
275 size_t len = strcspn(cmdline, "\f\b\r\n");
276 cmdline[len] = ']';
277 cmdline[len+1] = '\0';
278 }
279 }
280 if (!cmdline[0]) {
281 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700282 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700283 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700284 }
285
286 closedir(d);
287}
288
Colin Cross0c22e8b2012-11-02 15:46:56 -0700289static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800290 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700291 func(pid, cmdline);
292}
293
294void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700295 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700296
Felipe Leme515eb0d2015-12-14 15:09:56 -0800297 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700298}
299
300static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
301 DIR *d;
302 struct dirent *de;
303 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800304 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700305
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700306 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700307
308 if (!(d = opendir(taskpath))) {
309 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
310 return;
311 }
312
313 func(pid, pid, cmdline);
314
315 while ((de = readdir(d))) {
316 int tid;
317 int fd;
318 char commpath[255];
319 char comm[255];
320
321 if (!(tid = atoi(de->d_name))) {
322 continue;
323 }
324
325 if (tid == pid)
326 continue;
327
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700328 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800329 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700330 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700331 strcpy(comm, "N/A");
332 } else {
333 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800334 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700335 close(fd);
336
337 c = strrchr(comm, '\n');
338 if (c) {
339 *c = '\0';
340 }
341 }
342 func(pid, tid, comm);
343 }
344
345 closedir(d);
346}
347
348void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700349 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700350
Felipe Leme8620bb42015-11-10 11:04:45 -0800351 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700352}
353
354void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700355 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700356
Colin Crossf45fa6b2012-03-26 12:38:26 -0700357 char path[255];
358 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800359 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700360 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700361
362 memset(buffer, 0, sizeof(buffer));
363
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700364 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700365 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700366 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
367 return;
368 }
369
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800370 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
371 save_errno = errno;
372 close(fd);
373
374 if (ret < 0) {
375 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
376 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700377 }
378
Colin Cross0c22e8b2012-11-02 15:46:56 -0700379 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
380 pid == tid ? 0 : 3, "", name);
381
382 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700383
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800384 return;
385}
386
387// print time in centiseconds
388static void snprcent(char *buffer, size_t len, size_t spc,
389 unsigned long long time) {
390 static long hz; // cache discovered hz
391
392 if (hz <= 0) {
393 hz = sysconf(_SC_CLK_TCK);
394 if (hz <= 0) {
395 hz = 1000;
396 }
397 }
398
399 // convert to centiseconds
400 time = (time * 100 + (hz / 2)) / hz;
401
402 char str[16];
403
404 snprintf(str, sizeof(str), " %llu.%02u",
405 time / 100, (unsigned)(time % 100));
406 size_t offset = strlen(buffer);
407 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
408 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
409}
410
411// print permille as a percent
412static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
413 char str[16];
414
415 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
416 size_t offset = strlen(buffer);
417 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
418 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
419}
420
421void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700422 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700423
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800424 char path[255];
425 char buffer[1023];
426 int fd, ret, save_errno;
427
428 memset(buffer, 0, sizeof(buffer));
429
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700430 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800431 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
432 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
433 return;
434 }
435
436 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
437 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700438 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800439
440 if (ret < 0) {
441 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
442 return;
443 }
444
445 // field 14 is utime
446 // field 15 is stime
447 // field 42 is iotime
448 unsigned long long utime = 0, stime = 0, iotime = 0;
449 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800450 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
451 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
452 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
453 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800454 &utime, &stime, &iotime) != 3) {
455 return;
456 }
457
458 unsigned long long total = utime + stime;
459 if (!total) {
460 return;
461 }
462
463 unsigned permille = (iotime * 1000 + (total / 2)) / total;
464 if (permille > 1000) {
465 permille = 1000;
466 }
467
468 // try to beautify and stabilize columns at <80 characters
469 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
470 if ((name[0] != '[') || utime) {
471 snprcent(buffer, sizeof(buffer), 57, utime);
472 }
473 snprcent(buffer, sizeof(buffer), 65, stime);
474 if ((name[0] != '[') || iotime) {
475 snprcent(buffer, sizeof(buffer), 73, iotime);
476 }
477 if (iotime) {
478 snprdec(buffer, sizeof(buffer), 79, permille);
479 }
480 puts(buffer); // adds a trailing newline
481
Colin Crossf45fa6b2012-03-26 12:38:26 -0700482 return;
483}
484
485void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800486 const char *title = "KERNEL LOG (dmesg)";
487 DurationReporter duration_reporter(title);
488 printf("------ %s ------\n", title);
489
Felipe Leme4c2d6632016-09-28 14:32:00 -0700490 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700491
Elliott Hughes5f87b312012-09-17 11:43:40 -0700492 /* Get size of kernel buffer */
493 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700494 if (size <= 0) {
495 printf("Unexpected klogctl return value: %d\n\n", size);
496 return;
497 }
498 char *buf = (char *) malloc(size + 1);
499 if (buf == NULL) {
500 printf("memory allocation failed\n\n");
501 return;
502 }
503 int retval = klogctl(KLOG_READ_ALL, buf, size);
504 if (retval < 0) {
505 printf("klogctl failure\n\n");
506 free(buf);
507 return;
508 }
509 buf[retval] = '\0';
510 printf("%s\n\n", buf);
511 free(buf);
512 return;
513}
514
515void do_showmap(int pid, const char *name) {
516 char title[255];
517 char arg[255];
518
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700519 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
520 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700521 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700522}
523
Felipe Leme678727a2016-09-21 17:22:11 -0700524static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
525 if (!title.empty()) {
526 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800527
Colin Crossf45fa6b2012-03-26 12:38:26 -0700528 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800529 // Only show the modification time of non-device files.
530 size_t path_len = strlen(path);
531 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
532 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
533 (path_len < 3 || memcmp(path, "/d/", 3)) &&
534 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700535 char stamp[80];
536 time_t mtime = st.st_mtime;
537 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
538 printf(": %s", stamp);
539 }
540 printf(") ------\n");
541 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700542 if (IsDryRun()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700543 UpdateProgress(WEIGHT_FILE);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700544 close(fd);
545 return 0;
546 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700547
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800548 bool newline = false;
549 fd_set read_set;
550 struct timeval tm;
551 while (1) {
552 FD_ZERO(&read_set);
553 FD_SET(fd, &read_set);
554 /* Timeout if no data is read for 30 seconds. */
555 tm.tv_sec = 30;
556 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700557 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800558 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
559 if (ret == -1) {
560 printf("*** %s: select failed: %s\n", path, strerror(errno));
561 newline = true;
562 break;
563 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700564 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800565 printf("*** %s: Timed out after %.3fs\n", path,
566 (float) elapsed / NANOS_PER_SEC);
567 newline = true;
568 break;
569 } else {
570 char buffer[65536];
571 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
572 if (bytes_read > 0) {
573 fwrite(buffer, bytes_read, 1, stdout);
574 newline = (buffer[bytes_read-1] == '\n');
575 } else {
576 if (bytes_read == -1) {
577 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
578 newline = true;
579 }
580 break;
581 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700582 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700583 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700584 UpdateProgress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700585 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700586
Colin Crossf45fa6b2012-03-26 12:38:26 -0700587 if (!newline) printf("\n");
Felipe Leme678727a2016-09-21 17:22:11 -0700588 if (!title.empty()) printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700589 return 0;
590}
591
Felipe Leme678727a2016-09-21 17:22:11 -0700592int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700593 DurationReporter durationReporter(title);
594 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800595 if (fd < 0) {
596 int err = errno;
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700597 printf("*** %s: %s\n", path.c_str(), strerror(err));
Felipe Leme678727a2016-09-21 17:22:11 -0700598 if (!title.empty()) printf("\n");
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800599 return -1;
600 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700601 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800602}
603
Felipe Leme71a74ac2016-03-17 15:43:25 -0700604int read_file_as_long(const char *path, long int *output) {
605 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
606 if (fd < 0) {
607 int err = errno;
608 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
609 return -1;
610 }
611 char buffer[50];
612 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
613 if (bytes_read == -1) {
614 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
615 return -2;
616 }
617 if (bytes_read == 0) {
618 MYLOGE("File %s is empty\n", path);
619 return -3;
620 }
621 *output = atoi(buffer);
622 return 0;
623}
624
Mark Salyzyn326842f2015-04-30 09:49:41 -0700625/* calls skip to gate calling dump_from_fd recursively
626 * in the specified directory. dump_from_fd defaults to
627 * dump_file_from_fd above when set to NULL. skip defaults
628 * to false when set to NULL. dump_from_fd will always be
629 * called with title NULL.
630 */
Felipe Leme678727a2016-09-21 17:22:11 -0700631int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
632 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800633 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700634 DIR *dirp;
635 struct dirent *d;
636 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800637 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700638 int fd, retval = 0;
639
Felipe Leme678727a2016-09-21 17:22:11 -0700640 if (!title.empty()) {
641 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700642 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700643 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700644
645 if (dir[strlen(dir) - 1] == '/') {
646 ++slash;
647 }
648 dirp = opendir(dir);
649 if (dirp == NULL) {
650 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800651 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700652 return retval;
653 }
654
655 if (!dump_from_fd) {
656 dump_from_fd = dump_file_from_fd;
657 }
658 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
659 if ((d->d_name[0] == '.')
660 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
661 || (d->d_name[1] == '\0'))) {
662 continue;
663 }
664 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
665 (d->d_type == DT_DIR) ? "/" : "");
666 if (!newpath) {
667 retval = -errno;
668 continue;
669 }
670 if (skip && (*skip)(newpath)) {
671 continue;
672 }
673 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700674 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700675 if (ret < 0) {
676 retval = ret;
677 }
678 continue;
679 }
680 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
681 if (fd < 0) {
682 retval = fd;
683 printf("*** %s: %s\n", newpath, strerror(errno));
684 continue;
685 }
686 (*dump_from_fd)(NULL, newpath, fd);
687 }
688 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700689 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700690 printf("\n");
691 }
692 return retval;
693}
694
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800695/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
696 * it's possible to avoid issues where opening the file itself can get
697 * stuck.
698 */
699int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700700 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700701
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800702 int flags = fcntl(fd, F_GETFL);
703 if (flags == -1) {
704 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800705 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800706 return -1;
707 } else if (!(flags & O_NONBLOCK)) {
708 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800709 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800710 return -1;
711 }
712 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700713}
714
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800715bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
716 sigset_t child_mask, old_mask;
717 sigemptyset(&child_mask);
718 sigaddset(&child_mask, SIGCHLD);
719
720 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
721 printf("*** sigprocmask failed: %s\n", strerror(errno));
722 return false;
723 }
724
725 struct timespec ts;
726 ts.tv_sec = timeout_seconds;
727 ts.tv_nsec = 0;
728 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
729 int saved_errno = errno;
730 // Set the signals back the way they were.
731 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
732 printf("*** sigprocmask failed: %s\n", strerror(errno));
733 if (ret == 0) {
734 return false;
735 }
736 }
737 if (ret == -1) {
738 errno = saved_errno;
739 if (errno == EAGAIN) {
740 errno = ETIMEDOUT;
741 } else {
742 printf("*** sigtimedwait failed: %s\n", strerror(errno));
743 }
744 return false;
745 }
746
747 pid_t child_pid = waitpid(pid, status, WNOHANG);
748 if (child_pid != pid) {
749 if (child_pid != -1) {
750 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
751 } else {
752 printf("*** waitpid failed: %s\n", strerror(errno));
753 }
754 return false;
755 }
756 return true;
757}
758
Felipe Leme678727a2016-09-21 17:22:11 -0700759int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
760 const CommandOptions& options) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700761 if (fullCommand.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700762 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700763 return -1;
764 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800765
Felipe Leme30dbfa12016-09-02 12:43:26 -0700766 int size = fullCommand.size() + 1; // null terminated
Felipe Leme6ad9c062016-09-28 11:58:36 -0700767 int startingIndex = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700768 if (options.RootMode() == SU_ROOT) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700769 startingIndex = 2; // "su" "root"
770 size += startingIndex;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700771 }
772
Felipe Leme6ad9c062016-09-28 11:58:36 -0700773 std::vector<const char*> args;
774 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700775
776 std::string commandString;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700777 if (options.RootMode() == SU_ROOT) {
778 args[0] = SU_PATH;
779 commandString += SU_PATH;
780 args[1] = "root";
781 commandString += " root ";
782 }
Felipe Leme6ad9c062016-09-28 11:58:36 -0700783 int i = startingIndex;
784 for (auto arg = fullCommand.begin(); arg != fullCommand.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700785 args[i++] = arg->c_str();
786 commandString += arg->c_str();
787 if (arg != fullCommand.end() - 1) {
788 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800789 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800790 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700791 args[i] = nullptr;
792 const char* path = args[0];
793 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700794
Felipe Leme6ad9c062016-09-28 11:58:36 -0700795 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
796 printf("Skipping '%s' on user build.\n", command);
797 return 0;
798 }
799
Felipe Leme678727a2016-09-21 17:22:11 -0700800 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700801 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700802 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700803
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800804 fflush(stdout);
Felipe Leme6ad9c062016-09-28 11:58:36 -0700805 DurationReporter durationReporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700806
807 const std::string& loggingMessage = options.LoggingMessage();
808 if (!loggingMessage.empty()) {
809 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800810 }
811
Felipe Leme4c2d6632016-09-28 14:32:00 -0700812 if (IsDryRun() && !options.Always()) {
813 if (!title.empty()) {
814 printf("\t(skipped on dry run)\n");
815 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700816 UpdateProgress(options.Timeout());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700817 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700818 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800819
Felipe Leme30dbfa12016-09-02 12:43:26 -0700820 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700821
Felipe Leme30dbfa12016-09-02 12:43:26 -0700822 /* TODO: for now we're simplifying the progress calculation by using the
823 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
824 * where its weight should be much higher proportionally to its timeout.
825 * Ideally, it should use a options.EstimatedDuration() instead...*/
826 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800827
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700828 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700829 pid_t pid = fork();
830
831 /* handle error case */
832 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700833 if (!silent) printf("*** fork: %s\n", strerror(errno));
834 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700835 return pid;
836 }
837
838 /* handle child case */
839 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700840 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
841 if (!silent)
842 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700843 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700844 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800845 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700846
Felipe Leme29c39712016-04-01 10:02:00 -0700847 if (silent) {
848 // Redirect stderr to stdout
849 dup2(STDERR_FILENO, STDOUT_FILENO);
850 }
851
John Michelaue7b6cf12013-03-07 15:35:35 -0600852 /* make sure the child dies when dumpstate dies */
853 prctl(PR_SET_PDEATHSIG, SIGKILL);
854
Andres Morales2e671bb2014-08-21 12:38:22 -0700855 /* just ignore SIGPIPE, will go down with parent's */
856 struct sigaction sigact;
857 memset(&sigact, 0, sizeof(sigact));
858 sigact.sa_handler = SIG_IGN;
859 sigaction(SIGPIPE, &sigact, NULL);
860
Felipe Leme6ad9c062016-09-28 11:58:36 -0700861 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700862 // execvp's result will be handled after waitpid_with_timeout() below, but
863 // if it failed, it's safer to exit dumpstate.
864 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700865 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700866 // Must call _exit (instead of exit), otherwise it will corrupt the zip
867 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700868 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700869 }
870
871 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800872 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700873 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700874 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800875 if (!ret) {
876 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700877 if (!silent)
878 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
879 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700880 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -0700881 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800882 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700883 if (!silent)
884 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
885 (float)elapsed / NANOS_PER_SEC, pid);
886 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
887 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800888 }
889 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700890 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800891 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700892 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700893 if (!silent)
894 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
895 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700896 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700897 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700898 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800899 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700900 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800901
902 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700903 if (!silent)
904 printf("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
905 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800906 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700907 status = WEXITSTATUS(status);
908 if (!silent) printf("*** command '%s' failed: exit code %d\n", command, status);
909 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800910 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800911
Felipe Leme71bbfc52015-11-23 14:14:51 -0800912 if (weight > 0) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700913 UpdateProgress(weight);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800914 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800915 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700916}
917
Felipe Leme678727a2016-09-21 17:22:11 -0700918void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
919 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700920 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
921 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme30dbfa12016-09-02 12:43:26 -0700922 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700923 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700924}
925
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800926bool drop_root_user() {
927 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
Felipe Leme26c41572016-10-06 14:34:43 -0700928 MYLOGD("drop_root_user(): already running as Shell\n");
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800929 return true;
930 }
931 /* ensure we will keep capabilities when we drop root */
932 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
933 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
934 return false;
935 }
936
937 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700938 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
939 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800940 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
941 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
942 return false;
943 }
944 if (setgid(AID_SHELL) != 0) {
945 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
946 return false;
947 }
948 if (setuid(AID_SHELL) != 0) {
949 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
950 return false;
951 }
952
953 struct __user_cap_header_struct capheader;
954 struct __user_cap_data_struct capdata[2];
955 memset(&capheader, 0, sizeof(capheader));
956 memset(&capdata, 0, sizeof(capdata));
957 capheader.version = _LINUX_CAPABILITY_VERSION_3;
958 capheader.pid = 0;
959
Wei Liuf87959e2016-08-26 14:51:42 -0700960 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
961 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
962 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
963 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800964 capdata[0].inheritable = 0;
965 capdata[1].inheritable = 0;
966
967 if (capset(&capheader, &capdata[0]) < 0) {
968 MYLOGE("capset failed: %s\n", strerror(errno));
969 return false;
970 }
971
972 return true;
973}
974
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800975void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700976 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
977
978 am.insert(am.end(), args.begin(), args.end());
979
Felipe Leme678727a2016-09-21 17:22:11 -0700980 RunCommand("", am, CommandOptions::WithTimeout(20)
981 .Log("Sending broadcast: '%s'\n")
982 .Always()
983 .DropRoot()
984 .RedirectStderr()
985 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800986}
987
Colin Crossf45fa6b2012-03-26 12:38:26 -0700988size_t num_props = 0;
989static char* props[2000];
990
991static void print_prop(const char *key, const char *name, void *user) {
992 (void) user;
993 if (num_props < sizeof(props) / sizeof(props[0])) {
994 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
995 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
996 props[num_props++] = strdup(buf);
997 }
998}
999
1000static int compare_prop(const void *a, const void *b) {
1001 return strcmp(*(char * const *) a, *(char * const *) b);
1002}
1003
1004/* prints all the system properties */
1005void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001006 const char* title = "SYSTEM PROPERTIES";
1007 DurationReporter duration_reporter(title);
1008 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001009 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001010 size_t i;
1011 num_props = 0;
1012 property_list(print_prop, NULL);
1013 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1014
Colin Crossf45fa6b2012-03-26 12:38:26 -07001015 for (i = 0; i < num_props; ++i) {
1016 fputs(props[i], stdout);
1017 free(props[i]);
1018 }
1019 printf("\n");
1020}
1021
Felipe Leme2628e9e2016-04-12 16:36:51 -07001022int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001023 int s = android_get_control_socket(service);
1024 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001025 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026 exit(1);
1027 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001028 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001029 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001030 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001031 exit(1);
1032 }
1033
1034 struct sockaddr addr;
1035 socklen_t alen = sizeof(addr);
1036 int fd = accept(s, &addr, &alen);
1037 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001038 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001039 exit(1);
1040 }
1041
Felipe Leme2628e9e2016-04-12 16:36:51 -07001042 return fd;
1043}
1044
1045/* redirect output to a service control socket */
1046void redirect_to_socket(FILE *redirect, const char *service) {
1047 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001048 fflush(redirect);
1049 dup2(fd, fileno(redirect));
1050 close(fd);
1051}
1052
Felipe Leme2628e9e2016-04-12 16:36:51 -07001053// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001054void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001055 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001056
1057 /* skip initial slash */
1058 if (chp[0] == '/')
1059 chp++;
1060
1061 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001062 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001063 while (chp && chp[0]) {
1064 chp = strchr(chp, '/');
1065 if (chp) {
1066 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001067 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001068 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001069 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001070 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001071 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001072 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001073 }
1074 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001075 *chp++ = '/';
1076 }
1077 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001078}
1079
Felipe Leme0f3fb202016-06-10 17:10:53 -07001080void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001081 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001082
Felipe Leme0f3fb202016-06-10 17:10:53 -07001083 int fd = TEMP_FAILURE_RETRY(open(path,
1084 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001085 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001086 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001087 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001088 exit(1);
1089 }
1090
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001091 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001092 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001093}
1094
Felipe Leme0f3fb202016-06-10 17:10:53 -07001095void redirect_to_file(FILE *redirect, char *path) {
1096 _redirect_to_file(redirect, path, O_TRUNC);
1097}
1098
1099void redirect_to_existing_file(FILE *redirect, char *path) {
1100 _redirect_to_file(redirect, path, O_APPEND);
1101}
1102
Jeff Brownbf7f4922012-06-07 16:40:01 -07001103static bool should_dump_native_traces(const char* path) {
1104 for (const char** p = native_processes_to_dump; *p; p++) {
1105 if (!strcmp(*p, path)) {
1106 return true;
1107 }
1108 }
1109 return false;
1110}
1111
1112/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1113const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001114 DurationReporter duration_reporter("DUMP TRACES", nullptr);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001115 if (IsDryRun()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001116
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001117 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001118
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001119 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1120 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001121
1122 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001123 std::string anrTracesPath = tracesPath + ".anr";
1124 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1125 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1126 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001127 }
1128
Colin Crossf45fa6b2012-03-26 12:38:26 -07001129 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001130 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1131 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1132 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001133 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001134 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1135 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001136 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001137 int chmod_ret = fchmod(fd, 0666);
1138 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001139 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001140 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001141 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001142 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001143
Felipe Leme8620bb42015-11-10 11:04:45 -08001144 /* Variables below must be initialized before 'goto' statements */
1145 int dalvik_found = 0;
1146 int ifd, wfd = -1;
1147
Colin Crossf45fa6b2012-03-26 12:38:26 -07001148 /* walk /proc and kill -QUIT all Dalvik processes */
1149 DIR *proc = opendir("/proc");
1150 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001151 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001152 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001153 }
1154
1155 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001156 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001157 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001158 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001159 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001160 }
1161
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001162 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001163 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001164 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001165 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001166 }
1167
1168 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169 while ((d = readdir(proc))) {
1170 int pid = atoi(d->d_name);
1171 if (pid <= 0) continue;
1172
Jeff Brownbf7f4922012-06-07 16:40:01 -07001173 char path[PATH_MAX];
1174 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001175 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001176 ssize_t len = readlink(path, data, sizeof(data) - 1);
1177 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001178 continue;
1179 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001180 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001181
Colin Cross0d6180f2014-07-16 19:00:46 -07001182 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001183 /* skip zygote -- it won't dump its stack anyway */
1184 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001185 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001186 len = read(cfd, data, sizeof(data) - 1);
1187 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001188 if (len <= 0) {
1189 continue;
1190 }
1191 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001192 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001193 continue;
1194 }
1195
1196 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001197 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001198 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001199 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001200 continue;
1201 }
1202
1203 /* wait for the writable-close notification from inotify */
1204 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001205 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001206 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001207 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001208 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001209 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001210 } else {
1211 struct inotify_event ie;
1212 read(ifd, &ie, sizeof(ie));
1213 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001214
1215 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001216 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001217 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001218 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1219 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001220 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001221 } else if (should_dump_native_traces(data)) {
1222 /* dump native process if appropriate */
1223 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001224 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001225 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001226 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001227 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001228
1229 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1230 if (timeout_failures == 3) {
1231 dprintf(fd, "too many stack dump failures, skipping...\n");
1232 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1233 dprintf(fd, "dumping failed, likely due to a timeout\n");
1234 timeout_failures++;
1235 } else {
1236 timeout_failures = 0;
1237 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001238 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1239 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001240 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001241 }
1242 }
1243
Colin Crossf45fa6b2012-03-26 12:38:26 -07001244 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001245 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001246 }
1247
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001248 static std::string dumpTracesPath = tracesPath + ".bugreport";
1249 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1250 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001251 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001252 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001253 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001254
1255 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001256 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001257
1258error_close_ifd:
1259 close(ifd);
1260error_close_fd:
1261 close(fd);
1262 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001263}
1264
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001265void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001266 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001267 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001268 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001269 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001270 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001271 if (!fp) {
1272 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1273 return;
1274 }
1275 char table[16];
1276 // Each line has an integer (the table number), a space, and a string (the table name). We only
1277 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1278 // Add a fixed max limit so this doesn't go awry.
1279 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001280 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1281 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001282 }
1283 fclose(fp);
1284}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001285
Felipe Leme71bbfc52015-11-23 14:14:51 -08001286// TODO: make this function thread safe if sections are generated in parallel.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001287void Dumpstate::UpdateProgress(int delta) {
1288 if (!updateProgress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001289
Felipe Lemed80e6b62016-10-03 13:08:14 -07001290 progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001291
1292 char key[PROPERTY_KEY_MAX];
1293 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001294
1295 // adjusts max on the fly
Felipe Lemed80e6b62016-10-03 13:08:14 -07001296 if (progress_ > weightTotal_) {
1297 int newTotal = weightTotal_ * 1.2;
1298 MYLOGD("Adjusting total weight from %d to %d\n", weightTotal_, newTotal);
1299 weightTotal_ = newTotal;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001300 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001301 snprintf(value, sizeof(value), "%d", weightTotal_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001302 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001303 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001304 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001305 key, value, status);
1306 }
1307 }
1308
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001309 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001310 snprintf(value, sizeof(value), "%d", progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001311
Felipe Lemed80e6b62016-10-03 13:08:14 -07001312 if (progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001313 // We don't want to spam logcat, so only log multiples of 100.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001314 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001315 } else {
1316 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1317 // directly for debuggging.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001318 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001319 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001320
Felipe Lemed80e6b62016-10-03 13:08:14 -07001321 if (controlSocketFd_ >= 0) {
1322 dprintf(controlSocketFd_, "PROGRESS:%d/%d\n", progress_, weightTotal_);
1323 fsync(controlSocketFd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001324 }
1325
Felipe Leme71bbfc52015-11-23 14:14:51 -08001326 int status = property_set(key, value);
1327 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001328 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001329 key, value, status);
1330 }
1331}
Felipe Lemee338bf62015-12-07 14:03:50 -08001332
Felipe Leme3634a1e2015-12-09 10:11:47 -08001333void take_screenshot(const std::string& path) {
Felipe Leme678727a2016-09-21 17:22:11 -07001334 RunCommand("", {"/system/bin/screencap", "-p", path},
Felipe Leme30dbfa12016-09-02 12:43:26 -07001335 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001336}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001337
Felipe Leme0c80cf02016-01-05 13:25:34 -08001338void vibrate(FILE* vibrator, int ms) {
1339 fprintf(vibrator, "%d\n", ms);
1340 fflush(vibrator);
1341}
1342
1343bool is_dir(const char* pathname) {
1344 struct stat info;
1345 if (stat(pathname, &info) == -1) {
1346 return false;
1347 }
1348 return S_ISDIR(info.st_mode);
1349}
1350
1351time_t get_mtime(int fd, time_t default_mtime) {
1352 struct stat info;
1353 if (fstat(fd, &info) == -1) {
1354 return default_mtime;
1355 }
1356 return info.st_mtime;
1357}
1358
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001359void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001360 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001361 struct hex {
1362 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001363 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001364 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1365 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1366 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1367 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1368
1369 std::string buffer;
1370 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1371 return;
1372 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001373
1374 printf("------ %s Extended CSD ------\n", ext_csd_path);
1375
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001376 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1377 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001378 return;
1379 }
1380
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001381 int ext_csd_rev = 0;
1382 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1383 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1384 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1385 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001386 return;
1387 }
1388
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001389 static const char *ver_str[] = {
1390 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1391 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001392 printf("rev 1.%d (MMC %s)\n",
1393 ext_csd_rev,
1394 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1395 ver_str[ext_csd_rev] :
1396 "Unknown");
1397 if (ext_csd_rev < 7) {
1398 printf("\n");
1399 return;
1400 }
1401
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001402 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1403 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001404 return;
1405 }
1406
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001407 int ext_pre_eol_info = 0;
1408 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1409 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1410 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1411 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001412 return;
1413 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001414
1415 static const char *eol_str[] = {
1416 "Undefined",
1417 "Normal",
1418 "Warning (consumed 80% of reserve)",
1419 "Urgent (consumed 90% of reserve)"
1420 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001421 printf("PRE_EOL_INFO %d (MMC %s)\n",
1422 ext_pre_eol_info,
1423 eol_str[(ext_pre_eol_info < (int)
1424 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1425 ext_pre_eol_info : 0]);
1426
1427 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1428 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001429 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001430 int ext_device_life_time_est;
1431 static const char *est_str[] = {
1432 "Undefined",
1433 "0-10% of device lifetime used",
1434 "10-20% of device lifetime used",
1435 "20-30% of device lifetime used",
1436 "30-40% of device lifetime used",
1437 "40-50% of device lifetime used",
1438 "50-60% of device lifetime used",
1439 "60-70% of device lifetime used",
1440 "70-80% of device lifetime used",
1441 "80-90% of device lifetime used",
1442 "90-100% of device lifetime used",
1443 "Exceeded the maximum estimated device lifetime",
1444 };
1445
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001446 if (buffer.length() < (lifetime + sizeof(hex))) {
1447 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001448 break;
1449 }
1450
1451 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001452 sub = buffer.substr(lifetime, sizeof(hex));
1453 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1454 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001455 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001456 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1457 sizeof(hex)) + 'A',
1458 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001459 continue;
1460 }
1461 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001462 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1463 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001464 ext_device_life_time_est,
1465 est_str[(ext_device_life_time_est < (int)
1466 (sizeof(est_str) / sizeof(est_str[0]))) ?
1467 ext_device_life_time_est : 0]);
1468 }
1469
1470 printf("\n");
1471}