blob: 6cbb6916768c9adb5d67411f664568e5c120a51e [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
Felipe Lemef0292972016-11-22 13:57:05 -080017#define LOG_TAG "dumpstate"
18
19#include "dumpstate.h"
20
Colin Crossf45fa6b2012-03-26 12:38:26 -070021#include <dirent.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070022#include <fcntl.h>
Felipe Lemee184f662016-10-27 10:04:47 -070023#include <libgen.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070024#include <math.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070025#include <poll.h>
26#include <signal.h>
27#include <stdarg.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080031#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/inotify.h>
Felipe Lemee184f662016-10-27 10:04:47 -070033#include <sys/klog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070034#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070035#include <sys/stat.h>
36#include <sys/time.h>
37#include <sys/wait.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038#include <time.h>
39#include <unistd.h>
Mark Salyzyn261a7332016-05-24 12:38:40 -070040
Narayan Kamath8f788292017-05-25 13:20:39 +010041#include <memory>
Steven Moreland17b29e12017-03-21 18:38:05 -070042#include <set>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070043#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080044#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070045
Mark Salyzyn290f4b92016-05-16 08:33:59 -070046#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070047#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070048#include <android-base/stringprintf.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070049#include <android-base/strings.h>
Narayan Kamath8f788292017-05-25 13:20:39 +010050#include <android-base/unique_fd.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070051#include <cutils/properties.h>
52#include <cutils/sockets.h>
Josh Gaod2db0242017-01-05 18:27:33 -080053#include <debuggerd/client.h>
Kweku Adams5ce418d2018-02-05 16:43:53 -080054#include <dumputils/dump_utils.h>
Mark Salyzyn4eb13822017-01-12 13:57:51 -080055#include <log/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070056#include <private/android_filesystem_config.h>
57
Felipe Lemef0292972016-11-22 13:57:05 -080058#include "DumpstateInternal.h"
Jeff Brown1dc94e32014-09-11 14:15:27 -070059
Felipe Leme47e9be22016-12-21 15:37:07 -080060// TODO: remove once moved to namespace
61using android::os::dumpstate::CommandOptions;
62using android::os::dumpstate::DumpFileToFd;
63using android::os::dumpstate::PropertiesHelper;
64
Brian Carlstroma3322752017-03-19 17:48:01 -070065// Keep in sync with
66// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
Felipe Leme61884122016-06-13 09:23:30 -070067static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
68
Felipe Lemef0292972016-11-22 13:57:05 -080069/* Most simple commands have 10 as timeout, so 5 is a good estimate */
70static const int32_t WEIGHT_FILE = 5;
71
Felipe Lemee844a9d2016-09-21 15:01:39 -070072// TODO: temporary variables and functions used during C++ refactoring
73static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070074static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070075 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070076 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070077}
Felipe Lemee844a9d2016-09-21 15:01:39 -070078
Felipe Leme7447d7c2016-11-03 18:12:22 -070079// Reasonable value for max stats.
80static const int STATS_MAX_N_RUNS = 1000;
81static const long STATS_MAX_AVERAGE = 100000;
82
Felipe Lemebda15a02016-11-16 17:48:25 -080083CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -070084
Nandana Dutt197661d2018-11-16 16:40:21 +000085// TODO(111441001): Default DumpOptions to sensible values.
Felipe Lemef0292972016-11-22 13:57:05 -080086Dumpstate::Dumpstate(const std::string& version)
Nandana Dutt197661d2018-11-16 16:40:21 +000087 : pid_(getpid()),
88 options_(new Dumpstate::DumpOptions()),
89 version_(version),
90 now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -070091}
92
93Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -080094 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -070095 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -070096}
97
Felipe Leme46b85da2016-11-21 17:40:45 -080098DurationReporter::DurationReporter(const std::string& title, bool log_only)
99 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700100 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800101 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800102 }
103}
104
105DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700106 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800107 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800108 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700109 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800110 } else {
111 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800112 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
113 title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800114 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800115 }
116}
117
Felipe Leme7447d7c2016-11-03 18:12:22 -0700118const int32_t Progress::kDefaultMax = 5000;
119
120Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
121}
122
123Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
124 : Progress(initial_max, growth_factor, "") {
125 progress_ = progress;
126}
127
128Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
129 : initial_max_(initial_max),
130 progress_(0),
131 max_(initial_max),
132 growth_factor_(growth_factor),
133 n_runs_(0),
134 average_max_(0),
135 path_(path) {
136 if (!path_.empty()) {
137 Load();
138 }
139}
140
141void Progress::Load() {
142 MYLOGD("Loading stats from %s\n", path_.c_str());
143 std::string content;
144 if (!android::base::ReadFileToString(path_, &content)) {
145 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
146 return;
147 }
148 if (content.empty()) {
149 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
150 return;
151 }
152 std::vector<std::string> lines = android::base::Split(content, "\n");
153
154 if (lines.size() < 1) {
155 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
156 (int)lines.size(), max_);
157 return;
158 }
159 char* ptr;
160 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
161 average_max_ = strtol(ptr, nullptr, 10);
162 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
163 average_max_ > STATS_MAX_AVERAGE) {
164 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
165 initial_max_ = Progress::kDefaultMax;
166 } else {
167 initial_max_ = average_max_;
168 }
169 max_ = initial_max_;
170
171 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
172}
173
174void Progress::Save() {
175 int32_t total = n_runs_ * average_max_ + progress_;
176 int32_t runs = n_runs_ + 1;
177 int32_t average = floor(((float)total) / runs);
178 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
179 path_.c_str());
180 if (path_.empty()) {
181 return;
182 }
183
184 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
185 if (!android::base::WriteStringToFile(content, path_)) {
186 MYLOGE("Could not save stats on %s\n", path_.c_str());
187 }
188}
189
190int32_t Progress::Get() const {
191 return progress_;
192}
193
Vishnu Nair6921f802017-11-22 09:17:23 -0800194bool Progress::Inc(int32_t delta_sec) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700195 bool changed = false;
Vishnu Nair6921f802017-11-22 09:17:23 -0800196 if (delta_sec >= 0) {
197 progress_ += delta_sec;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700198 if (progress_ > max_) {
199 int32_t old_max = max_;
200 max_ = floor((float)progress_ * growth_factor_);
201 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
202 changed = true;
203 }
204 }
205 return changed;
206}
207
208int32_t Progress::GetMax() const {
209 return max_;
210}
211
212int32_t Progress::GetInitialMax() const {
213 return initial_max_;
214}
215
216void Progress::Dump(int fd, const std::string& prefix) const {
217 const char* pr = prefix.c_str();
218 dprintf(fd, "%sprogress: %d\n", pr, progress_);
219 dprintf(fd, "%smax: %d\n", pr, max_);
220 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
221 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
222 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
223 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
224 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
225}
226
Felipe Leme75876a22016-10-27 16:31:27 -0700227bool Dumpstate::IsZipping() const {
228 return zip_writer_ != nullptr;
229}
230
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700231std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700232 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700233 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700234}
235
Felipe Leme7447d7c2016-11-03 18:12:22 -0700236void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
237 progress_ = std::move(progress);
238}
239
John Spurlock5ecd4be2014-01-29 14:14:40 -0500240void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800241 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
242 "for_each_userid(%s)", header);
243 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800244 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700245
John Spurlock5ecd4be2014-01-29 14:14:40 -0500246 DIR *d;
247 struct dirent *de;
248
Felipe Lemed8b94e52016-12-08 10:21:44 -0800249 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500250 func(0);
251
252 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800253 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500254 return;
255 }
256
257 while ((de = readdir(d))) {
258 int userid;
259 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
260 continue;
261 }
262 func(userid);
263 }
264
265 closedir(d);
266}
267
Colin Cross0c22e8b2012-11-02 15:46:56 -0700268static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700269 DIR *d;
270 struct dirent *de;
271
272 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800273 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700274 return;
275 }
276
Felipe Lemed8b94e52016-12-08 10:21:44 -0800277 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700278 while ((de = readdir(d))) {
279 int pid;
280 int fd;
281 char cmdpath[255];
282 char cmdline[255];
283
284 if (!(pid = atoi(de->d_name))) {
285 continue;
286 }
287
Colin Crossf45fa6b2012-03-26 12:38:26 -0700288 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800289
290 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
291 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
292 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700293 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800294 if (cmdline[0]) {
295 helper(pid, cmdline, arg);
296 continue;
297 }
298 }
299
300 // if no cmdline, a kernel thread has comm
301 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
302 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
303 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
304 close(fd);
305 if (cmdline[1]) {
306 cmdline[0] = '[';
307 size_t len = strcspn(cmdline, "\f\b\r\n");
308 cmdline[len] = ']';
309 cmdline[len+1] = '\0';
310 }
311 }
312 if (!cmdline[0]) {
313 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700314 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700315 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700316 }
317
318 closedir(d);
319}
320
Colin Cross0c22e8b2012-11-02 15:46:56 -0700321static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800322 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700323 func(pid, cmdline);
324}
325
326void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800327 std::string title = header == nullptr ? "for_each_pid"
328 : android::base::StringPrintf("for_each_pid(%s)", header);
329 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800330 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700331
Felipe Leme515eb0d2015-12-14 15:09:56 -0800332 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700333}
334
335static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
336 DIR *d;
337 struct dirent *de;
338 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800339 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700340
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700341 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700342
343 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800344 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700345 return;
346 }
347
348 func(pid, pid, cmdline);
349
350 while ((de = readdir(d))) {
351 int tid;
352 int fd;
353 char commpath[255];
354 char comm[255];
355
356 if (!(tid = atoi(de->d_name))) {
357 continue;
358 }
359
360 if (tid == pid)
361 continue;
362
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700363 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800364 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700365 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700366 strcpy(comm, "N/A");
367 } else {
368 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800369 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700370 close(fd);
371
372 c = strrchr(comm, '\n');
373 if (c) {
374 *c = '\0';
375 }
376 }
377 func(pid, tid, comm);
378 }
379
380 closedir(d);
381}
382
383void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800384 std::string title = header == nullptr ? "for_each_tid"
385 : android::base::StringPrintf("for_each_tid(%s)", header);
386 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800387
Felipe Lemef0292972016-11-22 13:57:05 -0800388 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700389
Felipe Leme8620bb42015-11-10 11:04:45 -0800390 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700391}
392
393void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800394 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700395
Colin Crossf45fa6b2012-03-26 12:38:26 -0700396 char path[255];
397 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800398 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700399 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700400
401 memset(buffer, 0, sizeof(buffer));
402
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700403 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700404 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800405 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700406 return;
407 }
408
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800409 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
410 save_errno = errno;
411 close(fd);
412
413 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800414 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800415 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700416 }
417
Colin Cross0c22e8b2012-11-02 15:46:56 -0700418 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
419 pid == tid ? 0 : 3, "", name);
420
Felipe Lemed8b94e52016-12-08 10:21:44 -0800421 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700422
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800423 return;
424}
425
426// print time in centiseconds
427static void snprcent(char *buffer, size_t len, size_t spc,
428 unsigned long long time) {
429 static long hz; // cache discovered hz
430
431 if (hz <= 0) {
432 hz = sysconf(_SC_CLK_TCK);
433 if (hz <= 0) {
434 hz = 1000;
435 }
436 }
437
438 // convert to centiseconds
439 time = (time * 100 + (hz / 2)) / hz;
440
441 char str[16];
442
443 snprintf(str, sizeof(str), " %llu.%02u",
444 time / 100, (unsigned)(time % 100));
445 size_t offset = strlen(buffer);
446 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
447 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
448}
449
450// print permille as a percent
451static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
452 char str[16];
453
454 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
455 size_t offset = strlen(buffer);
456 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
457 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
458}
459
460void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800461 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700462
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800463 char path[255];
464 char buffer[1023];
465 int fd, ret, save_errno;
466
467 memset(buffer, 0, sizeof(buffer));
468
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700469 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800470 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800471 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800472 return;
473 }
474
475 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
476 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700477 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800478
479 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800480 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800481 return;
482 }
483
484 // field 14 is utime
485 // field 15 is stime
486 // field 42 is iotime
487 unsigned long long utime = 0, stime = 0, iotime = 0;
488 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800489 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
490 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
491 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
492 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800493 &utime, &stime, &iotime) != 3) {
494 return;
495 }
496
497 unsigned long long total = utime + stime;
498 if (!total) {
499 return;
500 }
501
502 unsigned permille = (iotime * 1000 + (total / 2)) / total;
503 if (permille > 1000) {
504 permille = 1000;
505 }
506
507 // try to beautify and stabilize columns at <80 characters
508 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
509 if ((name[0] != '[') || utime) {
510 snprcent(buffer, sizeof(buffer), 57, utime);
511 }
512 snprcent(buffer, sizeof(buffer), 65, stime);
513 if ((name[0] != '[') || iotime) {
514 snprcent(buffer, sizeof(buffer), 73, iotime);
515 }
516 if (iotime) {
517 snprdec(buffer, sizeof(buffer), 79, permille);
518 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800519 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800520
Colin Crossf45fa6b2012-03-26 12:38:26 -0700521 return;
522}
523
524void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800525 const char *title = "KERNEL LOG (dmesg)";
526 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800527 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800528
Felipe Lemef0292972016-11-22 13:57:05 -0800529 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700530
Elliott Hughes5f87b312012-09-17 11:43:40 -0700531 /* Get size of kernel buffer */
Yi Kong19d5c002018-07-20 13:39:55 -0700532 int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700533 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800534 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700535 return;
536 }
537 char *buf = (char *) malloc(size + 1);
Yi Kong19d5c002018-07-20 13:39:55 -0700538 if (buf == nullptr) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800539 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700540 return;
541 }
542 int retval = klogctl(KLOG_READ_ALL, buf, size);
543 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800544 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700545 free(buf);
546 return;
547 }
548 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800549 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700550 free(buf);
551 return;
552}
553
554void do_showmap(int pid, const char *name) {
555 char title[255];
556 char arg[255];
557
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700558 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
559 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800560 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800561}
562
Felipe Leme678727a2016-09-21 17:22:11 -0700563int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700564 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800565
Felipe Lemef0292972016-11-22 13:57:05 -0800566 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800567
Felipe Lemef0292972016-11-22 13:57:05 -0800568 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800569
Felipe Leme46b85da2016-11-21 17:40:45 -0800570 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800571}
572
Felipe Leme71a74ac2016-03-17 15:43:25 -0700573int read_file_as_long(const char *path, long int *output) {
574 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
575 if (fd < 0) {
576 int err = errno;
577 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
578 return -1;
579 }
580 char buffer[50];
581 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
582 if (bytes_read == -1) {
583 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
584 return -2;
585 }
586 if (bytes_read == 0) {
587 MYLOGE("File %s is empty\n", path);
588 return -3;
589 }
590 *output = atoi(buffer);
591 return 0;
592}
593
Mark Salyzyn326842f2015-04-30 09:49:41 -0700594/* calls skip to gate calling dump_from_fd recursively
595 * in the specified directory. dump_from_fd defaults to
596 * dump_file_from_fd above when set to NULL. skip defaults
597 * to false when set to NULL. dump_from_fd will always be
598 * called with title NULL.
599 */
Felipe Leme678727a2016-09-21 17:22:11 -0700600int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
601 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800602 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700603 DIR *dirp;
604 struct dirent *d;
Yi Kong19d5c002018-07-20 13:39:55 -0700605 char *newpath = nullptr;
Felipe Leme8620bb42015-11-10 11:04:45 -0800606 const char *slash = "/";
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100607 int retval = 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700608
Felipe Leme678727a2016-09-21 17:22:11 -0700609 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800610 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700611 }
Felipe Lemef0292972016-11-22 13:57:05 -0800612 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700613
614 if (dir[strlen(dir) - 1] == '/') {
615 ++slash;
616 }
617 dirp = opendir(dir);
Yi Kong19d5c002018-07-20 13:39:55 -0700618 if (dirp == nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700619 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800620 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700621 return retval;
622 }
623
624 if (!dump_from_fd) {
625 dump_from_fd = dump_file_from_fd;
626 }
Yi Kong19d5c002018-07-20 13:39:55 -0700627 for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700628 if ((d->d_name[0] == '.')
629 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
630 || (d->d_name[1] == '\0'))) {
631 continue;
632 }
633 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
634 (d->d_type == DT_DIR) ? "/" : "");
635 if (!newpath) {
636 retval = -errno;
637 continue;
638 }
639 if (skip && (*skip)(newpath)) {
640 continue;
641 }
642 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700643 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700644 if (ret < 0) {
645 retval = ret;
646 }
647 continue;
648 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100649 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
650 if (fd.get() < 0) {
651 retval = -1;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800652 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700653 continue;
654 }
Yi Kong19d5c002018-07-20 13:39:55 -0700655 (*dump_from_fd)(nullptr, newpath, fd.get());
Mark Salyzyn326842f2015-04-30 09:49:41 -0700656 }
657 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700658 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800659 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700660 }
661 return retval;
662}
663
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800664/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
665 * it's possible to avoid issues where opening the file itself can get
666 * stuck.
667 */
668int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800669 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700670
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800671 int flags = fcntl(fd, F_GETFL);
672 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800673 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800674 return -1;
675 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800676 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800677 return -1;
678 }
Felipe Lemef0292972016-11-22 13:57:05 -0800679 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700680}
681
Felipe Leme46b85da2016-11-21 17:40:45 -0800682int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
683 const CommandOptions& options) {
684 DurationReporter duration_reporter(title);
685
Felipe Lemef0292972016-11-22 13:57:05 -0800686 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800687
Felipe Lemef0292972016-11-22 13:57:05 -0800688 /* TODO: for now we're simplifying the progress calculation by using the
689 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
690 * where its weight should be much higher proportionally to its timeout.
691 * Ideally, it should use a options.EstimatedDuration() instead...*/
692 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800693
Felipe Leme46b85da2016-11-21 17:40:45 -0800694 return status;
695}
696
Felipe Leme9a523ae2016-10-20 15:10:33 -0700697void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Vishnu Nair6921f802017-11-22 09:17:23 -0800698 const CommandOptions& options, long dumpsysTimeoutMs) {
699 long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
700 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700701 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700702 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700703}
704
Felipe Leme2628e9e2016-04-12 16:36:51 -0700705int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700706 int s = android_get_control_socket(service);
707 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800708 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700709 exit(1);
710 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700711 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700712 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800713 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700714 exit(1);
715 }
716
717 struct sockaddr addr;
718 socklen_t alen = sizeof(addr);
719 int fd = accept(s, &addr, &alen);
720 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800721 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700722 exit(1);
723 }
724
Felipe Leme2628e9e2016-04-12 16:36:51 -0700725 return fd;
726}
727
728/* redirect output to a service control socket */
729void redirect_to_socket(FILE *redirect, const char *service) {
730 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700731 fflush(redirect);
732 dup2(fd, fileno(redirect));
733 close(fd);
734}
735
Felipe Leme2628e9e2016-04-12 16:36:51 -0700736// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800737void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800738 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700739
740 /* skip initial slash */
741 if (chp[0] == '/')
742 chp++;
743
744 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800745 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700746 while (chp && chp[0]) {
747 chp = strchr(chp, '/');
748 if (chp) {
749 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800750 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800751 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800752 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800753 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800754 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800755 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800756 }
757 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700758 *chp++ = '/';
759 }
760 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800761}
762
Felipe Leme0f3fb202016-06-10 17:10:53 -0700763void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800764 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700765
Felipe Leme0f3fb202016-06-10 17:10:53 -0700766 int fd = TEMP_FAILURE_RETRY(open(path,
767 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800768 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700769 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800770 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700771 exit(1);
772 }
773
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800774 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700775 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700776}
777
Felipe Leme0f3fb202016-06-10 17:10:53 -0700778void redirect_to_file(FILE *redirect, char *path) {
779 _redirect_to_file(redirect, path, O_TRUNC);
780}
781
782void redirect_to_existing_file(FILE *redirect, char *path) {
783 _redirect_to_file(redirect, path, O_APPEND);
784}
785
Elliott Hughes69fe5ec2018-03-23 11:04:25 -0700786// Dump Dalvik and native stack traces, return the trace file location (nullptr if none).
787const char* dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -0700788 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -0700789
Elliott Hughes69fe5ec2018-03-23 11:04:25 -0700790 const std::string temp_file_pattern = "/data/anr/dumptrace_XXXXXX";
Narayan Kamath8f788292017-05-25 13:20:39 +0100791 const size_t buf_size = temp_file_pattern.length() + 1;
792 std::unique_ptr<char[]> file_name_buf(new char[buf_size]);
793 memcpy(file_name_buf.get(), temp_file_pattern.c_str(), buf_size);
794
795 // Create a new, empty file to receive all trace dumps.
796 //
797 // TODO: This can be simplified once we remove support for the old style
798 // dumps. We can have a file descriptor passed in to dump_traces instead
799 // of creating a file, closing it and then reopening it again.
800 android::base::unique_fd fd(mkostemp(file_name_buf.get(), O_APPEND | O_CLOEXEC));
801 if (fd < 0) {
802 MYLOGE("mkostemp on pattern %s: %s\n", file_name_buf.get(), strerror(errno));
803 return nullptr;
804 }
805
806 // Nobody should have access to this temporary file except dumpstate, but we
807 // temporarily grant 'read' to 'others' here because this file is created
808 // when tombstoned is still running as root, but dumped after dropping. This
809 // can go away once support for old style dumping has.
810 const int chmod_ret = fchmod(fd, 0666);
811 if (chmod_ret < 0) {
812 MYLOGE("fchmod on %s failed: %s\n", file_name_buf.get(), strerror(errno));
813 return nullptr;
814 }
815
816 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
817 if (proc.get() == nullptr) {
818 MYLOGE("opendir /proc failed: %s\n", strerror(errno));
819 return nullptr;
820 }
821
822 // Number of times process dumping has timed out. If we encounter too many
823 // failures, we'll give up.
824 int timeout_failures = 0;
825 bool dalvik_found = false;
826
827 const std::set<int> hal_pids = get_interesting_hal_pids();
828
829 struct dirent* d;
830 while ((d = readdir(proc.get()))) {
831 int pid = atoi(d->d_name);
832 if (pid <= 0) {
833 continue;
834 }
835
836 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
837 std::string exe;
838 if (!android::base::Readlink(link_name, &exe)) {
839 continue;
840 }
841
842 bool is_java_process;
843 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
844 // Don't bother dumping backtraces for the zygote.
845 if (IsZygote(pid)) {
846 continue;
847 }
848
849 dalvik_found = true;
850 is_java_process = true;
851 } else if (should_dump_native_traces(exe.c_str()) || hal_pids.find(pid) != hal_pids.end()) {
852 is_java_process = false;
853 } else {
854 // Probably a native process we don't care about, continue.
855 continue;
856 }
857
858 // If 3 backtrace dumps fail in a row, consider debuggerd dead.
859 if (timeout_failures == 3) {
860 dprintf(fd, "ERROR: Too many stack dump failures, exiting.\n");
861 break;
862 }
863
864 const uint64_t start = Nanotime();
865 const int ret = dump_backtrace_to_file_timeout(
866 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
867 is_java_process ? 5 : 20, fd);
868
869 if (ret == -1) {
870 dprintf(fd, "dumping failed, likely due to a timeout\n");
871 timeout_failures++;
872 continue;
873 }
874
875 // We've successfully dumped stack traces, reset the failure count
876 // and write a summary of the elapsed time to the file and continue with the
877 // next process.
878 timeout_failures = 0;
879
880 dprintf(fd, "[dump %s stack %d: %.3fs elapsed]\n", is_java_process ? "dalvik" : "native",
881 pid, (float)(Nanotime() - start) / NANOS_PER_SEC);
882 }
883
884 if (!dalvik_found) {
885 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
886 }
887
888 return file_name_buf.release();
889}
890
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700891void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800892 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -0800893 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700894 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -0700895 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700896 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700897 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800898 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700899 return;
900 }
901 char table[16];
902 // Each line has an integer (the table number), a space, and a string (the table name). We only
903 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
904 // Add a fixed max limit so this doesn't go awry.
905 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700906 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
907 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700908 }
909 fclose(fp);
910}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800911
Felipe Leme71bbfc52015-11-23 14:14:51 -0800912// TODO: make this function thread safe if sections are generated in parallel.
Vishnu Nair6921f802017-11-22 09:17:23 -0800913void Dumpstate::UpdateProgress(int32_t delta_sec) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700914 if (progress_ == nullptr) {
915 MYLOGE("UpdateProgress: progress_ not set\n");
916 return;
917 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800918
Felipe Leme7447d7c2016-11-03 18:12:22 -0700919 // Always update progess so stats can be tuned...
Vishnu Nair6921f802017-11-22 09:17:23 -0800920 bool max_changed = progress_->Inc(delta_sec);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700921
922 // ...but only notifiy listeners when necessary.
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100923 if (!options_->do_progress_updates) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800924
Felipe Leme009ecbb2016-11-07 10:18:44 -0800925 int progress = progress_->Get();
926 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -0800927
928 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -0800929 if (max_changed && listener_ != nullptr) {
930 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -0800931 }
932
Felipe Leme009ecbb2016-11-07 10:18:44 -0800933 int32_t last_update_delta = progress - last_updated_progress_;
934 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
935 return;
936 }
937 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700938
Felipe Leme9a523ae2016-10-20 15:10:33 -0700939 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700940 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -0700941 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -0700942 }
943
Felipe Leme75876a22016-10-27 16:31:27 -0700944 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700945 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -0700946 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700947 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700948 } else {
949 // stderr is ignored on normal invocations, but useful when calling
950 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700951 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700952 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700953 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800954 }
955}
Felipe Lemee338bf62015-12-07 14:03:50 -0800956
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700957void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700958 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700959 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -0700960 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700961 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
962 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700963 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700964 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700965 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700966 }
Felipe Lemee338bf62015-12-07 14:03:50 -0800967}
Mark Salyzynf55d4022015-12-11 07:32:31 -0800968
Felipe Leme0c80cf02016-01-05 13:25:34 -0800969bool is_dir(const char* pathname) {
970 struct stat info;
971 if (stat(pathname, &info) == -1) {
972 return false;
973 }
974 return S_ISDIR(info.st_mode);
975}
976
977time_t get_mtime(int fd, time_t default_mtime) {
978 struct stat info;
979 if (fstat(fd, &info) == -1) {
980 return default_mtime;
981 }
982 return info.st_mtime;
983}
984
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800985void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700986 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800987 struct hex {
988 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800989 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700990 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
991 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
992 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
993 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
994
995 std::string buffer;
996 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
997 return;
998 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800999
Felipe Lemed8b94e52016-12-08 10:21:44 -08001000 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001001
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001002 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001003 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001004 return;
1005 }
1006
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001007 int ext_csd_rev = 0;
1008 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1009 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001010 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001011 return;
1012 }
1013
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001014 static const char *ver_str[] = {
1015 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1016 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001017 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1018 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1019 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001020 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001021 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001022 return;
1023 }
1024
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001025 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001026 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001027 return;
1028 }
1029
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001030 int ext_pre_eol_info = 0;
1031 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1032 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001033 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001034 return;
1035 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001036
1037 static const char *eol_str[] = {
1038 "Undefined",
1039 "Normal",
1040 "Warning (consumed 80% of reserve)",
1041 "Urgent (consumed 90% of reserve)"
1042 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001043 printf(
1044 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -08001045 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1046 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001047
1048 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1049 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001050 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001051 int ext_device_life_time_est;
1052 static const char *est_str[] = {
1053 "Undefined",
1054 "0-10% of device lifetime used",
1055 "10-20% of device lifetime used",
1056 "20-30% of device lifetime used",
1057 "30-40% of device lifetime used",
1058 "40-50% of device lifetime used",
1059 "50-60% of device lifetime used",
1060 "60-70% of device lifetime used",
1061 "70-80% of device lifetime used",
1062 "80-90% of device lifetime used",
1063 "90-100% of device lifetime used",
1064 "Exceeded the maximum estimated device lifetime",
1065 };
1066
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001067 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001068 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001069 break;
1070 }
1071
1072 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001073 sub = buffer.substr(lifetime, sizeof(hex));
1074 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001075 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1076 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1077 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001078 continue;
1079 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001080 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1081 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1082 ext_device_life_time_est,
1083 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1084 ? ext_device_life_time_est
1085 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001086 }
1087
Felipe Lemed8b94e52016-12-08 10:21:44 -08001088 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001089}