blob: 01a60da566eb4911e8e5c065987c553a7d61683c [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>
Colin Crossf45fa6b2012-03-26 12:38:26 -070026#include <sys/inotify.h>
Felipe Lemee184f662016-10-27 10:04:47 -070027#include <sys/klog.h>
Mark Salyzyn261a7332016-05-24 12:38:40 -070028
Mark Salyzyn290f4b92016-05-16 08:33:59 -070029#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070030#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070031#include <android-base/stringprintf.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070032#include <android-base/strings.h>
Jeff Brownbf7f4922012-06-07 16:40:01 -070033#include <cutils/debugger.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070034#include <cutils/properties.h>
35#include <cutils/sockets.h>
36#include <private/android_filesystem_config.h>
37
Felipe Lemef0292972016-11-22 13:57:05 -080038#include "DumpstateInternal.h"
Jeff Brown1dc94e32014-09-11 14:15:27 -070039
Felipe Leme61884122016-06-13 09:23:30 -070040static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
41
Felipe Lemef0292972016-11-22 13:57:05 -080042/* Most simple commands have 10 as timeout, so 5 is a good estimate */
43static const int32_t WEIGHT_FILE = 5;
44
Felipe Lemee844a9d2016-09-21 15:01:39 -070045// TODO: temporary variables and functions used during C++ refactoring
46static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070047static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070048 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070049 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070050}
Felipe Lemef0292972016-11-22 13:57:05 -080051bool Dumpstate::IsUserBuild() {
52 return PropertiesHelper::IsUserBuild();
Felipe Leme4c2d6632016-09-28 14:32:00 -070053}
Felipe Lemee844a9d2016-09-21 15:01:39 -070054
Jeff Brownbf7f4922012-06-07 16:40:01 -070055/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070056// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070057static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080058 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080059 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070060 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070061 "/system/bin/mediacodec", // media.codec
62 "/system/bin/mediadrmserver",
63 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070064 "/system/bin/mediaserver",
65 "/system/bin/sdcard",
66 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070067 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070068 NULL,
69};
70
Felipe Leme7447d7c2016-11-03 18:12:22 -070071// Reasonable value for max stats.
72static const int STATS_MAX_N_RUNS = 1000;
73static const long STATS_MAX_AVERAGE = 100000;
74
Felipe Lemebda15a02016-11-16 17:48:25 -080075CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -070076
Felipe Lemef0292972016-11-22 13:57:05 -080077Dumpstate::Dumpstate(const std::string& version)
78 : pid_(getpid()), version_(version), now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -070079}
80
81Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -080082 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -070083 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -070084}
85
Felipe Leme46b85da2016-11-21 17:40:45 -080086DurationReporter::DurationReporter(const std::string& title, bool log_only)
87 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -070088 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -080089 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -080090 }
91}
92
93DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -070094 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -080095 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -080096 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -070097 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -080098 } else {
99 // Use "Yoda grammar" to make it easier to grep|sort sections.
100 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
101 title_.c_str());
102 fflush(stdout);
Felipe Leme608385d2016-02-01 10:35:38 -0800103 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800104 }
105}
106
Felipe Leme7447d7c2016-11-03 18:12:22 -0700107const int32_t Progress::kDefaultMax = 5000;
108
109Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
110}
111
112Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
113 : Progress(initial_max, growth_factor, "") {
114 progress_ = progress;
115}
116
117Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
118 : initial_max_(initial_max),
119 progress_(0),
120 max_(initial_max),
121 growth_factor_(growth_factor),
122 n_runs_(0),
123 average_max_(0),
124 path_(path) {
125 if (!path_.empty()) {
126 Load();
127 }
128}
129
130void Progress::Load() {
131 MYLOGD("Loading stats from %s\n", path_.c_str());
132 std::string content;
133 if (!android::base::ReadFileToString(path_, &content)) {
134 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
135 return;
136 }
137 if (content.empty()) {
138 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
139 return;
140 }
141 std::vector<std::string> lines = android::base::Split(content, "\n");
142
143 if (lines.size() < 1) {
144 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
145 (int)lines.size(), max_);
146 return;
147 }
148 char* ptr;
149 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
150 average_max_ = strtol(ptr, nullptr, 10);
151 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
152 average_max_ > STATS_MAX_AVERAGE) {
153 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
154 initial_max_ = Progress::kDefaultMax;
155 } else {
156 initial_max_ = average_max_;
157 }
158 max_ = initial_max_;
159
160 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
161}
162
163void Progress::Save() {
164 int32_t total = n_runs_ * average_max_ + progress_;
165 int32_t runs = n_runs_ + 1;
166 int32_t average = floor(((float)total) / runs);
167 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
168 path_.c_str());
169 if (path_.empty()) {
170 return;
171 }
172
173 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
174 if (!android::base::WriteStringToFile(content, path_)) {
175 MYLOGE("Could not save stats on %s\n", path_.c_str());
176 }
177}
178
179int32_t Progress::Get() const {
180 return progress_;
181}
182
183bool Progress::Inc(int32_t delta) {
184 bool changed = false;
185 if (delta >= 0) {
186 progress_ += delta;
187 if (progress_ > max_) {
188 int32_t old_max = max_;
189 max_ = floor((float)progress_ * growth_factor_);
190 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
191 changed = true;
192 }
193 }
194 return changed;
195}
196
197int32_t Progress::GetMax() const {
198 return max_;
199}
200
201int32_t Progress::GetInitialMax() const {
202 return initial_max_;
203}
204
205void Progress::Dump(int fd, const std::string& prefix) const {
206 const char* pr = prefix.c_str();
207 dprintf(fd, "%sprogress: %d\n", pr, progress_);
208 dprintf(fd, "%smax: %d\n", pr, max_);
209 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
210 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
211 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
212 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
213 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
214}
215
Felipe Leme75876a22016-10-27 16:31:27 -0700216bool Dumpstate::IsZipping() const {
217 return zip_writer_ != nullptr;
218}
219
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700220std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700221 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700222 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700223}
224
Felipe Leme7447d7c2016-11-03 18:12:22 -0700225void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
226 progress_ = std::move(progress);
227}
228
John Spurlock5ecd4be2014-01-29 14:14:40 -0500229void for_each_userid(void (*func)(int), const char *header) {
Felipe Lemef0292972016-11-22 13:57:05 -0800230 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700231
John Spurlock5ecd4be2014-01-29 14:14:40 -0500232 DIR *d;
233 struct dirent *de;
234
235 if (header) printf("\n------ %s ------\n", header);
236 func(0);
237
238 if (!(d = opendir("/data/system/users"))) {
239 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
240 return;
241 }
242
243 while ((de = readdir(d))) {
244 int userid;
245 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
246 continue;
247 }
248 func(userid);
249 }
250
251 closedir(d);
252}
253
Colin Cross0c22e8b2012-11-02 15:46:56 -0700254static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700255 DIR *d;
256 struct dirent *de;
257
258 if (!(d = opendir("/proc"))) {
259 printf("Failed to open /proc (%s)\n", strerror(errno));
260 return;
261 }
262
Felipe Leme635ca312016-01-05 14:23:02 -0800263 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700264 while ((de = readdir(d))) {
265 int pid;
266 int fd;
267 char cmdpath[255];
268 char cmdline[255];
269
270 if (!(pid = atoi(de->d_name))) {
271 continue;
272 }
273
Colin Crossf45fa6b2012-03-26 12:38:26 -0700274 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800275
276 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
277 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
278 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700279 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800280 if (cmdline[0]) {
281 helper(pid, cmdline, arg);
282 continue;
283 }
284 }
285
286 // if no cmdline, a kernel thread has comm
287 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
288 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
289 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
290 close(fd);
291 if (cmdline[1]) {
292 cmdline[0] = '[';
293 size_t len = strcspn(cmdline, "\f\b\r\n");
294 cmdline[len] = ']';
295 cmdline[len+1] = '\0';
296 }
297 }
298 if (!cmdline[0]) {
299 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700300 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700301 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700302 }
303
304 closedir(d);
305}
306
Colin Cross0c22e8b2012-11-02 15:46:56 -0700307static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800308 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700309 func(pid, cmdline);
310}
311
312void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Lemef0292972016-11-22 13:57:05 -0800313 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700314
Felipe Leme515eb0d2015-12-14 15:09:56 -0800315 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700316}
317
318static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
319 DIR *d;
320 struct dirent *de;
321 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800322 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700323
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700324 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700325
326 if (!(d = opendir(taskpath))) {
327 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
328 return;
329 }
330
331 func(pid, pid, cmdline);
332
333 while ((de = readdir(d))) {
334 int tid;
335 int fd;
336 char commpath[255];
337 char comm[255];
338
339 if (!(tid = atoi(de->d_name))) {
340 continue;
341 }
342
343 if (tid == pid)
344 continue;
345
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700346 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800347 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700348 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700349 strcpy(comm, "N/A");
350 } else {
351 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800352 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700353 close(fd);
354
355 c = strrchr(comm, '\n');
356 if (c) {
357 *c = '\0';
358 }
359 }
360 func(pid, tid, comm);
361 }
362
363 closedir(d);
364}
365
366void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Lemef0292972016-11-22 13:57:05 -0800367 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700368
Felipe Leme8620bb42015-11-10 11:04:45 -0800369 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700370}
371
372void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800373 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700374
Colin Crossf45fa6b2012-03-26 12:38:26 -0700375 char path[255];
376 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800377 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700378 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700379
380 memset(buffer, 0, sizeof(buffer));
381
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700382 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700383 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700384 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
385 return;
386 }
387
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800388 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
389 save_errno = errno;
390 close(fd);
391
392 if (ret < 0) {
393 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
394 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700395 }
396
Colin Cross0c22e8b2012-11-02 15:46:56 -0700397 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
398 pid == tid ? 0 : 3, "", name);
399
400 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700401
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800402 return;
403}
404
405// print time in centiseconds
406static void snprcent(char *buffer, size_t len, size_t spc,
407 unsigned long long time) {
408 static long hz; // cache discovered hz
409
410 if (hz <= 0) {
411 hz = sysconf(_SC_CLK_TCK);
412 if (hz <= 0) {
413 hz = 1000;
414 }
415 }
416
417 // convert to centiseconds
418 time = (time * 100 + (hz / 2)) / hz;
419
420 char str[16];
421
422 snprintf(str, sizeof(str), " %llu.%02u",
423 time / 100, (unsigned)(time % 100));
424 size_t offset = strlen(buffer);
425 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
426 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
427}
428
429// print permille as a percent
430static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
431 char str[16];
432
433 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
434 size_t offset = strlen(buffer);
435 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
436 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
437}
438
439void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800440 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700441
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800442 char path[255];
443 char buffer[1023];
444 int fd, ret, save_errno;
445
446 memset(buffer, 0, sizeof(buffer));
447
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700448 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800449 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
450 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
451 return;
452 }
453
454 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
455 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700456 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800457
458 if (ret < 0) {
459 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
460 return;
461 }
462
463 // field 14 is utime
464 // field 15 is stime
465 // field 42 is iotime
466 unsigned long long utime = 0, stime = 0, iotime = 0;
467 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800468 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
469 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
470 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
471 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800472 &utime, &stime, &iotime) != 3) {
473 return;
474 }
475
476 unsigned long long total = utime + stime;
477 if (!total) {
478 return;
479 }
480
481 unsigned permille = (iotime * 1000 + (total / 2)) / total;
482 if (permille > 1000) {
483 permille = 1000;
484 }
485
486 // try to beautify and stabilize columns at <80 characters
487 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
488 if ((name[0] != '[') || utime) {
489 snprcent(buffer, sizeof(buffer), 57, utime);
490 }
491 snprcent(buffer, sizeof(buffer), 65, stime);
492 if ((name[0] != '[') || iotime) {
493 snprcent(buffer, sizeof(buffer), 73, iotime);
494 }
495 if (iotime) {
496 snprdec(buffer, sizeof(buffer), 79, permille);
497 }
498 puts(buffer); // adds a trailing newline
499
Colin Crossf45fa6b2012-03-26 12:38:26 -0700500 return;
501}
502
503void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800504 const char *title = "KERNEL LOG (dmesg)";
505 DurationReporter duration_reporter(title);
506 printf("------ %s ------\n", title);
507
Felipe Lemef0292972016-11-22 13:57:05 -0800508 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700509
Elliott Hughes5f87b312012-09-17 11:43:40 -0700510 /* Get size of kernel buffer */
511 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700512 if (size <= 0) {
513 printf("Unexpected klogctl return value: %d\n\n", size);
514 return;
515 }
516 char *buf = (char *) malloc(size + 1);
517 if (buf == NULL) {
518 printf("memory allocation failed\n\n");
519 return;
520 }
521 int retval = klogctl(KLOG_READ_ALL, buf, size);
522 if (retval < 0) {
523 printf("klogctl failure\n\n");
524 free(buf);
525 return;
526 }
527 buf[retval] = '\0';
528 printf("%s\n\n", buf);
529 free(buf);
530 return;
531}
532
533void do_showmap(int pid, const char *name) {
534 char title[255];
535 char arg[255];
536
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700537 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
538 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800539 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800540}
541
Felipe Leme678727a2016-09-21 17:22:11 -0700542int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700543 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800544
Felipe Lemef0292972016-11-22 13:57:05 -0800545 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800546
Felipe Lemef0292972016-11-22 13:57:05 -0800547 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800548
549 fflush(stdout);
550
551 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800552}
553
Felipe Leme71a74ac2016-03-17 15:43:25 -0700554int read_file_as_long(const char *path, long int *output) {
555 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
556 if (fd < 0) {
557 int err = errno;
558 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
559 return -1;
560 }
561 char buffer[50];
562 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
563 if (bytes_read == -1) {
564 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
565 return -2;
566 }
567 if (bytes_read == 0) {
568 MYLOGE("File %s is empty\n", path);
569 return -3;
570 }
571 *output = atoi(buffer);
572 return 0;
573}
574
Mark Salyzyn326842f2015-04-30 09:49:41 -0700575/* calls skip to gate calling dump_from_fd recursively
576 * in the specified directory. dump_from_fd defaults to
577 * dump_file_from_fd above when set to NULL. skip defaults
578 * to false when set to NULL. dump_from_fd will always be
579 * called with title NULL.
580 */
Felipe Leme678727a2016-09-21 17:22:11 -0700581int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
582 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800583 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700584 DIR *dirp;
585 struct dirent *d;
586 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800587 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700588 int fd, retval = 0;
589
Felipe Leme678727a2016-09-21 17:22:11 -0700590 if (!title.empty()) {
591 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700592 }
Felipe Lemef0292972016-11-22 13:57:05 -0800593 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700594
595 if (dir[strlen(dir) - 1] == '/') {
596 ++slash;
597 }
598 dirp = opendir(dir);
599 if (dirp == NULL) {
600 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800601 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700602 return retval;
603 }
604
605 if (!dump_from_fd) {
606 dump_from_fd = dump_file_from_fd;
607 }
608 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
609 if ((d->d_name[0] == '.')
610 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
611 || (d->d_name[1] == '\0'))) {
612 continue;
613 }
614 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
615 (d->d_type == DT_DIR) ? "/" : "");
616 if (!newpath) {
617 retval = -errno;
618 continue;
619 }
620 if (skip && (*skip)(newpath)) {
621 continue;
622 }
623 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700624 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700625 if (ret < 0) {
626 retval = ret;
627 }
628 continue;
629 }
630 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
631 if (fd < 0) {
632 retval = fd;
633 printf("*** %s: %s\n", newpath, strerror(errno));
634 continue;
635 }
636 (*dump_from_fd)(NULL, newpath, fd);
637 }
638 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700639 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700640 printf("\n");
641 }
642 return retval;
643}
644
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800645/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
646 * it's possible to avoid issues where opening the file itself can get
647 * stuck.
648 */
649int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800650 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700651
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800652 int flags = fcntl(fd, F_GETFL);
653 if (flags == -1) {
654 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800655 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800656 return -1;
657 } else if (!(flags & O_NONBLOCK)) {
658 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800659 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800660 return -1;
661 }
Felipe Lemef0292972016-11-22 13:57:05 -0800662 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700663}
664
Felipe Leme46b85da2016-11-21 17:40:45 -0800665int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
666 const CommandOptions& options) {
667 DurationReporter duration_reporter(title);
668
Felipe Lemef0292972016-11-22 13:57:05 -0800669 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800670
Felipe Lemef0292972016-11-22 13:57:05 -0800671 /* TODO: for now we're simplifying the progress calculation by using the
672 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
673 * where its weight should be much higher proportionally to its timeout.
674 * Ideally, it should use a options.EstimatedDuration() instead...*/
675 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800676
677 fflush(stdout);
678
679 return status;
680}
681
Felipe Leme9a523ae2016-10-20 15:10:33 -0700682void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700683 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700684 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
685 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700686 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700687 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700688}
689
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800690void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700691 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
692
693 am.insert(am.end(), args.begin(), args.end());
694
Felipe Leme678727a2016-09-21 17:22:11 -0700695 RunCommand("", am, CommandOptions::WithTimeout(20)
696 .Log("Sending broadcast: '%s'\n")
697 .Always()
698 .DropRoot()
699 .RedirectStderr()
700 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800701}
702
Colin Crossf45fa6b2012-03-26 12:38:26 -0700703size_t num_props = 0;
704static char* props[2000];
705
706static void print_prop(const char *key, const char *name, void *user) {
707 (void) user;
708 if (num_props < sizeof(props) / sizeof(props[0])) {
709 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
710 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
711 props[num_props++] = strdup(buf);
712 }
713}
714
715static int compare_prop(const void *a, const void *b) {
716 return strcmp(*(char * const *) a, *(char * const *) b);
717}
718
719/* prints all the system properties */
720void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800721 const char* title = "SYSTEM PROPERTIES";
722 DurationReporter duration_reporter(title);
723 printf("------ %s ------\n", title);
Felipe Lemef0292972016-11-22 13:57:05 -0800724 if (PropertiesHelper::IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700725 size_t i;
726 num_props = 0;
727 property_list(print_prop, NULL);
728 qsort(&props, num_props, sizeof(props[0]), compare_prop);
729
Colin Crossf45fa6b2012-03-26 12:38:26 -0700730 for (i = 0; i < num_props; ++i) {
731 fputs(props[i], stdout);
732 free(props[i]);
733 }
734 printf("\n");
735}
736
Felipe Leme2628e9e2016-04-12 16:36:51 -0700737int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700738 int s = android_get_control_socket(service);
739 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800740 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700741 exit(1);
742 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700743 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700744 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800745 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700746 exit(1);
747 }
748
749 struct sockaddr addr;
750 socklen_t alen = sizeof(addr);
751 int fd = accept(s, &addr, &alen);
752 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800753 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700754 exit(1);
755 }
756
Felipe Leme2628e9e2016-04-12 16:36:51 -0700757 return fd;
758}
759
760/* redirect output to a service control socket */
761void redirect_to_socket(FILE *redirect, const char *service) {
762 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700763 fflush(redirect);
764 dup2(fd, fileno(redirect));
765 close(fd);
766}
767
Felipe Leme2628e9e2016-04-12 16:36:51 -0700768// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800769void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800770 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700771
772 /* skip initial slash */
773 if (chp[0] == '/')
774 chp++;
775
776 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800777 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700778 while (chp && chp[0]) {
779 chp = strchr(chp, '/');
780 if (chp) {
781 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800782 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800783 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800784 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800785 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800786 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800787 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800788 }
789 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700790 *chp++ = '/';
791 }
792 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800793}
794
Felipe Leme0f3fb202016-06-10 17:10:53 -0700795void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800796 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700797
Felipe Leme0f3fb202016-06-10 17:10:53 -0700798 int fd = TEMP_FAILURE_RETRY(open(path,
799 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800800 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700801 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800802 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700803 exit(1);
804 }
805
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800806 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700807 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700808}
809
Felipe Leme0f3fb202016-06-10 17:10:53 -0700810void redirect_to_file(FILE *redirect, char *path) {
811 _redirect_to_file(redirect, path, O_TRUNC);
812}
813
814void redirect_to_existing_file(FILE *redirect, char *path) {
815 _redirect_to_file(redirect, path, O_APPEND);
816}
817
Jeff Brownbf7f4922012-06-07 16:40:01 -0700818static bool should_dump_native_traces(const char* path) {
819 for (const char** p = native_processes_to_dump; *p; p++) {
820 if (!strcmp(*p, path)) {
821 return true;
822 }
823 }
824 return false;
825}
826
827/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
828const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -0700829 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -0700830
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700831 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -0700832
Felipe Lemee184f662016-10-27 10:04:47 -0700833 std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
834 if (traces_path.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700835
836 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -0700837 std::string anrtraces_path = traces_path + ".anr";
838 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
839 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700840 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -0700841 }
842
Colin Crossf45fa6b2012-03-26 12:38:26 -0700843 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Lemee184f662016-10-27 10:04:47 -0700844 int fd = TEMP_FAILURE_RETRY(open(traces_path.c_str(),
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700845 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
846 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700847 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700848 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700849 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700850 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700851 int chmod_ret = fchmod(fd, 0666);
852 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700853 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700854 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700855 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700856 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700857
Felipe Leme8620bb42015-11-10 11:04:45 -0800858 /* Variables below must be initialized before 'goto' statements */
859 int dalvik_found = 0;
860 int ifd, wfd = -1;
861
Colin Crossf45fa6b2012-03-26 12:38:26 -0700862 /* walk /proc and kill -QUIT all Dalvik processes */
863 DIR *proc = opendir("/proc");
864 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800865 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700866 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700867 }
868
869 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -0800870 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700871 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800872 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700873 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700874 }
875
Felipe Lemee184f662016-10-27 10:04:47 -0700876 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700877 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700878 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700879 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700880 }
881
882 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700883 while ((d = readdir(proc))) {
884 int pid = atoi(d->d_name);
885 if (pid <= 0) continue;
886
Jeff Brownbf7f4922012-06-07 16:40:01 -0700887 char path[PATH_MAX];
888 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700889 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700890 ssize_t len = readlink(path, data, sizeof(data) - 1);
891 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700892 continue;
893 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700894 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700895
Colin Cross0d6180f2014-07-16 19:00:46 -0700896 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700897 /* skip zygote -- it won't dump its stack anyway */
898 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700899 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700900 len = read(cfd, data, sizeof(data) - 1);
901 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700902 if (len <= 0) {
903 continue;
904 }
905 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700906 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700907 continue;
908 }
909
910 ++dalvik_found;
Felipe Lemef0292972016-11-22 13:57:05 -0800911 uint64_t start = Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700912 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800913 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700914 continue;
915 }
916
917 /* wait for the writable-close notification from inotify */
918 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -0700919 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700920 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800921 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700922 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800923 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700924 } else {
925 struct inotify_event ie;
926 read(ifd, &ie, sizeof(ie));
927 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700928
929 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800930 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700931 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700932 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -0800933 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700934 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700935 } else if (should_dump_native_traces(data)) {
936 /* dump native process if appropriate */
937 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800938 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700939 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800940 static uint16_t timeout_failures = 0;
Felipe Lemef0292972016-11-22 13:57:05 -0800941 uint64_t start = Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800942
943 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
944 if (timeout_failures == 3) {
945 dprintf(fd, "too many stack dump failures, skipping...\n");
946 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
947 dprintf(fd, "dumping failed, likely due to a timeout\n");
948 timeout_failures++;
949 } else {
950 timeout_failures = 0;
951 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700952 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -0800953 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700954 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700955 }
956 }
957
Colin Crossf45fa6b2012-03-26 12:38:26 -0700958 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800959 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700960 }
961
Felipe Lemee184f662016-10-27 10:04:47 -0700962 static std::string dumptraces_path = android::base::StringPrintf(
963 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
964 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
965 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
966 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700967 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700968 }
Felipe Lemee184f662016-10-27 10:04:47 -0700969 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700970
971 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -0700972 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -0700973
974error_close_ifd:
975 close(ifd);
976error_close_fd:
977 close(fd);
978 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700979}
980
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700981void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800982 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -0800983 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700984 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -0700985 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700986 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700987 if (!fp) {
988 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
989 return;
990 }
991 char table[16];
992 // Each line has an integer (the table number), a space, and a string (the table name). We only
993 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
994 // Add a fixed max limit so this doesn't go awry.
995 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700996 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
997 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700998 }
999 fclose(fp);
1000}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001001
Felipe Leme71bbfc52015-11-23 14:14:51 -08001002// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001003void Dumpstate::UpdateProgress(int32_t delta) {
1004 if (progress_ == nullptr) {
1005 MYLOGE("UpdateProgress: progress_ not set\n");
1006 return;
1007 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001008
Felipe Leme7447d7c2016-11-03 18:12:22 -07001009 // Always update progess so stats can be tuned...
1010 bool max_changed = progress_->Inc(delta);
1011
1012 // ...but only notifiy listeners when necessary.
1013 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001014
Felipe Leme009ecbb2016-11-07 10:18:44 -08001015 int progress = progress_->Get();
1016 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -08001017
1018 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -08001019 if (max_changed && listener_ != nullptr) {
1020 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001021 }
1022
Felipe Leme009ecbb2016-11-07 10:18:44 -08001023 int32_t last_update_delta = progress - last_updated_progress_;
1024 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1025 return;
1026 }
1027 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001028
Felipe Leme9a523ae2016-10-20 15:10:33 -07001029 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001030 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001031 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001032 }
1033
Felipe Leme75876a22016-10-27 16:31:27 -07001034 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001035 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001036 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001037 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001038 } else {
1039 // stderr is ignored on normal invocations, but useful when calling
1040 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001041 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001042 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001043 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001044 }
1045}
Felipe Lemee338bf62015-12-07 14:03:50 -08001046
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001047void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001048 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001049 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001050 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001051 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1052 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001053 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001054 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001055 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001056 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001057}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001058
Felipe Leme0c80cf02016-01-05 13:25:34 -08001059void vibrate(FILE* vibrator, int ms) {
1060 fprintf(vibrator, "%d\n", ms);
1061 fflush(vibrator);
1062}
1063
1064bool is_dir(const char* pathname) {
1065 struct stat info;
1066 if (stat(pathname, &info) == -1) {
1067 return false;
1068 }
1069 return S_ISDIR(info.st_mode);
1070}
1071
1072time_t get_mtime(int fd, time_t default_mtime) {
1073 struct stat info;
1074 if (fstat(fd, &info) == -1) {
1075 return default_mtime;
1076 }
1077 return info.st_mtime;
1078}
1079
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001080void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001081 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001082 struct hex {
1083 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001084 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001085 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1086 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1087 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1088 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1089
1090 std::string buffer;
1091 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1092 return;
1093 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001094
1095 printf("------ %s Extended CSD ------\n", ext_csd_path);
1096
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001097 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1098 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001099 return;
1100 }
1101
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001102 int ext_csd_rev = 0;
1103 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1104 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1105 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1106 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001107 return;
1108 }
1109
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001110 static const char *ver_str[] = {
1111 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1112 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001113 printf("rev 1.%d (MMC %s)\n",
1114 ext_csd_rev,
1115 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1116 ver_str[ext_csd_rev] :
1117 "Unknown");
1118 if (ext_csd_rev < 7) {
1119 printf("\n");
1120 return;
1121 }
1122
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001123 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1124 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001125 return;
1126 }
1127
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001128 int ext_pre_eol_info = 0;
1129 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1130 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1131 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1132 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001133 return;
1134 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001135
1136 static const char *eol_str[] = {
1137 "Undefined",
1138 "Normal",
1139 "Warning (consumed 80% of reserve)",
1140 "Urgent (consumed 90% of reserve)"
1141 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001142 printf("PRE_EOL_INFO %d (MMC %s)\n",
1143 ext_pre_eol_info,
1144 eol_str[(ext_pre_eol_info < (int)
1145 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1146 ext_pre_eol_info : 0]);
1147
1148 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1149 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001150 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001151 int ext_device_life_time_est;
1152 static const char *est_str[] = {
1153 "Undefined",
1154 "0-10% of device lifetime used",
1155 "10-20% of device lifetime used",
1156 "20-30% of device lifetime used",
1157 "30-40% of device lifetime used",
1158 "40-50% of device lifetime used",
1159 "50-60% of device lifetime used",
1160 "60-70% of device lifetime used",
1161 "70-80% of device lifetime used",
1162 "80-90% of device lifetime used",
1163 "90-100% of device lifetime used",
1164 "Exceeded the maximum estimated device lifetime",
1165 };
1166
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001167 if (buffer.length() < (lifetime + sizeof(hex))) {
1168 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001169 break;
1170 }
1171
1172 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001173 sub = buffer.substr(lifetime, sizeof(hex));
1174 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1175 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001176 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001177 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1178 sizeof(hex)) + 'A',
1179 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001180 continue;
1181 }
1182 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001183 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1184 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001185 ext_device_life_time_est,
1186 est_str[(ext_device_life_time_est < (int)
1187 (sizeof(est_str) / sizeof(est_str[0]))) ?
1188 ext_device_life_time_est : 0]);
1189 }
1190
1191 printf("\n");
1192}