blob: 3153aa56f5ca274a0d1ae66fdbfc4590b48c594d [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/mediacodec", // media.codec
82 "/system/bin/mediadrmserver",
83 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070084 "/system/bin/mediaserver",
85 "/system/bin/sdcard",
86 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070087 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070088 NULL,
89};
90
Felipe Leme7447d7c2016-11-03 18:12:22 -070091// Reasonable value for max stats.
92static const int STATS_MAX_N_RUNS = 1000;
93static const long STATS_MAX_AVERAGE = 100000;
94
Felipe Lemebda15a02016-11-16 17:48:25 -080095CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -070096
Felipe Lemef0292972016-11-22 13:57:05 -080097Dumpstate::Dumpstate(const std::string& version)
98 : pid_(getpid()), version_(version), now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -070099}
100
101Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -0800102 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700103 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700104}
105
Felipe Leme46b85da2016-11-21 17:40:45 -0800106DurationReporter::DurationReporter(const std::string& title, bool log_only)
107 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700108 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800109 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800110 }
111}
112
113DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700114 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800115 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800116 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700117 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800118 } else {
119 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800120 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
121 title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800122 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800123 }
124}
125
Felipe Leme7447d7c2016-11-03 18:12:22 -0700126const int32_t Progress::kDefaultMax = 5000;
127
128Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
129}
130
131Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
132 : Progress(initial_max, growth_factor, "") {
133 progress_ = progress;
134}
135
136Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
137 : initial_max_(initial_max),
138 progress_(0),
139 max_(initial_max),
140 growth_factor_(growth_factor),
141 n_runs_(0),
142 average_max_(0),
143 path_(path) {
144 if (!path_.empty()) {
145 Load();
146 }
147}
148
149void Progress::Load() {
150 MYLOGD("Loading stats from %s\n", path_.c_str());
151 std::string content;
152 if (!android::base::ReadFileToString(path_, &content)) {
153 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
154 return;
155 }
156 if (content.empty()) {
157 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
158 return;
159 }
160 std::vector<std::string> lines = android::base::Split(content, "\n");
161
162 if (lines.size() < 1) {
163 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
164 (int)lines.size(), max_);
165 return;
166 }
167 char* ptr;
168 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
169 average_max_ = strtol(ptr, nullptr, 10);
170 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
171 average_max_ > STATS_MAX_AVERAGE) {
172 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
173 initial_max_ = Progress::kDefaultMax;
174 } else {
175 initial_max_ = average_max_;
176 }
177 max_ = initial_max_;
178
179 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
180}
181
182void Progress::Save() {
183 int32_t total = n_runs_ * average_max_ + progress_;
184 int32_t runs = n_runs_ + 1;
185 int32_t average = floor(((float)total) / runs);
186 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
187 path_.c_str());
188 if (path_.empty()) {
189 return;
190 }
191
192 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
193 if (!android::base::WriteStringToFile(content, path_)) {
194 MYLOGE("Could not save stats on %s\n", path_.c_str());
195 }
196}
197
198int32_t Progress::Get() const {
199 return progress_;
200}
201
202bool Progress::Inc(int32_t delta) {
203 bool changed = false;
204 if (delta >= 0) {
205 progress_ += delta;
206 if (progress_ > max_) {
207 int32_t old_max = max_;
208 max_ = floor((float)progress_ * growth_factor_);
209 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
210 changed = true;
211 }
212 }
213 return changed;
214}
215
216int32_t Progress::GetMax() const {
217 return max_;
218}
219
220int32_t Progress::GetInitialMax() const {
221 return initial_max_;
222}
223
224void Progress::Dump(int fd, const std::string& prefix) const {
225 const char* pr = prefix.c_str();
226 dprintf(fd, "%sprogress: %d\n", pr, progress_);
227 dprintf(fd, "%smax: %d\n", pr, max_);
228 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
229 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
230 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
231 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
232 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
233}
234
Felipe Leme75876a22016-10-27 16:31:27 -0700235bool Dumpstate::IsZipping() const {
236 return zip_writer_ != nullptr;
237}
238
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700239std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700240 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700241 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700242}
243
Felipe Leme7447d7c2016-11-03 18:12:22 -0700244void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
245 progress_ = std::move(progress);
246}
247
John Spurlock5ecd4be2014-01-29 14:14:40 -0500248void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800249 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
250 "for_each_userid(%s)", header);
251 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800252 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700253
John Spurlock5ecd4be2014-01-29 14:14:40 -0500254 DIR *d;
255 struct dirent *de;
256
Felipe Lemed8b94e52016-12-08 10:21:44 -0800257 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500258 func(0);
259
260 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800261 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500262 return;
263 }
264
265 while ((de = readdir(d))) {
266 int userid;
267 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
268 continue;
269 }
270 func(userid);
271 }
272
273 closedir(d);
274}
275
Colin Cross0c22e8b2012-11-02 15:46:56 -0700276static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700277 DIR *d;
278 struct dirent *de;
279
280 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800281 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700282 return;
283 }
284
Felipe Lemed8b94e52016-12-08 10:21:44 -0800285 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700286 while ((de = readdir(d))) {
287 int pid;
288 int fd;
289 char cmdpath[255];
290 char cmdline[255];
291
292 if (!(pid = atoi(de->d_name))) {
293 continue;
294 }
295
Colin Crossf45fa6b2012-03-26 12:38:26 -0700296 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800297
298 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
299 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
300 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700301 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800302 if (cmdline[0]) {
303 helper(pid, cmdline, arg);
304 continue;
305 }
306 }
307
308 // if no cmdline, a kernel thread has comm
309 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
310 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
311 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
312 close(fd);
313 if (cmdline[1]) {
314 cmdline[0] = '[';
315 size_t len = strcspn(cmdline, "\f\b\r\n");
316 cmdline[len] = ']';
317 cmdline[len+1] = '\0';
318 }
319 }
320 if (!cmdline[0]) {
321 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700322 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700323 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700324 }
325
326 closedir(d);
327}
328
Colin Cross0c22e8b2012-11-02 15:46:56 -0700329static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800330 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700331 func(pid, cmdline);
332}
333
334void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800335 std::string title = header == nullptr ? "for_each_pid"
336 : android::base::StringPrintf("for_each_pid(%s)", header);
337 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800338 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700339
Felipe Leme515eb0d2015-12-14 15:09:56 -0800340 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700341}
342
343static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
344 DIR *d;
345 struct dirent *de;
346 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800347 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700348
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700349 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700350
351 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800352 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700353 return;
354 }
355
356 func(pid, pid, cmdline);
357
358 while ((de = readdir(d))) {
359 int tid;
360 int fd;
361 char commpath[255];
362 char comm[255];
363
364 if (!(tid = atoi(de->d_name))) {
365 continue;
366 }
367
368 if (tid == pid)
369 continue;
370
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700371 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800372 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700373 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700374 strcpy(comm, "N/A");
375 } else {
376 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800377 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700378 close(fd);
379
380 c = strrchr(comm, '\n');
381 if (c) {
382 *c = '\0';
383 }
384 }
385 func(pid, tid, comm);
386 }
387
388 closedir(d);
389}
390
391void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800392 std::string title = header == nullptr ? "for_each_tid"
393 : android::base::StringPrintf("for_each_tid(%s)", header);
394 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800395
Felipe Lemef0292972016-11-22 13:57:05 -0800396 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700397
Felipe Leme8620bb42015-11-10 11:04:45 -0800398 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700399}
400
401void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800402 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700403
Colin Crossf45fa6b2012-03-26 12:38:26 -0700404 char path[255];
405 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800406 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700407 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700408
409 memset(buffer, 0, sizeof(buffer));
410
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700411 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700412 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800413 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700414 return;
415 }
416
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800417 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
418 save_errno = errno;
419 close(fd);
420
421 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800422 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800423 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700424 }
425
Colin Cross0c22e8b2012-11-02 15:46:56 -0700426 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
427 pid == tid ? 0 : 3, "", name);
428
Felipe Lemed8b94e52016-12-08 10:21:44 -0800429 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700430
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800431 return;
432}
433
434// print time in centiseconds
435static void snprcent(char *buffer, size_t len, size_t spc,
436 unsigned long long time) {
437 static long hz; // cache discovered hz
438
439 if (hz <= 0) {
440 hz = sysconf(_SC_CLK_TCK);
441 if (hz <= 0) {
442 hz = 1000;
443 }
444 }
445
446 // convert to centiseconds
447 time = (time * 100 + (hz / 2)) / hz;
448
449 char str[16];
450
451 snprintf(str, sizeof(str), " %llu.%02u",
452 time / 100, (unsigned)(time % 100));
453 size_t offset = strlen(buffer);
454 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
455 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
456}
457
458// print permille as a percent
459static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
460 char str[16];
461
462 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
463 size_t offset = strlen(buffer);
464 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
465 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
466}
467
468void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800469 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700470
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800471 char path[255];
472 char buffer[1023];
473 int fd, ret, save_errno;
474
475 memset(buffer, 0, sizeof(buffer));
476
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700477 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800478 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800479 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800480 return;
481 }
482
483 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
484 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700485 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800486
487 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800488 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800489 return;
490 }
491
492 // field 14 is utime
493 // field 15 is stime
494 // field 42 is iotime
495 unsigned long long utime = 0, stime = 0, iotime = 0;
496 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800497 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
498 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
499 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
500 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800501 &utime, &stime, &iotime) != 3) {
502 return;
503 }
504
505 unsigned long long total = utime + stime;
506 if (!total) {
507 return;
508 }
509
510 unsigned permille = (iotime * 1000 + (total / 2)) / total;
511 if (permille > 1000) {
512 permille = 1000;
513 }
514
515 // try to beautify and stabilize columns at <80 characters
516 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
517 if ((name[0] != '[') || utime) {
518 snprcent(buffer, sizeof(buffer), 57, utime);
519 }
520 snprcent(buffer, sizeof(buffer), 65, stime);
521 if ((name[0] != '[') || iotime) {
522 snprcent(buffer, sizeof(buffer), 73, iotime);
523 }
524 if (iotime) {
525 snprdec(buffer, sizeof(buffer), 79, permille);
526 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800527 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800528
Colin Crossf45fa6b2012-03-26 12:38:26 -0700529 return;
530}
531
532void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800533 const char *title = "KERNEL LOG (dmesg)";
534 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800535 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800536
Felipe Lemef0292972016-11-22 13:57:05 -0800537 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700538
Elliott Hughes5f87b312012-09-17 11:43:40 -0700539 /* Get size of kernel buffer */
540 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700541 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800542 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700543 return;
544 }
545 char *buf = (char *) malloc(size + 1);
546 if (buf == NULL) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800547 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700548 return;
549 }
550 int retval = klogctl(KLOG_READ_ALL, buf, size);
551 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800552 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700553 free(buf);
554 return;
555 }
556 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800557 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700558 free(buf);
559 return;
560}
561
562void do_showmap(int pid, const char *name) {
563 char title[255];
564 char arg[255];
565
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700566 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
567 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800568 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800569}
570
Felipe Leme678727a2016-09-21 17:22:11 -0700571int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700572 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800573
Felipe Lemef0292972016-11-22 13:57:05 -0800574 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800575
Felipe Lemef0292972016-11-22 13:57:05 -0800576 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800577
Felipe Leme46b85da2016-11-21 17:40:45 -0800578 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800579}
580
Felipe Leme71a74ac2016-03-17 15:43:25 -0700581int read_file_as_long(const char *path, long int *output) {
582 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
583 if (fd < 0) {
584 int err = errno;
585 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
586 return -1;
587 }
588 char buffer[50];
589 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
590 if (bytes_read == -1) {
591 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
592 return -2;
593 }
594 if (bytes_read == 0) {
595 MYLOGE("File %s is empty\n", path);
596 return -3;
597 }
598 *output = atoi(buffer);
599 return 0;
600}
601
Mark Salyzyn326842f2015-04-30 09:49:41 -0700602/* calls skip to gate calling dump_from_fd recursively
603 * in the specified directory. dump_from_fd defaults to
604 * dump_file_from_fd above when set to NULL. skip defaults
605 * to false when set to NULL. dump_from_fd will always be
606 * called with title NULL.
607 */
Felipe Leme678727a2016-09-21 17:22:11 -0700608int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
609 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800610 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700611 DIR *dirp;
612 struct dirent *d;
613 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800614 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700615 int fd, retval = 0;
616
Felipe Leme678727a2016-09-21 17:22:11 -0700617 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800618 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700619 }
Felipe Lemef0292972016-11-22 13:57:05 -0800620 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700621
622 if (dir[strlen(dir) - 1] == '/') {
623 ++slash;
624 }
625 dirp = opendir(dir);
626 if (dirp == NULL) {
627 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800628 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700629 return retval;
630 }
631
632 if (!dump_from_fd) {
633 dump_from_fd = dump_file_from_fd;
634 }
635 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
636 if ((d->d_name[0] == '.')
637 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
638 || (d->d_name[1] == '\0'))) {
639 continue;
640 }
641 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
642 (d->d_type == DT_DIR) ? "/" : "");
643 if (!newpath) {
644 retval = -errno;
645 continue;
646 }
647 if (skip && (*skip)(newpath)) {
648 continue;
649 }
650 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700651 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700652 if (ret < 0) {
653 retval = ret;
654 }
655 continue;
656 }
657 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
658 if (fd < 0) {
659 retval = fd;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800660 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700661 continue;
662 }
663 (*dump_from_fd)(NULL, newpath, fd);
664 }
665 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700666 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800667 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700668 }
669 return retval;
670}
671
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800672/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
673 * it's possible to avoid issues where opening the file itself can get
674 * stuck.
675 */
676int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800677 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700678
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800679 int flags = fcntl(fd, F_GETFL);
680 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800681 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800682 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800683 return -1;
684 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800685 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800686 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800687 return -1;
688 }
Felipe Lemef0292972016-11-22 13:57:05 -0800689 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700690}
691
Felipe Leme46b85da2016-11-21 17:40:45 -0800692int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
693 const CommandOptions& options) {
694 DurationReporter duration_reporter(title);
695
Felipe Lemef0292972016-11-22 13:57:05 -0800696 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800697
Felipe Lemef0292972016-11-22 13:57:05 -0800698 /* TODO: for now we're simplifying the progress calculation by using the
699 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
700 * where its weight should be much higher proportionally to its timeout.
701 * Ideally, it should use a options.EstimatedDuration() instead...*/
702 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800703
Felipe Leme46b85da2016-11-21 17:40:45 -0800704 return status;
705}
706
Felipe Leme9a523ae2016-10-20 15:10:33 -0700707void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700708 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700709 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
710 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700711 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700712 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700713}
714
Felipe Leme2628e9e2016-04-12 16:36:51 -0700715int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700716 int s = android_get_control_socket(service);
717 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800718 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700719 exit(1);
720 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700721 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700722 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800723 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700724 exit(1);
725 }
726
727 struct sockaddr addr;
728 socklen_t alen = sizeof(addr);
729 int fd = accept(s, &addr, &alen);
730 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800731 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700732 exit(1);
733 }
734
Felipe Leme2628e9e2016-04-12 16:36:51 -0700735 return fd;
736}
737
738/* redirect output to a service control socket */
739void redirect_to_socket(FILE *redirect, const char *service) {
740 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700741 fflush(redirect);
742 dup2(fd, fileno(redirect));
743 close(fd);
744}
745
Felipe Leme2628e9e2016-04-12 16:36:51 -0700746// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800747void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800748 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700749
750 /* skip initial slash */
751 if (chp[0] == '/')
752 chp++;
753
754 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800755 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700756 while (chp && chp[0]) {
757 chp = strchr(chp, '/');
758 if (chp) {
759 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800760 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800761 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800762 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800763 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800764 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800765 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800766 }
767 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700768 *chp++ = '/';
769 }
770 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800771}
772
Felipe Leme0f3fb202016-06-10 17:10:53 -0700773void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800774 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700775
Felipe Leme0f3fb202016-06-10 17:10:53 -0700776 int fd = TEMP_FAILURE_RETRY(open(path,
777 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800778 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700779 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800780 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700781 exit(1);
782 }
783
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800784 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700785 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700786}
787
Felipe Leme0f3fb202016-06-10 17:10:53 -0700788void redirect_to_file(FILE *redirect, char *path) {
789 _redirect_to_file(redirect, path, O_TRUNC);
790}
791
792void redirect_to_existing_file(FILE *redirect, char *path) {
793 _redirect_to_file(redirect, path, O_APPEND);
794}
795
Jeff Brownbf7f4922012-06-07 16:40:01 -0700796static bool should_dump_native_traces(const char* path) {
797 for (const char** p = native_processes_to_dump; *p; p++) {
798 if (!strcmp(*p, path)) {
799 return true;
800 }
801 }
802 return false;
803}
804
805/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
806const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -0700807 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -0700808
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700809 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -0700810
Felipe Lemee184f662016-10-27 10:04:47 -0700811 std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
812 if (traces_path.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700813
814 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -0700815 std::string anrtraces_path = traces_path + ".anr";
816 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
817 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700818 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -0700819 }
820
Colin Crossf45fa6b2012-03-26 12:38:26 -0700821 /* create a new, empty traces.txt file to receive stack dumps */
Josh Gao989b8122017-01-13 22:09:40 -0800822 int fd = TEMP_FAILURE_RETRY(
Josh Gaoe75d9632017-01-18 16:14:03 -0800823 open(traces_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
Josh Gao989b8122017-01-13 22:09:40 -0800824 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -0700825 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700826 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700827 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700828 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700829 int chmod_ret = fchmod(fd, 0666);
830 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700831 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700832 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700833 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -0700834 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700835
Felipe Leme8620bb42015-11-10 11:04:45 -0800836 /* Variables below must be initialized before 'goto' statements */
837 int dalvik_found = 0;
838 int ifd, wfd = -1;
839
Colin Crossf45fa6b2012-03-26 12:38:26 -0700840 /* walk /proc and kill -QUIT all Dalvik processes */
841 DIR *proc = opendir("/proc");
842 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800843 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700844 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700845 }
846
847 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -0800848 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700849 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800850 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700851 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700852 }
853
Felipe Lemee184f662016-10-27 10:04:47 -0700854 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700855 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -0700856 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700857 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700858 }
859
860 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700861 while ((d = readdir(proc))) {
862 int pid = atoi(d->d_name);
863 if (pid <= 0) continue;
864
Jeff Brownbf7f4922012-06-07 16:40:01 -0700865 char path[PATH_MAX];
866 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700867 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700868 ssize_t len = readlink(path, data, sizeof(data) - 1);
869 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700870 continue;
871 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700872 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -0700873
Colin Cross0d6180f2014-07-16 19:00:46 -0700874 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700875 /* skip zygote -- it won't dump its stack anyway */
876 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700877 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700878 len = read(cfd, data, sizeof(data) - 1);
879 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700880 if (len <= 0) {
881 continue;
882 }
883 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -0700884 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -0700885 continue;
886 }
887
888 ++dalvik_found;
Felipe Lemef0292972016-11-22 13:57:05 -0800889 uint64_t start = Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -0700890 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800891 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700892 continue;
893 }
894
895 /* wait for the writable-close notification from inotify */
896 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -0700897 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700898 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800899 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700900 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800901 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700902 } else {
903 struct inotify_event ie;
904 read(ifd, &ie, sizeof(ie));
905 }
Jeff Brown1dc94e32014-09-11 14:15:27 -0700906
907 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800908 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -0700909 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700910 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -0800911 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700912 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700913 } else if (should_dump_native_traces(data)) {
914 /* dump native process if appropriate */
915 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800916 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700917 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -0800918 static uint16_t timeout_failures = 0;
Felipe Lemef0292972016-11-22 13:57:05 -0800919 uint64_t start = Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -0800920
921 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
922 if (timeout_failures == 3) {
923 dprintf(fd, "too many stack dump failures, skipping...\n");
924 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
925 dprintf(fd, "dumping failed, likely due to a timeout\n");
926 timeout_failures++;
927 } else {
928 timeout_failures = 0;
929 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700930 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -0800931 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -0700932 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700933 }
934 }
935
Colin Crossf45fa6b2012-03-26 12:38:26 -0700936 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800937 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700938 }
939
Felipe Lemee184f662016-10-27 10:04:47 -0700940 static std::string dumptraces_path = android::base::StringPrintf(
941 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
942 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
943 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
944 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -0700945 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700946 }
Felipe Lemee184f662016-10-27 10:04:47 -0700947 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700948
949 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -0700950 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -0700951
952error_close_ifd:
953 close(ifd);
954error_close_fd:
955 close(fd);
956 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700957}
958
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700959void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800960 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -0800961 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700962 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -0700963 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700964 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700965 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800966 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700967 return;
968 }
969 char table[16];
970 // Each line has an integer (the table number), a space, and a string (the table name). We only
971 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
972 // Add a fixed max limit so this doesn't go awry.
973 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700974 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
975 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700976 }
977 fclose(fp);
978}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800979
Felipe Leme71bbfc52015-11-23 14:14:51 -0800980// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700981void Dumpstate::UpdateProgress(int32_t delta) {
982 if (progress_ == nullptr) {
983 MYLOGE("UpdateProgress: progress_ not set\n");
984 return;
985 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800986
Felipe Leme7447d7c2016-11-03 18:12:22 -0700987 // Always update progess so stats can be tuned...
988 bool max_changed = progress_->Inc(delta);
989
990 // ...but only notifiy listeners when necessary.
991 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800992
Felipe Leme009ecbb2016-11-07 10:18:44 -0800993 int progress = progress_->Get();
994 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -0800995
996 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -0800997 if (max_changed && listener_ != nullptr) {
998 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -0800999 }
1000
Felipe Leme009ecbb2016-11-07 10:18:44 -08001001 int32_t last_update_delta = progress - last_updated_progress_;
1002 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1003 return;
1004 }
1005 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001006
Felipe Leme9a523ae2016-10-20 15:10:33 -07001007 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001008 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001009 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001010 }
1011
Felipe Leme75876a22016-10-27 16:31:27 -07001012 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001013 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001014 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001015 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001016 } else {
1017 // stderr is ignored on normal invocations, but useful when calling
1018 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001019 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001020 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001021 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001022 }
1023}
Felipe Lemee338bf62015-12-07 14:03:50 -08001024
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001025void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001026 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001027 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001028 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001029 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1030 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001031 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001032 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001033 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001034 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001035}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001036
Felipe Leme0c80cf02016-01-05 13:25:34 -08001037bool is_dir(const char* pathname) {
1038 struct stat info;
1039 if (stat(pathname, &info) == -1) {
1040 return false;
1041 }
1042 return S_ISDIR(info.st_mode);
1043}
1044
1045time_t get_mtime(int fd, time_t default_mtime) {
1046 struct stat info;
1047 if (fstat(fd, &info) == -1) {
1048 return default_mtime;
1049 }
1050 return info.st_mtime;
1051}
1052
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001053void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001054 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001055 struct hex {
1056 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001057 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001058 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1059 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1060 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1061 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1062
1063 std::string buffer;
1064 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1065 return;
1066 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001067
Felipe Lemed8b94e52016-12-08 10:21:44 -08001068 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001069
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001070 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001071 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001072 return;
1073 }
1074
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001075 int ext_csd_rev = 0;
1076 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1077 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001078 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001079 return;
1080 }
1081
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001082 static const char *ver_str[] = {
1083 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1084 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001085 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1086 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1087 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001088 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001089 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001090 return;
1091 }
1092
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001093 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001094 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001095 return;
1096 }
1097
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001098 int ext_pre_eol_info = 0;
1099 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1100 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001101 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001102 return;
1103 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001104
1105 static const char *eol_str[] = {
1106 "Undefined",
1107 "Normal",
1108 "Warning (consumed 80% of reserve)",
1109 "Urgent (consumed 90% of reserve)"
1110 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001111 printf(
1112 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -08001113 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1114 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001115
1116 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1117 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001118 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001119 int ext_device_life_time_est;
1120 static const char *est_str[] = {
1121 "Undefined",
1122 "0-10% of device lifetime used",
1123 "10-20% of device lifetime used",
1124 "20-30% of device lifetime used",
1125 "30-40% of device lifetime used",
1126 "40-50% of device lifetime used",
1127 "50-60% of device lifetime used",
1128 "60-70% of device lifetime used",
1129 "70-80% of device lifetime used",
1130 "80-90% of device lifetime used",
1131 "90-100% of device lifetime used",
1132 "Exceeded the maximum estimated device lifetime",
1133 };
1134
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001135 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001136 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001137 break;
1138 }
1139
1140 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001141 sub = buffer.substr(lifetime, sizeof(hex));
1142 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001143 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1144 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1145 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001146 continue;
1147 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001148 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1149 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1150 ext_device_life_time_est,
1151 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1152 ? ext_device_life_time_est
1153 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001154 }
1155
Felipe Lemed8b94e52016-12-08 10:21:44 -08001156 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001157}