blob: 31c86978896836fa9893e06a32abc25ba8a810cf [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>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070043#include <android-base/stringprintf.h>
Jeff Brownbf7f4922012-06-07 16:40:01 -070044#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080045#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070046#include <cutils/properties.h>
47#include <cutils/sockets.h>
48#include <private/android_filesystem_config.h>
49
Robert Craig95798372013-04-04 06:33:10 -040050#include <selinux/android.h>
51
Colin Crossf45fa6b2012-03-26 12:38:26 -070052#include "dumpstate.h"
53
Felipe Lemefd8affa2016-09-30 17:38:57 -070054#define SU_PATH "/system/xbin/su"
55
Jeff Brown1dc94e32014-09-11 14:15:27 -070056static const int64_t NANOS_PER_SEC = 1000000000;
57
Felipe Leme61884122016-06-13 09:23:30 -070058static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
59
Felipe Lemee844a9d2016-09-21 15:01:39 -070060// TODO: temporary variables and functions used during C++ refactoring
61static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070062static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070063 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070064 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070065}
Felipe Leme4c2d6632016-09-28 14:32:00 -070066static bool IsDryRun() {
67 return Dumpstate::GetInstance().IsDryRun();
68}
Felipe Lemed80e6b62016-10-03 13:08:14 -070069static void UpdateProgress(int delta) {
70 ds.UpdateProgress(delta);
71}
Felipe Lemee844a9d2016-09-21 15:01:39 -070072
Jeff Brownbf7f4922012-06-07 16:40:01 -070073/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070074// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070075static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080076 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080077 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070078 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070079 "/system/bin/mediacodec", // media.codec
80 "/system/bin/mediadrmserver",
81 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070082 "/system/bin/mediaserver",
83 "/system/bin/sdcard",
84 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070085 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070086 NULL,
87};
88
Felipe Lemee844a9d2016-09-21 15:01:39 -070089/* Most simple commands have 10 as timeout, so 5 is a good estimate */
90static const int WEIGHT_FILE = 5;
91
Felipe Leme30dbfa12016-09-02 12:43:26 -070092CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
93CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
94CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
95CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
96CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
97
Felipe Leme9a523ae2016-10-20 15:10:33 -070098CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -070099}
100
101CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700102 values.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700103 return *this;
104}
105
106CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700107 values.root_mode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700108 return *this;
109}
110
111CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700112 values.root_mode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700113 return *this;
114}
115
116CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700117 values.stdout_mode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700118 return *this;
119}
120
121CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
122 const std::string& message) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700123 values.logging_message_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700124 return *this;
125}
126
127CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700128 return CommandOptions(values);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700129}
130
131CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700132 : timeout_(timeout),
133 always_(false),
Felipe Leme9a523ae2016-10-20 15:10:33 -0700134 root_mode_(DONT_DROP_ROOT),
135 stdout_mode_(NORMAL_STDOUT),
136 logging_message_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700137}
138
Felipe Leme9a523ae2016-10-20 15:10:33 -0700139CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700140}
141
142long CommandOptions::Timeout() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700143 return values.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700144}
145
146bool CommandOptions::Always() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700147 return values.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700148}
149
150RootMode CommandOptions::RootMode() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700151 return values.root_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700152}
153
154StdoutMode CommandOptions::StdoutMode() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700155 return values.stdout_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700156}
157
158std::string CommandOptions::LoggingMessage() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700159 return values.logging_message_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700160}
161
162CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
163 return CommandOptions::CommandOptionsBuilder(timeout);
164}
165
Felipe Lemed071c682016-10-20 16:48:00 -0700166Dumpstate::Dumpstate(const std::string& version, bool dry_run, const std::string& build_type)
167 : version_(version), now_(time(nullptr)), dry_run_(dry_run), build_type_(build_type) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700168}
169
170Dumpstate& Dumpstate::GetInstance() {
Felipe Lemed071c682016-10-20 16:48:00 -0700171 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT),
172 android::base::GetBoolProperty("dumpstate.dry_run", false),
Felipe Lemed80e6b62016-10-03 13:08:14 -0700173 android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700174 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700175}
176
Felipe Leme678727a2016-09-21 17:22:11 -0700177DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
178}
Felipe Leme608385d2016-02-01 10:35:38 -0800179
Felipe Leme678727a2016-09-21 17:22:11 -0700180DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
181 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700182 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800183 }
184}
185
186DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700187 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700188 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800189 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700190 if (out_ != nullptr) {
191 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700192 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800193 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700194 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800195 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800196 }
197}
198
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700199uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800200 struct timespec ts;
201 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800202 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800203}
204
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700205bool Dumpstate::IsDryRun() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700206 return dry_run_;
Felipe Leme4c2d6632016-09-28 14:32:00 -0700207}
208
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700209bool Dumpstate::IsUserBuild() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700210 return "user" == build_type_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700211}
212
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700213std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700214 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700215 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700216}
217
John Spurlock5ecd4be2014-01-29 14:14:40 -0500218void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700219 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700220
John Spurlock5ecd4be2014-01-29 14:14:40 -0500221 DIR *d;
222 struct dirent *de;
223
224 if (header) printf("\n------ %s ------\n", header);
225 func(0);
226
227 if (!(d = opendir("/data/system/users"))) {
228 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
229 return;
230 }
231
232 while ((de = readdir(d))) {
233 int userid;
234 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
235 continue;
236 }
237 func(userid);
238 }
239
240 closedir(d);
241}
242
Colin Cross0c22e8b2012-11-02 15:46:56 -0700243static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700244 DIR *d;
245 struct dirent *de;
246
247 if (!(d = opendir("/proc"))) {
248 printf("Failed to open /proc (%s)\n", strerror(errno));
249 return;
250 }
251
Felipe Leme635ca312016-01-05 14:23:02 -0800252 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700253 while ((de = readdir(d))) {
254 int pid;
255 int fd;
256 char cmdpath[255];
257 char cmdline[255];
258
259 if (!(pid = atoi(de->d_name))) {
260 continue;
261 }
262
Colin Crossf45fa6b2012-03-26 12:38:26 -0700263 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800264
265 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
266 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
267 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700268 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800269 if (cmdline[0]) {
270 helper(pid, cmdline, arg);
271 continue;
272 }
273 }
274
275 // if no cmdline, a kernel thread has comm
276 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
277 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
278 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
279 close(fd);
280 if (cmdline[1]) {
281 cmdline[0] = '[';
282 size_t len = strcspn(cmdline, "\f\b\r\n");
283 cmdline[len] = ']';
284 cmdline[len+1] = '\0';
285 }
286 }
287 if (!cmdline[0]) {
288 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700289 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700290 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700291 }
292
293 closedir(d);
294}
295
Colin Cross0c22e8b2012-11-02 15:46:56 -0700296static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800297 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700298 func(pid, cmdline);
299}
300
301void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700302 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700303
Felipe Leme515eb0d2015-12-14 15:09:56 -0800304 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700305}
306
307static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
308 DIR *d;
309 struct dirent *de;
310 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800311 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700312
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700313 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700314
315 if (!(d = opendir(taskpath))) {
316 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
317 return;
318 }
319
320 func(pid, pid, cmdline);
321
322 while ((de = readdir(d))) {
323 int tid;
324 int fd;
325 char commpath[255];
326 char comm[255];
327
328 if (!(tid = atoi(de->d_name))) {
329 continue;
330 }
331
332 if (tid == pid)
333 continue;
334
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700335 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800336 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700337 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700338 strcpy(comm, "N/A");
339 } else {
340 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800341 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700342 close(fd);
343
344 c = strrchr(comm, '\n');
345 if (c) {
346 *c = '\0';
347 }
348 }
349 func(pid, tid, comm);
350 }
351
352 closedir(d);
353}
354
355void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700356 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700357
Felipe Leme8620bb42015-11-10 11:04:45 -0800358 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700359}
360
361void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700362 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700363
Colin Crossf45fa6b2012-03-26 12:38:26 -0700364 char path[255];
365 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800366 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700367 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700368
369 memset(buffer, 0, sizeof(buffer));
370
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700371 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700372 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700373 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
374 return;
375 }
376
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800377 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
378 save_errno = errno;
379 close(fd);
380
381 if (ret < 0) {
382 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
383 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700384 }
385
Colin Cross0c22e8b2012-11-02 15:46:56 -0700386 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
387 pid == tid ? 0 : 3, "", name);
388
389 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700390
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800391 return;
392}
393
394// print time in centiseconds
395static void snprcent(char *buffer, size_t len, size_t spc,
396 unsigned long long time) {
397 static long hz; // cache discovered hz
398
399 if (hz <= 0) {
400 hz = sysconf(_SC_CLK_TCK);
401 if (hz <= 0) {
402 hz = 1000;
403 }
404 }
405
406 // convert to centiseconds
407 time = (time * 100 + (hz / 2)) / hz;
408
409 char str[16];
410
411 snprintf(str, sizeof(str), " %llu.%02u",
412 time / 100, (unsigned)(time % 100));
413 size_t offset = strlen(buffer);
414 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
415 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
416}
417
418// print permille as a percent
419static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
420 char str[16];
421
422 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
423 size_t offset = strlen(buffer);
424 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
425 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
426}
427
428void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700429 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700430
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800431 char path[255];
432 char buffer[1023];
433 int fd, ret, save_errno;
434
435 memset(buffer, 0, sizeof(buffer));
436
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700437 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800438 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
439 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
440 return;
441 }
442
443 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
444 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700445 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800446
447 if (ret < 0) {
448 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
449 return;
450 }
451
452 // field 14 is utime
453 // field 15 is stime
454 // field 42 is iotime
455 unsigned long long utime = 0, stime = 0, iotime = 0;
456 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800457 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
458 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
459 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
460 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800461 &utime, &stime, &iotime) != 3) {
462 return;
463 }
464
465 unsigned long long total = utime + stime;
466 if (!total) {
467 return;
468 }
469
470 unsigned permille = (iotime * 1000 + (total / 2)) / total;
471 if (permille > 1000) {
472 permille = 1000;
473 }
474
475 // try to beautify and stabilize columns at <80 characters
476 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
477 if ((name[0] != '[') || utime) {
478 snprcent(buffer, sizeof(buffer), 57, utime);
479 }
480 snprcent(buffer, sizeof(buffer), 65, stime);
481 if ((name[0] != '[') || iotime) {
482 snprcent(buffer, sizeof(buffer), 73, iotime);
483 }
484 if (iotime) {
485 snprdec(buffer, sizeof(buffer), 79, permille);
486 }
487 puts(buffer); // adds a trailing newline
488
Colin Crossf45fa6b2012-03-26 12:38:26 -0700489 return;
490}
491
492void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800493 const char *title = "KERNEL LOG (dmesg)";
494 DurationReporter duration_reporter(title);
495 printf("------ %s ------\n", title);
496
Felipe Leme4c2d6632016-09-28 14:32:00 -0700497 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700498
Elliott Hughes5f87b312012-09-17 11:43:40 -0700499 /* Get size of kernel buffer */
500 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700501 if (size <= 0) {
502 printf("Unexpected klogctl return value: %d\n\n", size);
503 return;
504 }
505 char *buf = (char *) malloc(size + 1);
506 if (buf == NULL) {
507 printf("memory allocation failed\n\n");
508 return;
509 }
510 int retval = klogctl(KLOG_READ_ALL, buf, size);
511 if (retval < 0) {
512 printf("klogctl failure\n\n");
513 free(buf);
514 return;
515 }
516 buf[retval] = '\0';
517 printf("%s\n\n", buf);
518 free(buf);
519 return;
520}
521
522void do_showmap(int pid, const char *name) {
523 char title[255];
524 char arg[255];
525
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700526 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
527 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700528 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700529}
530
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700531// TODO: when converted to a Dumpstate function, it should be const
Felipe Leme678727a2016-09-21 17:22:11 -0700532static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
533 if (!title.empty()) {
534 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800535
Colin Crossf45fa6b2012-03-26 12:38:26 -0700536 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800537 // Only show the modification time of non-device files.
538 size_t path_len = strlen(path);
539 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
540 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
541 (path_len < 3 || memcmp(path, "/d/", 3)) &&
542 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700543 char stamp[80];
544 time_t mtime = st.st_mtime;
545 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
546 printf(": %s", stamp);
547 }
548 printf(") ------\n");
549 }
550
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800551 bool newline = false;
552 fd_set read_set;
553 struct timeval tm;
554 while (1) {
555 FD_ZERO(&read_set);
556 FD_SET(fd, &read_set);
557 /* Timeout if no data is read for 30 seconds. */
558 tm.tv_sec = 30;
559 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700560 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800561 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
562 if (ret == -1) {
563 printf("*** %s: select failed: %s\n", path, strerror(errno));
564 newline = true;
565 break;
566 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700567 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800568 printf("*** %s: Timed out after %.3fs\n", path,
569 (float) elapsed / NANOS_PER_SEC);
570 newline = true;
571 break;
572 } else {
573 char buffer[65536];
574 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
575 if (bytes_read > 0) {
576 fwrite(buffer, bytes_read, 1, stdout);
577 newline = (buffer[bytes_read-1] == '\n');
578 } else {
579 if (bytes_read == -1) {
580 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
581 newline = true;
582 }
583 break;
584 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700585 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700586 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700587 UpdateProgress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700588 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700589
Colin Crossf45fa6b2012-03-26 12:38:26 -0700590 if (!newline) printf("\n");
Felipe Leme678727a2016-09-21 17:22:11 -0700591 if (!title.empty()) printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700592 return 0;
593}
594
Felipe Leme678727a2016-09-21 17:22:11 -0700595int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700596 DurationReporter duration_reporter(title);
Felipe Lemecef02982016-10-03 17:22:22 -0700597 if (IsDryRun()) {
598 if (!title.empty()) {
599 printf("------ %s (%s) ------\n", title.c_str(), path.c_str());
600 printf("\t(skipped on dry run)\n");
601 }
602 UpdateProgress(WEIGHT_FILE);
603 return 0;
604 }
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700605 return JustDumpFile(title, path);
606}
Felipe Lemecef02982016-10-03 17:22:22 -0700607
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700608int Dumpstate::JustDumpFile(const std::string& title, const std::string& path) const {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700609 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800610 if (fd < 0) {
611 int err = errno;
Felipe Lemecef02982016-10-03 17:22:22 -0700612 if (title.empty()) {
613 printf("*** Error dumping %s: %s\n", path.c_str(), strerror(err));
614 } else {
615 printf("*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(), strerror(err));
616 }
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800617 return -1;
618 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700619 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800620}
621
Felipe Leme71a74ac2016-03-17 15:43:25 -0700622int read_file_as_long(const char *path, long int *output) {
623 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
624 if (fd < 0) {
625 int err = errno;
626 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
627 return -1;
628 }
629 char buffer[50];
630 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
631 if (bytes_read == -1) {
632 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
633 return -2;
634 }
635 if (bytes_read == 0) {
636 MYLOGE("File %s is empty\n", path);
637 return -3;
638 }
639 *output = atoi(buffer);
640 return 0;
641}
642
Mark Salyzyn326842f2015-04-30 09:49:41 -0700643/* calls skip to gate calling dump_from_fd recursively
644 * in the specified directory. dump_from_fd defaults to
645 * dump_file_from_fd above when set to NULL. skip defaults
646 * to false when set to NULL. dump_from_fd will always be
647 * called with title NULL.
648 */
Felipe Leme678727a2016-09-21 17:22:11 -0700649int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
650 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800651 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700652 DIR *dirp;
653 struct dirent *d;
654 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800655 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700656 int fd, retval = 0;
657
Felipe Leme678727a2016-09-21 17:22:11 -0700658 if (!title.empty()) {
659 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700660 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700661 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700662
663 if (dir[strlen(dir) - 1] == '/') {
664 ++slash;
665 }
666 dirp = opendir(dir);
667 if (dirp == NULL) {
668 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800669 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700670 return retval;
671 }
672
673 if (!dump_from_fd) {
674 dump_from_fd = dump_file_from_fd;
675 }
676 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
677 if ((d->d_name[0] == '.')
678 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
679 || (d->d_name[1] == '\0'))) {
680 continue;
681 }
682 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
683 (d->d_type == DT_DIR) ? "/" : "");
684 if (!newpath) {
685 retval = -errno;
686 continue;
687 }
688 if (skip && (*skip)(newpath)) {
689 continue;
690 }
691 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700692 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700693 if (ret < 0) {
694 retval = ret;
695 }
696 continue;
697 }
698 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
699 if (fd < 0) {
700 retval = fd;
701 printf("*** %s: %s\n", newpath, strerror(errno));
702 continue;
703 }
704 (*dump_from_fd)(NULL, newpath, fd);
705 }
706 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700707 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700708 printf("\n");
709 }
710 return retval;
711}
712
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800713/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
714 * it's possible to avoid issues where opening the file itself can get
715 * stuck.
716 */
717int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700718 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700719
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800720 int flags = fcntl(fd, F_GETFL);
721 if (flags == -1) {
722 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800723 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800724 return -1;
725 } else if (!(flags & O_NONBLOCK)) {
726 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800727 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800728 return -1;
729 }
730 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700731}
732
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800733bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
734 sigset_t child_mask, old_mask;
735 sigemptyset(&child_mask);
736 sigaddset(&child_mask, SIGCHLD);
737
738 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
739 printf("*** sigprocmask failed: %s\n", strerror(errno));
740 return false;
741 }
742
743 struct timespec ts;
744 ts.tv_sec = timeout_seconds;
745 ts.tv_nsec = 0;
746 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
747 int saved_errno = errno;
748 // Set the signals back the way they were.
749 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
750 printf("*** sigprocmask failed: %s\n", strerror(errno));
751 if (ret == 0) {
752 return false;
753 }
754 }
755 if (ret == -1) {
756 errno = saved_errno;
757 if (errno == EAGAIN) {
758 errno = ETIMEDOUT;
759 } else {
760 printf("*** sigtimedwait failed: %s\n", strerror(errno));
761 }
762 return false;
763 }
764
765 pid_t child_pid = waitpid(pid, status, WNOHANG);
766 if (child_pid != pid) {
767 if (child_pid != -1) {
768 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
769 } else {
770 printf("*** waitpid failed: %s\n", strerror(errno));
771 }
772 return false;
773 }
774 return true;
775}
776
Felipe Leme9a523ae2016-10-20 15:10:33 -0700777int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -0700778 const CommandOptions& options) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700779 if (full_command.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700780 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700781 return -1;
782 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800783
Felipe Leme9a523ae2016-10-20 15:10:33 -0700784 int size = full_command.size() + 1; // null terminated
785 int starting_index = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700786 if (options.RootMode() == SU_ROOT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700787 starting_index = 2; // "su" "root"
788 size += starting_index;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700789 }
790
Felipe Leme6ad9c062016-09-28 11:58:36 -0700791 std::vector<const char*> args;
792 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700793
Felipe Leme9a523ae2016-10-20 15:10:33 -0700794 std::string command_string;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700795 if (options.RootMode() == SU_ROOT) {
796 args[0] = SU_PATH;
Felipe Leme9a523ae2016-10-20 15:10:33 -0700797 command_string += SU_PATH;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700798 args[1] = "root";
Felipe Leme9a523ae2016-10-20 15:10:33 -0700799 command_string += " root ";
Felipe Leme30dbfa12016-09-02 12:43:26 -0700800 }
Felipe Leme9a523ae2016-10-20 15:10:33 -0700801 int i = starting_index;
802 for (auto arg = full_command.begin(); arg != full_command.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700803 args[i++] = arg->c_str();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700804 command_string += arg->c_str();
805 if (arg != full_command.end() - 1) {
806 command_string += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800807 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800808 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700809 args[i] = nullptr;
810 const char* path = args[0];
Felipe Leme9a523ae2016-10-20 15:10:33 -0700811 const char* command = command_string.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700812
Felipe Leme6ad9c062016-09-28 11:58:36 -0700813 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
814 printf("Skipping '%s' on user build.\n", command);
815 return 0;
816 }
817
Felipe Leme678727a2016-09-21 17:22:11 -0700818 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700819 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700820 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700821
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800822 fflush(stdout);
Felipe Leme9a523ae2016-10-20 15:10:33 -0700823 DurationReporter duration_reporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700824
Felipe Leme9a523ae2016-10-20 15:10:33 -0700825 const std::string& logging_message = options.LoggingMessage();
826 if (!logging_message.empty()) {
827 MYLOGI(logging_message.c_str(), command_string.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800828 }
829
Felipe Leme4c2d6632016-09-28 14:32:00 -0700830 if (IsDryRun() && !options.Always()) {
831 if (!title.empty()) {
832 printf("\t(skipped on dry run)\n");
833 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700834 UpdateProgress(options.Timeout());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700835 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700836 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800837
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700838 int status = JustRunCommand(command, path, args, options);
Felipe Lemeea160d12016-03-24 11:29:44 -0700839
Felipe Leme30dbfa12016-09-02 12:43:26 -0700840 /* TODO: for now we're simplifying the progress calculation by using the
841 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
842 * where its weight should be much higher proportionally to its timeout.
843 * Ideally, it should use a options.EstimatedDuration() instead...*/
844 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800845
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700846 if (weight > 0) {
847 UpdateProgress(weight);
848 }
849
850 return status;
851}
852
853int Dumpstate::JustRunCommand(const char* command, const char* path, std::vector<const char*>& args,
854 const CommandOptions& options) const {
855 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
856
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700857 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700858 pid_t pid = fork();
859
860 /* handle error case */
861 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700862 if (!silent) printf("*** fork: %s\n", strerror(errno));
863 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700864 return pid;
865 }
866
867 /* handle child case */
868 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700869 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
870 if (!silent)
871 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700872 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700873 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800874 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700875
Felipe Leme29c39712016-04-01 10:02:00 -0700876 if (silent) {
877 // Redirect stderr to stdout
878 dup2(STDERR_FILENO, STDOUT_FILENO);
879 }
880
John Michelaue7b6cf12013-03-07 15:35:35 -0600881 /* make sure the child dies when dumpstate dies */
882 prctl(PR_SET_PDEATHSIG, SIGKILL);
883
Andres Morales2e671bb2014-08-21 12:38:22 -0700884 /* just ignore SIGPIPE, will go down with parent's */
885 struct sigaction sigact;
886 memset(&sigact, 0, sizeof(sigact));
887 sigact.sa_handler = SIG_IGN;
888 sigaction(SIGPIPE, &sigact, NULL);
889
Felipe Leme6ad9c062016-09-28 11:58:36 -0700890 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700891 // execvp's result will be handled after waitpid_with_timeout() below, but
892 // if it failed, it's safer to exit dumpstate.
893 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700894 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700895 // Must call _exit (instead of exit), otherwise it will corrupt the zip
896 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700897 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700898 }
899
900 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800901 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700902 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700903 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800904 if (!ret) {
905 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700906 if (!silent)
907 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
908 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700909 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -0700910 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800911 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700912 if (!silent)
913 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
914 (float)elapsed / NANOS_PER_SEC, pid);
915 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
916 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800917 }
918 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700919 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800920 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700921 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700922 if (!silent)
923 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
924 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700925 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700926 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700927 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800928 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700929 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800930
931 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700932 if (!silent)
933 printf("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
934 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800935 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700936 status = WEXITSTATUS(status);
937 if (!silent) printf("*** command '%s' failed: exit code %d\n", command, status);
938 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800939 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800940
941 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700942}
943
Felipe Leme9a523ae2016-10-20 15:10:33 -0700944void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700945 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700946 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
947 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700948 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700949 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700950}
951
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800952bool drop_root_user() {
953 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
Felipe Leme26c41572016-10-06 14:34:43 -0700954 MYLOGD("drop_root_user(): already running as Shell\n");
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800955 return true;
956 }
957 /* ensure we will keep capabilities when we drop root */
958 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
959 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
960 return false;
961 }
962
963 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700964 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
965 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800966 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
967 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
968 return false;
969 }
970 if (setgid(AID_SHELL) != 0) {
971 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
972 return false;
973 }
974 if (setuid(AID_SHELL) != 0) {
975 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
976 return false;
977 }
978
979 struct __user_cap_header_struct capheader;
980 struct __user_cap_data_struct capdata[2];
981 memset(&capheader, 0, sizeof(capheader));
982 memset(&capdata, 0, sizeof(capdata));
983 capheader.version = _LINUX_CAPABILITY_VERSION_3;
984 capheader.pid = 0;
985
Wei Liuf87959e2016-08-26 14:51:42 -0700986 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
987 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
988 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
989 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800990 capdata[0].inheritable = 0;
991 capdata[1].inheritable = 0;
992
993 if (capset(&capheader, &capdata[0]) < 0) {
994 MYLOGE("capset failed: %s\n", strerror(errno));
995 return false;
996 }
997
998 return true;
999}
1000
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001001void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001002 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
1003
1004 am.insert(am.end(), args.begin(), args.end());
1005
Felipe Leme678727a2016-09-21 17:22:11 -07001006 RunCommand("", am, CommandOptions::WithTimeout(20)
1007 .Log("Sending broadcast: '%s'\n")
1008 .Always()
1009 .DropRoot()
1010 .RedirectStderr()
1011 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001012}
1013
Colin Crossf45fa6b2012-03-26 12:38:26 -07001014size_t num_props = 0;
1015static char* props[2000];
1016
1017static void print_prop(const char *key, const char *name, void *user) {
1018 (void) user;
1019 if (num_props < sizeof(props) / sizeof(props[0])) {
1020 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
1021 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
1022 props[num_props++] = strdup(buf);
1023 }
1024}
1025
1026static int compare_prop(const void *a, const void *b) {
1027 return strcmp(*(char * const *) a, *(char * const *) b);
1028}
1029
1030/* prints all the system properties */
1031void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001032 const char* title = "SYSTEM PROPERTIES";
1033 DurationReporter duration_reporter(title);
1034 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001035 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001036 size_t i;
1037 num_props = 0;
1038 property_list(print_prop, NULL);
1039 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1040
Colin Crossf45fa6b2012-03-26 12:38:26 -07001041 for (i = 0; i < num_props; ++i) {
1042 fputs(props[i], stdout);
1043 free(props[i]);
1044 }
1045 printf("\n");
1046}
1047
Felipe Leme2628e9e2016-04-12 16:36:51 -07001048int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001049 int s = android_get_control_socket(service);
1050 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001051 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001052 exit(1);
1053 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001054 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001055 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001056 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001057 exit(1);
1058 }
1059
1060 struct sockaddr addr;
1061 socklen_t alen = sizeof(addr);
1062 int fd = accept(s, &addr, &alen);
1063 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001064 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001065 exit(1);
1066 }
1067
Felipe Leme2628e9e2016-04-12 16:36:51 -07001068 return fd;
1069}
1070
1071/* redirect output to a service control socket */
1072void redirect_to_socket(FILE *redirect, const char *service) {
1073 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001074 fflush(redirect);
1075 dup2(fd, fileno(redirect));
1076 close(fd);
1077}
1078
Felipe Leme2628e9e2016-04-12 16:36:51 -07001079// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001080void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001081 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001082
1083 /* skip initial slash */
1084 if (chp[0] == '/')
1085 chp++;
1086
1087 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001088 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001089 while (chp && chp[0]) {
1090 chp = strchr(chp, '/');
1091 if (chp) {
1092 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001093 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001094 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001095 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001096 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001097 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001098 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001099 }
1100 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001101 *chp++ = '/';
1102 }
1103 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001104}
1105
Felipe Leme0f3fb202016-06-10 17:10:53 -07001106void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001107 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001108
Felipe Leme0f3fb202016-06-10 17:10:53 -07001109 int fd = TEMP_FAILURE_RETRY(open(path,
1110 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001111 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001112 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001113 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001114 exit(1);
1115 }
1116
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001117 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001118 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001119}
1120
Felipe Leme0f3fb202016-06-10 17:10:53 -07001121void redirect_to_file(FILE *redirect, char *path) {
1122 _redirect_to_file(redirect, path, O_TRUNC);
1123}
1124
1125void redirect_to_existing_file(FILE *redirect, char *path) {
1126 _redirect_to_file(redirect, path, O_APPEND);
1127}
1128
Jeff Brownbf7f4922012-06-07 16:40:01 -07001129static bool should_dump_native_traces(const char* path) {
1130 for (const char** p = native_processes_to_dump; *p; p++) {
1131 if (!strcmp(*p, path)) {
1132 return true;
1133 }
1134 }
1135 return false;
1136}
1137
1138/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1139const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001140 DurationReporter duration_reporter("DUMP TRACES", nullptr);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001141 if (IsDryRun()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001142
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001143 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001144
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001145 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1146 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001147
1148 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001149 std::string anrTracesPath = tracesPath + ".anr";
1150 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1151 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1152 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001153 }
1154
Colin Crossf45fa6b2012-03-26 12:38:26 -07001155 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001156 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1157 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1158 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001159 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001160 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1161 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001162 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001163 int chmod_ret = fchmod(fd, 0666);
1164 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001165 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001166 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001167 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001168 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169
Felipe Leme8620bb42015-11-10 11:04:45 -08001170 /* Variables below must be initialized before 'goto' statements */
1171 int dalvik_found = 0;
1172 int ifd, wfd = -1;
1173
Colin Crossf45fa6b2012-03-26 12:38:26 -07001174 /* walk /proc and kill -QUIT all Dalvik processes */
1175 DIR *proc = opendir("/proc");
1176 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001177 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001178 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001179 }
1180
1181 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001182 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001183 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001184 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001185 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001186 }
1187
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001188 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001189 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001190 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001191 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001192 }
1193
1194 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001195 while ((d = readdir(proc))) {
1196 int pid = atoi(d->d_name);
1197 if (pid <= 0) continue;
1198
Jeff Brownbf7f4922012-06-07 16:40:01 -07001199 char path[PATH_MAX];
1200 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001201 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001202 ssize_t len = readlink(path, data, sizeof(data) - 1);
1203 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001204 continue;
1205 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001206 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001207
Colin Cross0d6180f2014-07-16 19:00:46 -07001208 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001209 /* skip zygote -- it won't dump its stack anyway */
1210 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001211 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001212 len = read(cfd, data, sizeof(data) - 1);
1213 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001214 if (len <= 0) {
1215 continue;
1216 }
1217 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001218 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001219 continue;
1220 }
1221
1222 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001223 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001224 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001225 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001226 continue;
1227 }
1228
1229 /* wait for the writable-close notification from inotify */
1230 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001231 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001232 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001233 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001234 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001235 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001236 } else {
1237 struct inotify_event ie;
1238 read(ifd, &ie, sizeof(ie));
1239 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001240
1241 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001242 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001243 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001244 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1245 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001246 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001247 } else if (should_dump_native_traces(data)) {
1248 /* dump native process if appropriate */
1249 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001250 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001251 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001252 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001253 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001254
1255 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1256 if (timeout_failures == 3) {
1257 dprintf(fd, "too many stack dump failures, skipping...\n");
1258 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1259 dprintf(fd, "dumping failed, likely due to a timeout\n");
1260 timeout_failures++;
1261 } else {
1262 timeout_failures = 0;
1263 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001264 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1265 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001266 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001267 }
1268 }
1269
Colin Crossf45fa6b2012-03-26 12:38:26 -07001270 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001271 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001272 }
1273
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001274 static std::string dumpTracesPath = tracesPath + ".bugreport";
1275 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1276 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001277 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001278 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001279 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001280
1281 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001282 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001283
1284error_close_ifd:
1285 close(ifd);
1286error_close_fd:
1287 close(fd);
1288 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001289}
1290
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001291void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001292 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001293 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001294 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001295 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001296 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001297 if (!fp) {
1298 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1299 return;
1300 }
1301 char table[16];
1302 // Each line has an integer (the table number), a space, and a string (the table name). We only
1303 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1304 // Add a fixed max limit so this doesn't go awry.
1305 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001306 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1307 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001308 }
1309 fclose(fp);
1310}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001311
Felipe Leme71bbfc52015-11-23 14:14:51 -08001312// TODO: make this function thread safe if sections are generated in parallel.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001313void Dumpstate::UpdateProgress(int delta) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001314 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001315
Felipe Lemed80e6b62016-10-03 13:08:14 -07001316 progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001317
1318 char key[PROPERTY_KEY_MAX];
1319 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001320
1321 // adjusts max on the fly
Felipe Leme9a523ae2016-10-20 15:10:33 -07001322 if (progress_ > weight_total_) {
1323 int new_total = weight_total_ * 1.2;
1324 MYLOGD("Adjusting total weight from %d to %d\n", weight_total_, new_total);
1325 weight_total_ = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001326 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Leme9a523ae2016-10-20 15:10:33 -07001327 snprintf(value, sizeof(value), "%d", weight_total_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001328 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001329 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001330 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001331 key, value, status);
1332 }
1333 }
1334
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001335 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001336 snprintf(value, sizeof(value), "%d", progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001337
Felipe Lemed80e6b62016-10-03 13:08:14 -07001338 if (progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001339 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme9a523ae2016-10-20 15:10:33 -07001340 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001341 } else {
1342 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1343 // directly for debuggging.
Felipe Leme9a523ae2016-10-20 15:10:33 -07001344 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001345 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001346
Felipe Leme9a523ae2016-10-20 15:10:33 -07001347 if (control_socket_fd_ >= 0) {
1348 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress_, weight_total_);
1349 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001350 }
1351
Felipe Leme71bbfc52015-11-23 14:14:51 -08001352 int status = property_set(key, value);
1353 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001354 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001355 key, value, status);
1356 }
1357}
Felipe Lemee338bf62015-12-07 14:03:50 -08001358
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001359void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001360 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001361 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001362 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001363 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1364 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001365 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001366 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001367 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001368 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001369}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001370
Felipe Leme0c80cf02016-01-05 13:25:34 -08001371void vibrate(FILE* vibrator, int ms) {
1372 fprintf(vibrator, "%d\n", ms);
1373 fflush(vibrator);
1374}
1375
1376bool is_dir(const char* pathname) {
1377 struct stat info;
1378 if (stat(pathname, &info) == -1) {
1379 return false;
1380 }
1381 return S_ISDIR(info.st_mode);
1382}
1383
1384time_t get_mtime(int fd, time_t default_mtime) {
1385 struct stat info;
1386 if (fstat(fd, &info) == -1) {
1387 return default_mtime;
1388 }
1389 return info.st_mtime;
1390}
1391
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001392void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001393 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001394 struct hex {
1395 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001396 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001397 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1398 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1399 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1400 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1401
1402 std::string buffer;
1403 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1404 return;
1405 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001406
1407 printf("------ %s Extended CSD ------\n", ext_csd_path);
1408
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001409 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1410 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001411 return;
1412 }
1413
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001414 int ext_csd_rev = 0;
1415 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1416 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1417 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1418 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001419 return;
1420 }
1421
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001422 static const char *ver_str[] = {
1423 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1424 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001425 printf("rev 1.%d (MMC %s)\n",
1426 ext_csd_rev,
1427 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1428 ver_str[ext_csd_rev] :
1429 "Unknown");
1430 if (ext_csd_rev < 7) {
1431 printf("\n");
1432 return;
1433 }
1434
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001435 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1436 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001437 return;
1438 }
1439
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001440 int ext_pre_eol_info = 0;
1441 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1442 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1443 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1444 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001445 return;
1446 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001447
1448 static const char *eol_str[] = {
1449 "Undefined",
1450 "Normal",
1451 "Warning (consumed 80% of reserve)",
1452 "Urgent (consumed 90% of reserve)"
1453 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001454 printf("PRE_EOL_INFO %d (MMC %s)\n",
1455 ext_pre_eol_info,
1456 eol_str[(ext_pre_eol_info < (int)
1457 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1458 ext_pre_eol_info : 0]);
1459
1460 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1461 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001462 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001463 int ext_device_life_time_est;
1464 static const char *est_str[] = {
1465 "Undefined",
1466 "0-10% of device lifetime used",
1467 "10-20% of device lifetime used",
1468 "20-30% of device lifetime used",
1469 "30-40% of device lifetime used",
1470 "40-50% of device lifetime used",
1471 "50-60% of device lifetime used",
1472 "60-70% of device lifetime used",
1473 "70-80% of device lifetime used",
1474 "80-90% of device lifetime used",
1475 "90-100% of device lifetime used",
1476 "Exceeded the maximum estimated device lifetime",
1477 };
1478
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001479 if (buffer.length() < (lifetime + sizeof(hex))) {
1480 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001481 break;
1482 }
1483
1484 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001485 sub = buffer.substr(lifetime, sizeof(hex));
1486 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1487 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001488 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001489 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1490 sizeof(hex)) + 'A',
1491 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001492 continue;
1493 }
1494 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001495 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1496 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001497 ext_device_life_time_est,
1498 est_str[(ext_device_life_time_est < (int)
1499 (sizeof(est_str) / sizeof(est_str[0]))) ?
1500 ext_device_life_time_est : 0]);
1501 }
1502
1503 printf("\n");
1504}