blob: b7645b434f4b804c1ca7057b47ea574c187d676f [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);
Felipe Lemecef02982016-10-03 17:22:22 -0700594 if (IsDryRun()) {
595 if (!title.empty()) {
596 printf("------ %s (%s) ------\n", title.c_str(), path.c_str());
597 printf("\t(skipped on dry run)\n");
598 }
599 UpdateProgress(WEIGHT_FILE);
600 return 0;
601 }
602
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700603 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800604 if (fd < 0) {
605 int err = errno;
Felipe Lemecef02982016-10-03 17:22:22 -0700606 if (title.empty()) {
607 printf("*** Error dumping %s: %s\n", path.c_str(), strerror(err));
608 } else {
609 printf("*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(), strerror(err));
610 }
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800611 return -1;
612 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700613 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800614}
615
Felipe Leme71a74ac2016-03-17 15:43:25 -0700616int read_file_as_long(const char *path, long int *output) {
617 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
618 if (fd < 0) {
619 int err = errno;
620 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
621 return -1;
622 }
623 char buffer[50];
624 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
625 if (bytes_read == -1) {
626 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
627 return -2;
628 }
629 if (bytes_read == 0) {
630 MYLOGE("File %s is empty\n", path);
631 return -3;
632 }
633 *output = atoi(buffer);
634 return 0;
635}
636
Mark Salyzyn326842f2015-04-30 09:49:41 -0700637/* calls skip to gate calling dump_from_fd recursively
638 * in the specified directory. dump_from_fd defaults to
639 * dump_file_from_fd above when set to NULL. skip defaults
640 * to false when set to NULL. dump_from_fd will always be
641 * called with title NULL.
642 */
Felipe Leme678727a2016-09-21 17:22:11 -0700643int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
644 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800645 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700646 DIR *dirp;
647 struct dirent *d;
648 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800649 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700650 int fd, retval = 0;
651
Felipe Leme678727a2016-09-21 17:22:11 -0700652 if (!title.empty()) {
653 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700654 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700655 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700656
657 if (dir[strlen(dir) - 1] == '/') {
658 ++slash;
659 }
660 dirp = opendir(dir);
661 if (dirp == NULL) {
662 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800663 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700664 return retval;
665 }
666
667 if (!dump_from_fd) {
668 dump_from_fd = dump_file_from_fd;
669 }
670 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
671 if ((d->d_name[0] == '.')
672 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
673 || (d->d_name[1] == '\0'))) {
674 continue;
675 }
676 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
677 (d->d_type == DT_DIR) ? "/" : "");
678 if (!newpath) {
679 retval = -errno;
680 continue;
681 }
682 if (skip && (*skip)(newpath)) {
683 continue;
684 }
685 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700686 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700687 if (ret < 0) {
688 retval = ret;
689 }
690 continue;
691 }
692 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
693 if (fd < 0) {
694 retval = fd;
695 printf("*** %s: %s\n", newpath, strerror(errno));
696 continue;
697 }
698 (*dump_from_fd)(NULL, newpath, fd);
699 }
700 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700701 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700702 printf("\n");
703 }
704 return retval;
705}
706
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800707/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
708 * it's possible to avoid issues where opening the file itself can get
709 * stuck.
710 */
711int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700712 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700713
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800714 int flags = fcntl(fd, F_GETFL);
715 if (flags == -1) {
716 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800717 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800718 return -1;
719 } else if (!(flags & O_NONBLOCK)) {
720 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800721 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800722 return -1;
723 }
724 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700725}
726
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800727bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
728 sigset_t child_mask, old_mask;
729 sigemptyset(&child_mask);
730 sigaddset(&child_mask, SIGCHLD);
731
732 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
733 printf("*** sigprocmask failed: %s\n", strerror(errno));
734 return false;
735 }
736
737 struct timespec ts;
738 ts.tv_sec = timeout_seconds;
739 ts.tv_nsec = 0;
740 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
741 int saved_errno = errno;
742 // Set the signals back the way they were.
743 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
744 printf("*** sigprocmask failed: %s\n", strerror(errno));
745 if (ret == 0) {
746 return false;
747 }
748 }
749 if (ret == -1) {
750 errno = saved_errno;
751 if (errno == EAGAIN) {
752 errno = ETIMEDOUT;
753 } else {
754 printf("*** sigtimedwait failed: %s\n", strerror(errno));
755 }
756 return false;
757 }
758
759 pid_t child_pid = waitpid(pid, status, WNOHANG);
760 if (child_pid != pid) {
761 if (child_pid != -1) {
762 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
763 } else {
764 printf("*** waitpid failed: %s\n", strerror(errno));
765 }
766 return false;
767 }
768 return true;
769}
770
Felipe Leme678727a2016-09-21 17:22:11 -0700771int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
772 const CommandOptions& options) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700773 if (fullCommand.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700774 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700775 return -1;
776 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800777
Felipe Leme30dbfa12016-09-02 12:43:26 -0700778 int size = fullCommand.size() + 1; // null terminated
Felipe Leme6ad9c062016-09-28 11:58:36 -0700779 int startingIndex = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700780 if (options.RootMode() == SU_ROOT) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700781 startingIndex = 2; // "su" "root"
782 size += startingIndex;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700783 }
784
Felipe Leme6ad9c062016-09-28 11:58:36 -0700785 std::vector<const char*> args;
786 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700787
788 std::string commandString;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700789 if (options.RootMode() == SU_ROOT) {
790 args[0] = SU_PATH;
791 commandString += SU_PATH;
792 args[1] = "root";
793 commandString += " root ";
794 }
Felipe Leme6ad9c062016-09-28 11:58:36 -0700795 int i = startingIndex;
796 for (auto arg = fullCommand.begin(); arg != fullCommand.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700797 args[i++] = arg->c_str();
798 commandString += arg->c_str();
799 if (arg != fullCommand.end() - 1) {
800 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800801 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800802 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700803 args[i] = nullptr;
804 const char* path = args[0];
805 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700806
Felipe Leme6ad9c062016-09-28 11:58:36 -0700807 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
808 printf("Skipping '%s' on user build.\n", command);
809 return 0;
810 }
811
Felipe Leme678727a2016-09-21 17:22:11 -0700812 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700813 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700814 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700815
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800816 fflush(stdout);
Felipe Leme6ad9c062016-09-28 11:58:36 -0700817 DurationReporter durationReporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700818
819 const std::string& loggingMessage = options.LoggingMessage();
820 if (!loggingMessage.empty()) {
821 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800822 }
823
Felipe Leme4c2d6632016-09-28 14:32:00 -0700824 if (IsDryRun() && !options.Always()) {
825 if (!title.empty()) {
826 printf("\t(skipped on dry run)\n");
827 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700828 UpdateProgress(options.Timeout());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700829 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700830 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800831
Felipe Leme30dbfa12016-09-02 12:43:26 -0700832 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700833
Felipe Leme30dbfa12016-09-02 12:43:26 -0700834 /* TODO: for now we're simplifying the progress calculation by using the
835 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
836 * where its weight should be much higher proportionally to its timeout.
837 * Ideally, it should use a options.EstimatedDuration() instead...*/
838 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800839
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700840 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700841 pid_t pid = fork();
842
843 /* handle error case */
844 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700845 if (!silent) printf("*** fork: %s\n", strerror(errno));
846 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700847 return pid;
848 }
849
850 /* handle child case */
851 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700852 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
853 if (!silent)
854 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700855 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700856 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800857 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700858
Felipe Leme29c39712016-04-01 10:02:00 -0700859 if (silent) {
860 // Redirect stderr to stdout
861 dup2(STDERR_FILENO, STDOUT_FILENO);
862 }
863
John Michelaue7b6cf12013-03-07 15:35:35 -0600864 /* make sure the child dies when dumpstate dies */
865 prctl(PR_SET_PDEATHSIG, SIGKILL);
866
Andres Morales2e671bb2014-08-21 12:38:22 -0700867 /* just ignore SIGPIPE, will go down with parent's */
868 struct sigaction sigact;
869 memset(&sigact, 0, sizeof(sigact));
870 sigact.sa_handler = SIG_IGN;
871 sigaction(SIGPIPE, &sigact, NULL);
872
Felipe Leme6ad9c062016-09-28 11:58:36 -0700873 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700874 // execvp's result will be handled after waitpid_with_timeout() below, but
875 // if it failed, it's safer to exit dumpstate.
876 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700877 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700878 // Must call _exit (instead of exit), otherwise it will corrupt the zip
879 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700880 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700881 }
882
883 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800884 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700885 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700886 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800887 if (!ret) {
888 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700889 if (!silent)
890 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
891 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700892 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -0700893 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800894 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700895 if (!silent)
896 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
897 (float)elapsed / NANOS_PER_SEC, pid);
898 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
899 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800900 }
901 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700902 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800903 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700904 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700905 if (!silent)
906 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
907 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700908 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700909 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700910 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800911 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700912 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800913
914 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700915 if (!silent)
916 printf("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
917 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800918 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700919 status = WEXITSTATUS(status);
920 if (!silent) printf("*** command '%s' failed: exit code %d\n", command, status);
921 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800922 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800923
Felipe Leme71bbfc52015-11-23 14:14:51 -0800924 if (weight > 0) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700925 UpdateProgress(weight);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800926 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800927 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700928}
929
Felipe Leme678727a2016-09-21 17:22:11 -0700930void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
931 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700932 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
933 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme30dbfa12016-09-02 12:43:26 -0700934 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700935 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700936}
937
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800938bool drop_root_user() {
939 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
940 MYLOGD("drop_root_user(): already running as Shell");
941 return true;
942 }
943 /* ensure we will keep capabilities when we drop root */
944 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
945 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
946 return false;
947 }
948
949 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700950 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
951 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800952 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
953 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
954 return false;
955 }
956 if (setgid(AID_SHELL) != 0) {
957 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
958 return false;
959 }
960 if (setuid(AID_SHELL) != 0) {
961 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
962 return false;
963 }
964
965 struct __user_cap_header_struct capheader;
966 struct __user_cap_data_struct capdata[2];
967 memset(&capheader, 0, sizeof(capheader));
968 memset(&capdata, 0, sizeof(capdata));
969 capheader.version = _LINUX_CAPABILITY_VERSION_3;
970 capheader.pid = 0;
971
Wei Liuf87959e2016-08-26 14:51:42 -0700972 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
973 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
974 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
975 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800976 capdata[0].inheritable = 0;
977 capdata[1].inheritable = 0;
978
979 if (capset(&capheader, &capdata[0]) < 0) {
980 MYLOGE("capset failed: %s\n", strerror(errno));
981 return false;
982 }
983
984 return true;
985}
986
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800987void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700988 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
989
990 am.insert(am.end(), args.begin(), args.end());
991
Felipe Leme678727a2016-09-21 17:22:11 -0700992 RunCommand("", am, CommandOptions::WithTimeout(20)
993 .Log("Sending broadcast: '%s'\n")
994 .Always()
995 .DropRoot()
996 .RedirectStderr()
997 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800998}
999
Colin Crossf45fa6b2012-03-26 12:38:26 -07001000size_t num_props = 0;
1001static char* props[2000];
1002
1003static void print_prop(const char *key, const char *name, void *user) {
1004 (void) user;
1005 if (num_props < sizeof(props) / sizeof(props[0])) {
1006 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
1007 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
1008 props[num_props++] = strdup(buf);
1009 }
1010}
1011
1012static int compare_prop(const void *a, const void *b) {
1013 return strcmp(*(char * const *) a, *(char * const *) b);
1014}
1015
1016/* prints all the system properties */
1017void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001018 const char* title = "SYSTEM PROPERTIES";
1019 DurationReporter duration_reporter(title);
1020 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001021 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001022 size_t i;
1023 num_props = 0;
1024 property_list(print_prop, NULL);
1025 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1026
Colin Crossf45fa6b2012-03-26 12:38:26 -07001027 for (i = 0; i < num_props; ++i) {
1028 fputs(props[i], stdout);
1029 free(props[i]);
1030 }
1031 printf("\n");
1032}
1033
Felipe Leme2628e9e2016-04-12 16:36:51 -07001034int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001035 int s = android_get_control_socket(service);
1036 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001037 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001038 exit(1);
1039 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001040 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001041 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001042 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001043 exit(1);
1044 }
1045
1046 struct sockaddr addr;
1047 socklen_t alen = sizeof(addr);
1048 int fd = accept(s, &addr, &alen);
1049 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001050 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001051 exit(1);
1052 }
1053
Felipe Leme2628e9e2016-04-12 16:36:51 -07001054 return fd;
1055}
1056
1057/* redirect output to a service control socket */
1058void redirect_to_socket(FILE *redirect, const char *service) {
1059 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001060 fflush(redirect);
1061 dup2(fd, fileno(redirect));
1062 close(fd);
1063}
1064
Felipe Leme2628e9e2016-04-12 16:36:51 -07001065// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001066void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001067 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001068
1069 /* skip initial slash */
1070 if (chp[0] == '/')
1071 chp++;
1072
1073 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001074 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001075 while (chp && chp[0]) {
1076 chp = strchr(chp, '/');
1077 if (chp) {
1078 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001079 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001080 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001081 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001082 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001083 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001084 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001085 }
1086 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001087 *chp++ = '/';
1088 }
1089 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001090}
1091
Felipe Leme0f3fb202016-06-10 17:10:53 -07001092void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001093 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001094
Felipe Leme0f3fb202016-06-10 17:10:53 -07001095 int fd = TEMP_FAILURE_RETRY(open(path,
1096 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001097 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001098 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001099 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001100 exit(1);
1101 }
1102
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001103 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001104 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001105}
1106
Felipe Leme0f3fb202016-06-10 17:10:53 -07001107void redirect_to_file(FILE *redirect, char *path) {
1108 _redirect_to_file(redirect, path, O_TRUNC);
1109}
1110
1111void redirect_to_existing_file(FILE *redirect, char *path) {
1112 _redirect_to_file(redirect, path, O_APPEND);
1113}
1114
Jeff Brownbf7f4922012-06-07 16:40:01 -07001115static bool should_dump_native_traces(const char* path) {
1116 for (const char** p = native_processes_to_dump; *p; p++) {
1117 if (!strcmp(*p, path)) {
1118 return true;
1119 }
1120 }
1121 return false;
1122}
1123
1124/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1125const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001126 DurationReporter duration_reporter("DUMP TRACES", nullptr);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001127 if (IsDryRun()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001128
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001129 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001130
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001131 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1132 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001133
1134 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001135 std::string anrTracesPath = tracesPath + ".anr";
1136 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1137 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1138 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001139 }
1140
Colin Crossf45fa6b2012-03-26 12:38:26 -07001141 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001142 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1143 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1144 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001145 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001146 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1147 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001148 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001149 int chmod_ret = fchmod(fd, 0666);
1150 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001151 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001152 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001153 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001154 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001155
Felipe Leme8620bb42015-11-10 11:04:45 -08001156 /* Variables below must be initialized before 'goto' statements */
1157 int dalvik_found = 0;
1158 int ifd, wfd = -1;
1159
Colin Crossf45fa6b2012-03-26 12:38:26 -07001160 /* walk /proc and kill -QUIT all Dalvik processes */
1161 DIR *proc = opendir("/proc");
1162 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001163 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001164 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001165 }
1166
1167 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001168 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001170 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001171 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001172 }
1173
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001174 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001175 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001176 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001177 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001178 }
1179
1180 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001181 while ((d = readdir(proc))) {
1182 int pid = atoi(d->d_name);
1183 if (pid <= 0) continue;
1184
Jeff Brownbf7f4922012-06-07 16:40:01 -07001185 char path[PATH_MAX];
1186 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001187 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001188 ssize_t len = readlink(path, data, sizeof(data) - 1);
1189 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001190 continue;
1191 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001192 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001193
Colin Cross0d6180f2014-07-16 19:00:46 -07001194 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001195 /* skip zygote -- it won't dump its stack anyway */
1196 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001197 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001198 len = read(cfd, data, sizeof(data) - 1);
1199 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001200 if (len <= 0) {
1201 continue;
1202 }
1203 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001204 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001205 continue;
1206 }
1207
1208 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001209 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001210 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001211 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001212 continue;
1213 }
1214
1215 /* wait for the writable-close notification from inotify */
1216 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001217 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001218 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001219 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001220 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001221 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001222 } else {
1223 struct inotify_event ie;
1224 read(ifd, &ie, sizeof(ie));
1225 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001226
1227 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001228 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001229 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001230 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1231 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001232 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001233 } else if (should_dump_native_traces(data)) {
1234 /* dump native process if appropriate */
1235 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001236 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001237 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001238 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001239 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001240
1241 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1242 if (timeout_failures == 3) {
1243 dprintf(fd, "too many stack dump failures, skipping...\n");
1244 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1245 dprintf(fd, "dumping failed, likely due to a timeout\n");
1246 timeout_failures++;
1247 } else {
1248 timeout_failures = 0;
1249 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001250 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1251 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001252 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001253 }
1254 }
1255
Colin Crossf45fa6b2012-03-26 12:38:26 -07001256 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001257 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001258 }
1259
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001260 static std::string dumpTracesPath = tracesPath + ".bugreport";
1261 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1262 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001263 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001264 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001265 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001266
1267 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001268 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001269
1270error_close_ifd:
1271 close(ifd);
1272error_close_fd:
1273 close(fd);
1274 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001275}
1276
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001277void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001278 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001279 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001280 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001281 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001282 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001283 if (!fp) {
1284 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1285 return;
1286 }
1287 char table[16];
1288 // Each line has an integer (the table number), a space, and a string (the table name). We only
1289 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1290 // Add a fixed max limit so this doesn't go awry.
1291 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001292 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1293 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001294 }
1295 fclose(fp);
1296}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001297
Felipe Leme71bbfc52015-11-23 14:14:51 -08001298// TODO: make this function thread safe if sections are generated in parallel.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001299void Dumpstate::UpdateProgress(int delta) {
1300 if (!updateProgress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001301
Felipe Lemed80e6b62016-10-03 13:08:14 -07001302 progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001303
1304 char key[PROPERTY_KEY_MAX];
1305 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001306
1307 // adjusts max on the fly
Felipe Lemed80e6b62016-10-03 13:08:14 -07001308 if (progress_ > weightTotal_) {
1309 int newTotal = weightTotal_ * 1.2;
1310 MYLOGD("Adjusting total weight from %d to %d\n", weightTotal_, newTotal);
1311 weightTotal_ = newTotal;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001312 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001313 snprintf(value, sizeof(value), "%d", weightTotal_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001314 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001315 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001316 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001317 key, value, status);
1318 }
1319 }
1320
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001321 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001322 snprintf(value, sizeof(value), "%d", progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001323
Felipe Lemed80e6b62016-10-03 13:08:14 -07001324 if (progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001325 // We don't want to spam logcat, so only log multiples of 100.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001326 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001327 } else {
1328 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1329 // directly for debuggging.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001330 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001331 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001332
Felipe Lemed80e6b62016-10-03 13:08:14 -07001333 if (controlSocketFd_ >= 0) {
1334 dprintf(controlSocketFd_, "PROGRESS:%d/%d\n", progress_, weightTotal_);
1335 fsync(controlSocketFd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001336 }
1337
Felipe Leme71bbfc52015-11-23 14:14:51 -08001338 int status = property_set(key, value);
1339 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001340 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001341 key, value, status);
1342 }
1343}
Felipe Lemee338bf62015-12-07 14:03:50 -08001344
Felipe Leme3634a1e2015-12-09 10:11:47 -08001345void take_screenshot(const std::string& path) {
Felipe Leme678727a2016-09-21 17:22:11 -07001346 RunCommand("", {"/system/bin/screencap", "-p", path},
Felipe Leme30dbfa12016-09-02 12:43:26 -07001347 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001348}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001349
Felipe Leme0c80cf02016-01-05 13:25:34 -08001350void vibrate(FILE* vibrator, int ms) {
1351 fprintf(vibrator, "%d\n", ms);
1352 fflush(vibrator);
1353}
1354
1355bool is_dir(const char* pathname) {
1356 struct stat info;
1357 if (stat(pathname, &info) == -1) {
1358 return false;
1359 }
1360 return S_ISDIR(info.st_mode);
1361}
1362
1363time_t get_mtime(int fd, time_t default_mtime) {
1364 struct stat info;
1365 if (fstat(fd, &info) == -1) {
1366 return default_mtime;
1367 }
1368 return info.st_mtime;
1369}
1370
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001371void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001372 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001373 struct hex {
1374 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001375 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001376 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1377 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1378 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1379 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1380
1381 std::string buffer;
1382 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1383 return;
1384 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001385
1386 printf("------ %s Extended CSD ------\n", ext_csd_path);
1387
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001388 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1389 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001390 return;
1391 }
1392
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001393 int ext_csd_rev = 0;
1394 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1395 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1396 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1397 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001398 return;
1399 }
1400
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001401 static const char *ver_str[] = {
1402 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1403 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001404 printf("rev 1.%d (MMC %s)\n",
1405 ext_csd_rev,
1406 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1407 ver_str[ext_csd_rev] :
1408 "Unknown");
1409 if (ext_csd_rev < 7) {
1410 printf("\n");
1411 return;
1412 }
1413
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001414 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1415 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001416 return;
1417 }
1418
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001419 int ext_pre_eol_info = 0;
1420 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1421 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1422 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1423 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001424 return;
1425 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001426
1427 static const char *eol_str[] = {
1428 "Undefined",
1429 "Normal",
1430 "Warning (consumed 80% of reserve)",
1431 "Urgent (consumed 90% of reserve)"
1432 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001433 printf("PRE_EOL_INFO %d (MMC %s)\n",
1434 ext_pre_eol_info,
1435 eol_str[(ext_pre_eol_info < (int)
1436 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1437 ext_pre_eol_info : 0]);
1438
1439 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1440 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001441 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001442 int ext_device_life_time_est;
1443 static const char *est_str[] = {
1444 "Undefined",
1445 "0-10% of device lifetime used",
1446 "10-20% of device lifetime used",
1447 "20-30% of device lifetime used",
1448 "30-40% of device lifetime used",
1449 "40-50% of device lifetime used",
1450 "50-60% of device lifetime used",
1451 "60-70% of device lifetime used",
1452 "70-80% of device lifetime used",
1453 "80-90% of device lifetime used",
1454 "90-100% of device lifetime used",
1455 "Exceeded the maximum estimated device lifetime",
1456 };
1457
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001458 if (buffer.length() < (lifetime + sizeof(hex))) {
1459 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001460 break;
1461 }
1462
1463 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001464 sub = buffer.substr(lifetime, sizeof(hex));
1465 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1466 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001467 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001468 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1469 sizeof(hex)) + 'A',
1470 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001471 continue;
1472 }
1473 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001474 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1475 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001476 ext_device_life_time_est,
1477 est_str[(ext_device_life_time_est < (int)
1478 (sizeof(est_str) / sizeof(est_str[0]))) ?
1479 ext_device_life_time_est : 0]);
1480 }
1481
1482 printf("\n");
1483}