blob: 3ba177e550873b3b418fdab66dc8851f583087c5 [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
Mark Salyzyna5e161b2016-09-29 08:08:05 -070041#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080042#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070043
Mark Salyzyn290f4b92016-05-16 08:33:59 -070044#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070045#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070046#include <android-base/stringprintf.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070047#include <android-base/strings.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070048#include <cutils/properties.h>
49#include <cutils/sockets.h>
Josh Gaod2db0242017-01-05 18:27:33 -080050#include <debuggerd/client.h>
Mark Salyzyn4eb13822017-01-12 13:57:51 -080051#include <log/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070052#include <private/android_filesystem_config.h>
53
Felipe Lemef0292972016-11-22 13:57:05 -080054#include "DumpstateInternal.h"
Jeff Brown1dc94e32014-09-11 14:15:27 -070055
Felipe Leme47e9be22016-12-21 15:37:07 -080056// TODO: remove once moved to namespace
57using android::os::dumpstate::CommandOptions;
58using android::os::dumpstate::DumpFileToFd;
59using android::os::dumpstate::PropertiesHelper;
60
Brian Carlstroma3322752017-03-19 17:48:01 -070061// Keep in sync with
62// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
Felipe Leme61884122016-06-13 09:23:30 -070063static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
64
Felipe Lemef0292972016-11-22 13:57:05 -080065/* Most simple commands have 10 as timeout, so 5 is a good estimate */
66static const int32_t WEIGHT_FILE = 5;
67
Felipe Lemee844a9d2016-09-21 15:01:39 -070068// TODO: temporary variables and functions used during C++ refactoring
69static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070070static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070071 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070072 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070073}
Felipe Lemee844a9d2016-09-21 15:01:39 -070074
Jeff Brownbf7f4922012-06-07 16:40:01 -070075/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070076// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070077static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080078 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080079 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070080 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070081 "/system/bin/mediadrmserver",
82 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070083 "/system/bin/mediaserver",
84 "/system/bin/sdcard",
85 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070086 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070087 NULL,
88};
89
Felipe Leme7447d7c2016-11-03 18:12:22 -070090// Reasonable value for max stats.
91static const int STATS_MAX_N_RUNS = 1000;
92static const long STATS_MAX_AVERAGE = 100000;
93
Felipe Lemebda15a02016-11-16 17:48:25 -080094CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -070095
Felipe Lemef0292972016-11-22 13:57:05 -080096Dumpstate::Dumpstate(const std::string& version)
97 : pid_(getpid()), version_(version), now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -070098}
99
100Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -0800101 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700102 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700103}
104
Felipe Leme46b85da2016-11-21 17:40:45 -0800105DurationReporter::DurationReporter(const std::string& title, bool log_only)
106 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700107 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800108 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800109 }
110}
111
112DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700113 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800114 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800115 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700116 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800117 } else {
118 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800119 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
120 title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800121 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800122 }
123}
124
Felipe Leme7447d7c2016-11-03 18:12:22 -0700125const int32_t Progress::kDefaultMax = 5000;
126
127Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
128}
129
130Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
131 : Progress(initial_max, growth_factor, "") {
132 progress_ = progress;
133}
134
135Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
136 : initial_max_(initial_max),
137 progress_(0),
138 max_(initial_max),
139 growth_factor_(growth_factor),
140 n_runs_(0),
141 average_max_(0),
142 path_(path) {
143 if (!path_.empty()) {
144 Load();
145 }
146}
147
148void Progress::Load() {
149 MYLOGD("Loading stats from %s\n", path_.c_str());
150 std::string content;
151 if (!android::base::ReadFileToString(path_, &content)) {
152 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
153 return;
154 }
155 if (content.empty()) {
156 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
157 return;
158 }
159 std::vector<std::string> lines = android::base::Split(content, "\n");
160
161 if (lines.size() < 1) {
162 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
163 (int)lines.size(), max_);
164 return;
165 }
166 char* ptr;
167 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
168 average_max_ = strtol(ptr, nullptr, 10);
169 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
170 average_max_ > STATS_MAX_AVERAGE) {
171 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
172 initial_max_ = Progress::kDefaultMax;
173 } else {
174 initial_max_ = average_max_;
175 }
176 max_ = initial_max_;
177
178 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
179}
180
181void Progress::Save() {
182 int32_t total = n_runs_ * average_max_ + progress_;
183 int32_t runs = n_runs_ + 1;
184 int32_t average = floor(((float)total) / runs);
185 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
186 path_.c_str());
187 if (path_.empty()) {
188 return;
189 }
190
191 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
192 if (!android::base::WriteStringToFile(content, path_)) {
193 MYLOGE("Could not save stats on %s\n", path_.c_str());
194 }
195}
196
197int32_t Progress::Get() const {
198 return progress_;
199}
200
201bool Progress::Inc(int32_t delta) {
202 bool changed = false;
203 if (delta >= 0) {
204 progress_ += delta;
205 if (progress_ > max_) {
206 int32_t old_max = max_;
207 max_ = floor((float)progress_ * growth_factor_);
208 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
209 changed = true;
210 }
211 }
212 return changed;
213}
214
215int32_t Progress::GetMax() const {
216 return max_;
217}
218
219int32_t Progress::GetInitialMax() const {
220 return initial_max_;
221}
222
223void Progress::Dump(int fd, const std::string& prefix) const {
224 const char* pr = prefix.c_str();
225 dprintf(fd, "%sprogress: %d\n", pr, progress_);
226 dprintf(fd, "%smax: %d\n", pr, max_);
227 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
228 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
229 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
230 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
231 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
232}
233
Felipe Leme75876a22016-10-27 16:31:27 -0700234bool Dumpstate::IsZipping() const {
235 return zip_writer_ != nullptr;
236}
237
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700238std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700239 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700240 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700241}
242
Felipe Leme7447d7c2016-11-03 18:12:22 -0700243void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
244 progress_ = std::move(progress);
245}
246
John Spurlock5ecd4be2014-01-29 14:14:40 -0500247void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800248 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
249 "for_each_userid(%s)", header);
250 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800251 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700252
John Spurlock5ecd4be2014-01-29 14:14:40 -0500253 DIR *d;
254 struct dirent *de;
255
Felipe Lemed8b94e52016-12-08 10:21:44 -0800256 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500257 func(0);
258
259 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800260 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500261 return;
262 }
263
264 while ((de = readdir(d))) {
265 int userid;
266 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
267 continue;
268 }
269 func(userid);
270 }
271
272 closedir(d);
273}
274
Colin Cross0c22e8b2012-11-02 15:46:56 -0700275static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700276 DIR *d;
277 struct dirent *de;
278
279 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800280 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700281 return;
282 }
283
Felipe Lemed8b94e52016-12-08 10:21:44 -0800284 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700285 while ((de = readdir(d))) {
286 int pid;
287 int fd;
288 char cmdpath[255];
289 char cmdline[255];
290
291 if (!(pid = atoi(de->d_name))) {
292 continue;
293 }
294
Colin Crossf45fa6b2012-03-26 12:38:26 -0700295 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800296
297 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
298 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
299 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700300 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800301 if (cmdline[0]) {
302 helper(pid, cmdline, arg);
303 continue;
304 }
305 }
306
307 // if no cmdline, a kernel thread has comm
308 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
309 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
310 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
311 close(fd);
312 if (cmdline[1]) {
313 cmdline[0] = '[';
314 size_t len = strcspn(cmdline, "\f\b\r\n");
315 cmdline[len] = ']';
316 cmdline[len+1] = '\0';
317 }
318 }
319 if (!cmdline[0]) {
320 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700321 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700322 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700323 }
324
325 closedir(d);
326}
327
Colin Cross0c22e8b2012-11-02 15:46:56 -0700328static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800329 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700330 func(pid, cmdline);
331}
332
333void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800334 std::string title = header == nullptr ? "for_each_pid"
335 : android::base::StringPrintf("for_each_pid(%s)", header);
336 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800337 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700338
Felipe Leme515eb0d2015-12-14 15:09:56 -0800339 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700340}
341
342static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
343 DIR *d;
344 struct dirent *de;
345 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800346 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700347
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700348 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700349
350 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800351 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700352 return;
353 }
354
355 func(pid, pid, cmdline);
356
357 while ((de = readdir(d))) {
358 int tid;
359 int fd;
360 char commpath[255];
361 char comm[255];
362
363 if (!(tid = atoi(de->d_name))) {
364 continue;
365 }
366
367 if (tid == pid)
368 continue;
369
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700370 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800371 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700372 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700373 strcpy(comm, "N/A");
374 } else {
375 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800376 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700377 close(fd);
378
379 c = strrchr(comm, '\n');
380 if (c) {
381 *c = '\0';
382 }
383 }
384 func(pid, tid, comm);
385 }
386
387 closedir(d);
388}
389
390void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800391 std::string title = header == nullptr ? "for_each_tid"
392 : android::base::StringPrintf("for_each_tid(%s)", header);
393 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800394
Felipe Lemef0292972016-11-22 13:57:05 -0800395 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700396
Felipe Leme8620bb42015-11-10 11:04:45 -0800397 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700398}
399
400void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800401 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700402
Colin Crossf45fa6b2012-03-26 12:38:26 -0700403 char path[255];
404 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800405 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700406 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700407
408 memset(buffer, 0, sizeof(buffer));
409
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700410 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700411 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800412 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700413 return;
414 }
415
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800416 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
417 save_errno = errno;
418 close(fd);
419
420 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800421 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800422 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700423 }
424
Colin Cross0c22e8b2012-11-02 15:46:56 -0700425 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
426 pid == tid ? 0 : 3, "", name);
427
Felipe Lemed8b94e52016-12-08 10:21:44 -0800428 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700429
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800430 return;
431}
432
433// print time in centiseconds
434static void snprcent(char *buffer, size_t len, size_t spc,
435 unsigned long long time) {
436 static long hz; // cache discovered hz
437
438 if (hz <= 0) {
439 hz = sysconf(_SC_CLK_TCK);
440 if (hz <= 0) {
441 hz = 1000;
442 }
443 }
444
445 // convert to centiseconds
446 time = (time * 100 + (hz / 2)) / hz;
447
448 char str[16];
449
450 snprintf(str, sizeof(str), " %llu.%02u",
451 time / 100, (unsigned)(time % 100));
452 size_t offset = strlen(buffer);
453 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
454 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
455}
456
457// print permille as a percent
458static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
459 char str[16];
460
461 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
462 size_t offset = strlen(buffer);
463 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
464 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
465}
466
467void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800468 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700469
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800470 char path[255];
471 char buffer[1023];
472 int fd, ret, save_errno;
473
474 memset(buffer, 0, sizeof(buffer));
475
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700476 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800477 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800478 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800479 return;
480 }
481
482 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
483 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700484 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800485
486 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800487 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800488 return;
489 }
490
491 // field 14 is utime
492 // field 15 is stime
493 // field 42 is iotime
494 unsigned long long utime = 0, stime = 0, iotime = 0;
495 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800496 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
497 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
498 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
499 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800500 &utime, &stime, &iotime) != 3) {
501 return;
502 }
503
504 unsigned long long total = utime + stime;
505 if (!total) {
506 return;
507 }
508
509 unsigned permille = (iotime * 1000 + (total / 2)) / total;
510 if (permille > 1000) {
511 permille = 1000;
512 }
513
514 // try to beautify and stabilize columns at <80 characters
515 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
516 if ((name[0] != '[') || utime) {
517 snprcent(buffer, sizeof(buffer), 57, utime);
518 }
519 snprcent(buffer, sizeof(buffer), 65, stime);
520 if ((name[0] != '[') || iotime) {
521 snprcent(buffer, sizeof(buffer), 73, iotime);
522 }
523 if (iotime) {
524 snprdec(buffer, sizeof(buffer), 79, permille);
525 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800526 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800527
Colin Crossf45fa6b2012-03-26 12:38:26 -0700528 return;
529}
530
531void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800532 const char *title = "KERNEL LOG (dmesg)";
533 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800534 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800535
Felipe Lemef0292972016-11-22 13:57:05 -0800536 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700537
Elliott Hughes5f87b312012-09-17 11:43:40 -0700538 /* Get size of kernel buffer */
539 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700540 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800541 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700542 return;
543 }
544 char *buf = (char *) malloc(size + 1);
545 if (buf == NULL) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800546 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700547 return;
548 }
549 int retval = klogctl(KLOG_READ_ALL, buf, size);
550 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800551 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700552 free(buf);
553 return;
554 }
555 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800556 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700557 free(buf);
558 return;
559}
560
561void do_showmap(int pid, const char *name) {
562 char title[255];
563 char arg[255];
564
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700565 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
566 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800567 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800568}
569
Felipe Leme678727a2016-09-21 17:22:11 -0700570int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700571 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800572
Felipe Lemef0292972016-11-22 13:57:05 -0800573 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800574
Felipe Lemef0292972016-11-22 13:57:05 -0800575 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800576
Felipe Leme46b85da2016-11-21 17:40:45 -0800577 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800578}
579
Felipe Leme71a74ac2016-03-17 15:43:25 -0700580int read_file_as_long(const char *path, long int *output) {
581 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
582 if (fd < 0) {
583 int err = errno;
584 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
585 return -1;
586 }
587 char buffer[50];
588 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
589 if (bytes_read == -1) {
590 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
591 return -2;
592 }
593 if (bytes_read == 0) {
594 MYLOGE("File %s is empty\n", path);
595 return -3;
596 }
597 *output = atoi(buffer);
598 return 0;
599}
600
Mark Salyzyn326842f2015-04-30 09:49:41 -0700601/* calls skip to gate calling dump_from_fd recursively
602 * in the specified directory. dump_from_fd defaults to
603 * dump_file_from_fd above when set to NULL. skip defaults
604 * to false when set to NULL. dump_from_fd will always be
605 * called with title NULL.
606 */
Felipe Leme678727a2016-09-21 17:22:11 -0700607int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
608 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800609 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700610 DIR *dirp;
611 struct dirent *d;
612 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800613 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700614 int fd, retval = 0;
615
Felipe Leme678727a2016-09-21 17:22:11 -0700616 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800617 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700618 }
Felipe Lemef0292972016-11-22 13:57:05 -0800619 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700620
621 if (dir[strlen(dir) - 1] == '/') {
622 ++slash;
623 }
624 dirp = opendir(dir);
625 if (dirp == NULL) {
626 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800627 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700628 return retval;
629 }
630
631 if (!dump_from_fd) {
632 dump_from_fd = dump_file_from_fd;
633 }
634 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
635 if ((d->d_name[0] == '.')
636 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
637 || (d->d_name[1] == '\0'))) {
638 continue;
639 }
640 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
641 (d->d_type == DT_DIR) ? "/" : "");
642 if (!newpath) {
643 retval = -errno;
644 continue;
645 }
646 if (skip && (*skip)(newpath)) {
647 continue;
648 }
649 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700650 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700651 if (ret < 0) {
652 retval = ret;
653 }
654 continue;
655 }
656 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
657 if (fd < 0) {
658 retval = fd;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800659 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700660 continue;
661 }
662 (*dump_from_fd)(NULL, newpath, fd);
663 }
664 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700665 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800666 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700667 }
668 return retval;
669}
670
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800671/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
672 * it's possible to avoid issues where opening the file itself can get
673 * stuck.
674 */
675int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800676 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700677
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800678 int flags = fcntl(fd, F_GETFL);
679 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800680 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800681 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800682 return -1;
683 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800684 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800685 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800686 return -1;
687 }
Felipe Lemef0292972016-11-22 13:57:05 -0800688 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700689}
690
Felipe Leme46b85da2016-11-21 17:40:45 -0800691int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
692 const CommandOptions& options) {
693 DurationReporter duration_reporter(title);
694
Felipe Lemef0292972016-11-22 13:57:05 -0800695 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800696
Felipe Lemef0292972016-11-22 13:57:05 -0800697 /* TODO: for now we're simplifying the progress calculation by using the
698 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
699 * where its weight should be much higher proportionally to its timeout.
700 * Ideally, it should use a options.EstimatedDuration() instead...*/
701 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800702
Felipe Leme46b85da2016-11-21 17:40:45 -0800703 return status;
704}
705
Felipe Leme9a523ae2016-10-20 15:10:33 -0700706void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700707 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700708 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
709 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700710 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700711 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700712}
713
Felipe Leme2628e9e2016-04-12 16:36:51 -0700714int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700715 int s = android_get_control_socket(service);
716 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800717 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700718 exit(1);
719 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700720 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700721 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800722 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700723 exit(1);
724 }
725
726 struct sockaddr addr;
727 socklen_t alen = sizeof(addr);
728 int fd = accept(s, &addr, &alen);
729 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800730 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700731 exit(1);
732 }
733
Felipe Leme2628e9e2016-04-12 16:36:51 -0700734 return fd;
735}
736
737/* redirect output to a service control socket */
738void redirect_to_socket(FILE *redirect, const char *service) {
739 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700740 fflush(redirect);
741 dup2(fd, fileno(redirect));
742 close(fd);
743}
744
Felipe Leme2628e9e2016-04-12 16:36:51 -0700745// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800746void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800747 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700748
749 /* skip initial slash */
750 if (chp[0] == '/')
751 chp++;
752
753 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800754 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700755 while (chp && chp[0]) {
756 chp = strchr(chp, '/');
757 if (chp) {
758 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800759 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800760 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800761 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800762 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800763 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800764 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800765 }
766 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700767 *chp++ = '/';
768 }
769 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800770}
771
Felipe Leme0f3fb202016-06-10 17:10:53 -0700772void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800773 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700774
Felipe Leme0f3fb202016-06-10 17:10:53 -0700775 int fd = TEMP_FAILURE_RETRY(open(path,
776 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800777 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700778 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800779 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700780 exit(1);
781 }
782
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800783 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700784 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700785}
786
Felipe Leme0f3fb202016-06-10 17:10:53 -0700787void redirect_to_file(FILE *redirect, char *path) {
788 _redirect_to_file(redirect, path, O_TRUNC);
789}
790
791void redirect_to_existing_file(FILE *redirect, char *path) {
792 _redirect_to_file(redirect, path, O_APPEND);
793}
794
Jeff Brownbf7f4922012-06-07 16:40:01 -0700795static bool should_dump_native_traces(const char* path) {
796 for (const char** p = native_processes_to_dump; *p; p++) {
797 if (!strcmp(*p, path)) {
798 return true;
799 }
800 }
801 return false;
802}
803
804/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
805const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -0700806 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -0700807
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700808 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -0700809
Felipe Lemee184f662016-10-27 10:04:47 -0700810 std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
811 if (traces_path.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700812
813 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -0700814 std::string anrtraces_path = traces_path + ".anr";
815 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
816 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700817 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -0700818 }
819
Colin Crossf45fa6b2012-03-26 12:38:26 -0700820 /* create a new, empty traces.txt file to receive stack dumps */
Josh Gao989b8122017-01-13 22:09:40 -0800821 int fd = TEMP_FAILURE_RETRY(
Josh Gaoe75d9632017-01-18 16:14:03 -0800822 open(traces_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
Josh Gao989b8122017-01-13 22:09:40 -0800823 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700824 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700825 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700826 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700827 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700828 int chmod_ret = fchmod(fd, 0666);
829 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700830 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700831 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700832 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700833 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700834
Felipe Leme8620bb42015-11-10 11:04:45 -0800835 /* Variables below must be initialized before 'goto' statements */
836 int dalvik_found = 0;
837 int ifd, wfd = -1;
838
Colin Crossf45fa6b2012-03-26 12:38:26 -0700839 /* walk /proc and kill -QUIT all Dalvik processes */
840 DIR *proc = opendir("/proc");
841 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800842 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700843 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700844 }
845
846 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -0800847 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700848 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800849 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700850 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700851 }
852
Felipe Lemee184f662016-10-27 10:04:47 -0700853 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700854 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700855 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700856 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700857 }
858
859 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700860 while ((d = readdir(proc))) {
861 int pid = atoi(d->d_name);
862 if (pid <= 0) continue;
863
Jeff Brownbf7f4922012-06-07 16:40:01 -0700864 char path[PATH_MAX];
865 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700866 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700867 ssize_t len = readlink(path, data, sizeof(data) - 1);
868 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700869 continue;
870 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700871 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700872
Colin Cross0d6180f2014-07-16 19:00:46 -0700873 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700874 /* skip zygote -- it won't dump its stack anyway */
875 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700876 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700877 len = read(cfd, data, sizeof(data) - 1);
878 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700879 if (len <= 0) {
880 continue;
881 }
882 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700883 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700884 continue;
885 }
886
887 ++dalvik_found;
Felipe Lemef0292972016-11-22 13:57:05 -0800888 uint64_t start = Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700889 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800890 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700891 continue;
892 }
893
894 /* wait for the writable-close notification from inotify */
895 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -0700896 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700897 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800898 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700899 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800900 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700901 } else {
902 struct inotify_event ie;
903 read(ifd, &ie, sizeof(ie));
904 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700905
906 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800907 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700908 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700909 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -0800910 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700911 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700912 } else if (should_dump_native_traces(data)) {
913 /* dump native process if appropriate */
914 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800915 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700916 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800917 static uint16_t timeout_failures = 0;
Felipe Lemef0292972016-11-22 13:57:05 -0800918 uint64_t start = Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800919
920 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
921 if (timeout_failures == 3) {
922 dprintf(fd, "too many stack dump failures, skipping...\n");
923 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
924 dprintf(fd, "dumping failed, likely due to a timeout\n");
925 timeout_failures++;
926 } else {
927 timeout_failures = 0;
928 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700929 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -0800930 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700931 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700932 }
933 }
934
Colin Crossf45fa6b2012-03-26 12:38:26 -0700935 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800936 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700937 }
938
Felipe Lemee184f662016-10-27 10:04:47 -0700939 static std::string dumptraces_path = android::base::StringPrintf(
940 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
941 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
942 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
943 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700944 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700945 }
Felipe Lemee184f662016-10-27 10:04:47 -0700946 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700947
948 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -0700949 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -0700950
951error_close_ifd:
952 close(ifd);
953error_close_fd:
954 close(fd);
955 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700956}
957
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700958void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800959 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -0800960 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700961 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -0700962 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700963 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700964 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800965 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700966 return;
967 }
968 char table[16];
969 // Each line has an integer (the table number), a space, and a string (the table name). We only
970 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
971 // Add a fixed max limit so this doesn't go awry.
972 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700973 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
974 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700975 }
976 fclose(fp);
977}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800978
Felipe Leme71bbfc52015-11-23 14:14:51 -0800979// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700980void Dumpstate::UpdateProgress(int32_t delta) {
981 if (progress_ == nullptr) {
982 MYLOGE("UpdateProgress: progress_ not set\n");
983 return;
984 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800985
Felipe Leme7447d7c2016-11-03 18:12:22 -0700986 // Always update progess so stats can be tuned...
987 bool max_changed = progress_->Inc(delta);
988
989 // ...but only notifiy listeners when necessary.
990 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800991
Felipe Leme009ecbb2016-11-07 10:18:44 -0800992 int progress = progress_->Get();
993 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -0800994
995 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -0800996 if (max_changed && listener_ != nullptr) {
997 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -0800998 }
999
Felipe Leme009ecbb2016-11-07 10:18:44 -08001000 int32_t last_update_delta = progress - last_updated_progress_;
1001 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1002 return;
1003 }
1004 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001005
Felipe Leme9a523ae2016-10-20 15:10:33 -07001006 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001007 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001008 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001009 }
1010
Felipe Leme75876a22016-10-27 16:31:27 -07001011 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001012 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001013 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001014 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001015 } else {
1016 // stderr is ignored on normal invocations, but useful when calling
1017 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001018 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001019 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001020 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001021 }
1022}
Felipe Lemee338bf62015-12-07 14:03:50 -08001023
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001024void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001025 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001026 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001027 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001028 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1029 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001030 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001031 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001032 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001033 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001034}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001035
Felipe Leme0c80cf02016-01-05 13:25:34 -08001036bool is_dir(const char* pathname) {
1037 struct stat info;
1038 if (stat(pathname, &info) == -1) {
1039 return false;
1040 }
1041 return S_ISDIR(info.st_mode);
1042}
1043
1044time_t get_mtime(int fd, time_t default_mtime) {
1045 struct stat info;
1046 if (fstat(fd, &info) == -1) {
1047 return default_mtime;
1048 }
1049 return info.st_mtime;
1050}
1051
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001052void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001053 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001054 struct hex {
1055 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001056 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001057 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1058 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1059 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1060 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1061
1062 std::string buffer;
1063 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1064 return;
1065 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001066
Felipe Lemed8b94e52016-12-08 10:21:44 -08001067 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001068
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001069 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001070 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001071 return;
1072 }
1073
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001074 int ext_csd_rev = 0;
1075 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1076 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001077 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001078 return;
1079 }
1080
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001081 static const char *ver_str[] = {
1082 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1083 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001084 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1085 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1086 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001087 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001088 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001089 return;
1090 }
1091
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001092 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001093 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001094 return;
1095 }
1096
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001097 int ext_pre_eol_info = 0;
1098 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1099 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001100 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001101 return;
1102 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001103
1104 static const char *eol_str[] = {
1105 "Undefined",
1106 "Normal",
1107 "Warning (consumed 80% of reserve)",
1108 "Urgent (consumed 90% of reserve)"
1109 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001110 printf(
1111 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -08001112 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1113 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001114
1115 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1116 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001117 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001118 int ext_device_life_time_est;
1119 static const char *est_str[] = {
1120 "Undefined",
1121 "0-10% of device lifetime used",
1122 "10-20% of device lifetime used",
1123 "20-30% of device lifetime used",
1124 "30-40% of device lifetime used",
1125 "40-50% of device lifetime used",
1126 "50-60% of device lifetime used",
1127 "60-70% of device lifetime used",
1128 "70-80% of device lifetime used",
1129 "80-90% of device lifetime used",
1130 "90-100% of device lifetime used",
1131 "Exceeded the maximum estimated device lifetime",
1132 };
1133
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001134 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001135 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001136 break;
1137 }
1138
1139 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001140 sub = buffer.substr(lifetime, sizeof(hex));
1141 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001142 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1143 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1144 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001145 continue;
1146 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001147 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1148 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1149 ext_device_life_time_est,
1150 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1151 ? ext_device_life_time_est
1152 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001153 }
1154
Felipe Lemed8b94e52016-12-08 10:21:44 -08001155 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001156}