blob: 2224b3d8cb31da9904e48778062f2a98c89d8ae9 [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Felipe Lemef0292972016-11-22 13:57:05 -080017#define LOG_TAG "dumpstate"
18
19#include "dumpstate.h"
20
Colin Crossf45fa6b2012-03-26 12:38:26 -070021#include <dirent.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070022#include <fcntl.h>
Felipe Lemee184f662016-10-27 10:04:47 -070023#include <libgen.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070024#include <math.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070025#include <poll.h>
26#include <signal.h>
27#include <stdarg.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080031#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/inotify.h>
Felipe Lemee184f662016-10-27 10:04:47 -070033#include <sys/klog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070034#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070035#include <sys/stat.h>
36#include <sys/time.h>
37#include <sys/wait.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038#include <time.h>
39#include <unistd.h>
Mark Salyzyn261a7332016-05-24 12:38:40 -070040
Narayan Kamath8f788292017-05-25 13:20:39 +010041#include <memory>
Steven Moreland17b29e12017-03-21 18:38:05 -070042#include <set>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070043#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080044#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070045
Mark Salyzyn290f4b92016-05-16 08:33:59 -070046#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070047#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070048#include <android-base/stringprintf.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070049#include <android-base/strings.h>
Narayan Kamath8f788292017-05-25 13:20:39 +010050#include <android-base/unique_fd.h>
Steven Moreland17b29e12017-03-21 18:38:05 -070051#include <android/hidl/manager/1.0/IServiceManager.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070052#include <cutils/properties.h>
53#include <cutils/sockets.h>
Josh Gaod2db0242017-01-05 18:27:33 -080054#include <debuggerd/client.h>
Mark Salyzyn4eb13822017-01-12 13:57:51 -080055#include <log/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070056#include <private/android_filesystem_config.h>
57
Felipe Lemef0292972016-11-22 13:57:05 -080058#include "DumpstateInternal.h"
Jeff Brown1dc94e32014-09-11 14:15:27 -070059
Felipe Leme47e9be22016-12-21 15:37:07 -080060// TODO: remove once moved to namespace
61using android::os::dumpstate::CommandOptions;
62using android::os::dumpstate::DumpFileToFd;
63using android::os::dumpstate::PropertiesHelper;
64
Brian Carlstroma3322752017-03-19 17:48:01 -070065// Keep in sync with
66// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
Felipe Leme61884122016-06-13 09:23:30 -070067static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
68
Felipe Lemef0292972016-11-22 13:57:05 -080069/* Most simple commands have 10 as timeout, so 5 is a good estimate */
70static const int32_t WEIGHT_FILE = 5;
71
Felipe Lemee844a9d2016-09-21 15:01:39 -070072// TODO: temporary variables and functions used during C++ refactoring
73static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070074static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070075 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070076 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070077}
Felipe Lemee844a9d2016-09-21 15:01:39 -070078
Jeff Brownbf7f4922012-06-07 16:40:01 -070079/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070080// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070081static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080082 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080083 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070084 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070085 "/system/bin/mediadrmserver",
86 "/system/bin/mediaextractor", // media.extractor
Andy Hung756655c2018-01-04 12:09:50 -080087 "/system/bin/mediametrics", // media.metrics
Jeff Brownbf7f4922012-06-07 16:40:01 -070088 "/system/bin/mediaserver",
89 "/system/bin/sdcard",
Andreas Gampea3127a72018-01-24 17:55:55 -080090 "/system/bin/statsd",
Jeff Brownbf7f4922012-06-07 16:40:01 -070091 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070092 "/system/bin/vehicle_network_service",
Chong Zhangde00ee42017-06-02 16:13:16 -070093 "/vendor/bin/hw/android.hardware.media.omx@1.0-service", // media.codec
Jeff Brownbf7f4922012-06-07 16:40:01 -070094 NULL,
95};
96
Steven Moreland17b29e12017-03-21 18:38:05 -070097/* list of hal interface to dump containing process during native dumps */
98static const char* hal_interfaces_to_dump[] {
99 "android.hardware.audio@2.0::IDevicesFactory",
100 "android.hardware.bluetooth@1.0::IBluetoothHci",
101 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu108c0f02017-04-20 14:31:50 -0700102 "android.hardware.graphics.composer@2.1::IComposer",
Steven Moreland17b29e12017-03-21 18:38:05 -0700103 "android.hardware.media.omx@1.0::IOmx",
Peng Xuf1ab0ac2017-07-11 21:14:42 -0700104 "android.hardware.sensors@1.0::ISensors",
105 "android.hardware.vr@1.0::IVr",
Steven Moreland17b29e12017-03-21 18:38:05 -0700106 NULL,
107};
108
Felipe Leme7447d7c2016-11-03 18:12:22 -0700109// Reasonable value for max stats.
110static const int STATS_MAX_N_RUNS = 1000;
111static const long STATS_MAX_AVERAGE = 100000;
112
Felipe Lemebda15a02016-11-16 17:48:25 -0800113CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -0700114
Felipe Lemef0292972016-11-22 13:57:05 -0800115Dumpstate::Dumpstate(const std::string& version)
116 : pid_(getpid()), version_(version), now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700117}
118
119Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -0800120 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700121 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700122}
123
Felipe Leme46b85da2016-11-21 17:40:45 -0800124DurationReporter::DurationReporter(const std::string& title, bool log_only)
125 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700126 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800127 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800128 }
129}
130
131DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700132 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800133 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800134 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700135 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800136 } else {
137 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800138 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
139 title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800140 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800141 }
142}
143
Felipe Leme7447d7c2016-11-03 18:12:22 -0700144const int32_t Progress::kDefaultMax = 5000;
145
146Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
147}
148
149Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
150 : Progress(initial_max, growth_factor, "") {
151 progress_ = progress;
152}
153
154Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
155 : initial_max_(initial_max),
156 progress_(0),
157 max_(initial_max),
158 growth_factor_(growth_factor),
159 n_runs_(0),
160 average_max_(0),
161 path_(path) {
162 if (!path_.empty()) {
163 Load();
164 }
165}
166
167void Progress::Load() {
168 MYLOGD("Loading stats from %s\n", path_.c_str());
169 std::string content;
170 if (!android::base::ReadFileToString(path_, &content)) {
171 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
172 return;
173 }
174 if (content.empty()) {
175 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
176 return;
177 }
178 std::vector<std::string> lines = android::base::Split(content, "\n");
179
180 if (lines.size() < 1) {
181 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
182 (int)lines.size(), max_);
183 return;
184 }
185 char* ptr;
186 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
187 average_max_ = strtol(ptr, nullptr, 10);
188 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
189 average_max_ > STATS_MAX_AVERAGE) {
190 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
191 initial_max_ = Progress::kDefaultMax;
192 } else {
193 initial_max_ = average_max_;
194 }
195 max_ = initial_max_;
196
197 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
198}
199
200void Progress::Save() {
201 int32_t total = n_runs_ * average_max_ + progress_;
202 int32_t runs = n_runs_ + 1;
203 int32_t average = floor(((float)total) / runs);
204 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
205 path_.c_str());
206 if (path_.empty()) {
207 return;
208 }
209
210 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
211 if (!android::base::WriteStringToFile(content, path_)) {
212 MYLOGE("Could not save stats on %s\n", path_.c_str());
213 }
214}
215
216int32_t Progress::Get() const {
217 return progress_;
218}
219
Vishnu Nair6921f802017-11-22 09:17:23 -0800220bool Progress::Inc(int32_t delta_sec) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700221 bool changed = false;
Vishnu Nair6921f802017-11-22 09:17:23 -0800222 if (delta_sec >= 0) {
223 progress_ += delta_sec;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700224 if (progress_ > max_) {
225 int32_t old_max = max_;
226 max_ = floor((float)progress_ * growth_factor_);
227 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
228 changed = true;
229 }
230 }
231 return changed;
232}
233
234int32_t Progress::GetMax() const {
235 return max_;
236}
237
238int32_t Progress::GetInitialMax() const {
239 return initial_max_;
240}
241
242void Progress::Dump(int fd, const std::string& prefix) const {
243 const char* pr = prefix.c_str();
244 dprintf(fd, "%sprogress: %d\n", pr, progress_);
245 dprintf(fd, "%smax: %d\n", pr, max_);
246 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
247 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
248 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
249 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
250 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
251}
252
Felipe Leme75876a22016-10-27 16:31:27 -0700253bool Dumpstate::IsZipping() const {
254 return zip_writer_ != nullptr;
255}
256
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700257std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700258 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700259 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700260}
261
Vishnu Nair780b1282017-10-10 13:57:24 -0700262bool Dumpstate::CurrentVersionSupportsPriorityDumps() const {
263 return (version_ == VERSION_PRIORITY_DUMPS);
264}
265
Felipe Leme7447d7c2016-11-03 18:12:22 -0700266void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
267 progress_ = std::move(progress);
268}
269
John Spurlock5ecd4be2014-01-29 14:14:40 -0500270void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800271 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
272 "for_each_userid(%s)", header);
273 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800274 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700275
John Spurlock5ecd4be2014-01-29 14:14:40 -0500276 DIR *d;
277 struct dirent *de;
278
Felipe Lemed8b94e52016-12-08 10:21:44 -0800279 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500280 func(0);
281
282 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800283 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500284 return;
285 }
286
287 while ((de = readdir(d))) {
288 int userid;
289 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
290 continue;
291 }
292 func(userid);
293 }
294
295 closedir(d);
296}
297
Colin Cross0c22e8b2012-11-02 15:46:56 -0700298static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700299 DIR *d;
300 struct dirent *de;
301
302 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800303 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700304 return;
305 }
306
Felipe Lemed8b94e52016-12-08 10:21:44 -0800307 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700308 while ((de = readdir(d))) {
309 int pid;
310 int fd;
311 char cmdpath[255];
312 char cmdline[255];
313
314 if (!(pid = atoi(de->d_name))) {
315 continue;
316 }
317
Colin Crossf45fa6b2012-03-26 12:38:26 -0700318 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800319
320 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
321 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
322 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700323 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800324 if (cmdline[0]) {
325 helper(pid, cmdline, arg);
326 continue;
327 }
328 }
329
330 // if no cmdline, a kernel thread has comm
331 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
332 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
333 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
334 close(fd);
335 if (cmdline[1]) {
336 cmdline[0] = '[';
337 size_t len = strcspn(cmdline, "\f\b\r\n");
338 cmdline[len] = ']';
339 cmdline[len+1] = '\0';
340 }
341 }
342 if (!cmdline[0]) {
343 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700344 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700345 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700346 }
347
348 closedir(d);
349}
350
Colin Cross0c22e8b2012-11-02 15:46:56 -0700351static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800352 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700353 func(pid, cmdline);
354}
355
356void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800357 std::string title = header == nullptr ? "for_each_pid"
358 : android::base::StringPrintf("for_each_pid(%s)", header);
359 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800360 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700361
Felipe Leme515eb0d2015-12-14 15:09:56 -0800362 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700363}
364
365static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
366 DIR *d;
367 struct dirent *de;
368 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800369 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700370
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700371 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700372
373 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800374 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700375 return;
376 }
377
378 func(pid, pid, cmdline);
379
380 while ((de = readdir(d))) {
381 int tid;
382 int fd;
383 char commpath[255];
384 char comm[255];
385
386 if (!(tid = atoi(de->d_name))) {
387 continue;
388 }
389
390 if (tid == pid)
391 continue;
392
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700393 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800394 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700395 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700396 strcpy(comm, "N/A");
397 } else {
398 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800399 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700400 close(fd);
401
402 c = strrchr(comm, '\n');
403 if (c) {
404 *c = '\0';
405 }
406 }
407 func(pid, tid, comm);
408 }
409
410 closedir(d);
411}
412
413void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800414 std::string title = header == nullptr ? "for_each_tid"
415 : android::base::StringPrintf("for_each_tid(%s)", header);
416 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800417
Felipe Lemef0292972016-11-22 13:57:05 -0800418 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700419
Felipe Leme8620bb42015-11-10 11:04:45 -0800420 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700421}
422
423void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800424 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700425
Colin Crossf45fa6b2012-03-26 12:38:26 -0700426 char path[255];
427 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800428 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700429 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700430
431 memset(buffer, 0, sizeof(buffer));
432
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700433 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700434 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800435 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700436 return;
437 }
438
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800439 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
440 save_errno = errno;
441 close(fd);
442
443 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800444 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800445 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700446 }
447
Colin Cross0c22e8b2012-11-02 15:46:56 -0700448 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
449 pid == tid ? 0 : 3, "", name);
450
Felipe Lemed8b94e52016-12-08 10:21:44 -0800451 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700452
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800453 return;
454}
455
456// print time in centiseconds
457static void snprcent(char *buffer, size_t len, size_t spc,
458 unsigned long long time) {
459 static long hz; // cache discovered hz
460
461 if (hz <= 0) {
462 hz = sysconf(_SC_CLK_TCK);
463 if (hz <= 0) {
464 hz = 1000;
465 }
466 }
467
468 // convert to centiseconds
469 time = (time * 100 + (hz / 2)) / hz;
470
471 char str[16];
472
473 snprintf(str, sizeof(str), " %llu.%02u",
474 time / 100, (unsigned)(time % 100));
475 size_t offset = strlen(buffer);
476 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
477 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
478}
479
480// print permille as a percent
481static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
482 char str[16];
483
484 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
485 size_t offset = strlen(buffer);
486 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
487 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
488}
489
490void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800491 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700492
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800493 char path[255];
494 char buffer[1023];
495 int fd, ret, save_errno;
496
497 memset(buffer, 0, sizeof(buffer));
498
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700499 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800500 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800501 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800502 return;
503 }
504
505 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
506 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700507 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800508
509 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800510 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800511 return;
512 }
513
514 // field 14 is utime
515 // field 15 is stime
516 // field 42 is iotime
517 unsigned long long utime = 0, stime = 0, iotime = 0;
518 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800519 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
520 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
521 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
522 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800523 &utime, &stime, &iotime) != 3) {
524 return;
525 }
526
527 unsigned long long total = utime + stime;
528 if (!total) {
529 return;
530 }
531
532 unsigned permille = (iotime * 1000 + (total / 2)) / total;
533 if (permille > 1000) {
534 permille = 1000;
535 }
536
537 // try to beautify and stabilize columns at <80 characters
538 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
539 if ((name[0] != '[') || utime) {
540 snprcent(buffer, sizeof(buffer), 57, utime);
541 }
542 snprcent(buffer, sizeof(buffer), 65, stime);
543 if ((name[0] != '[') || iotime) {
544 snprcent(buffer, sizeof(buffer), 73, iotime);
545 }
546 if (iotime) {
547 snprdec(buffer, sizeof(buffer), 79, permille);
548 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800549 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800550
Colin Crossf45fa6b2012-03-26 12:38:26 -0700551 return;
552}
553
554void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800555 const char *title = "KERNEL LOG (dmesg)";
556 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800557 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800558
Felipe Lemef0292972016-11-22 13:57:05 -0800559 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700560
Elliott Hughes5f87b312012-09-17 11:43:40 -0700561 /* Get size of kernel buffer */
562 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700563 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800564 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700565 return;
566 }
567 char *buf = (char *) malloc(size + 1);
568 if (buf == NULL) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800569 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700570 return;
571 }
572 int retval = klogctl(KLOG_READ_ALL, buf, size);
573 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800574 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700575 free(buf);
576 return;
577 }
578 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800579 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700580 free(buf);
581 return;
582}
583
584void do_showmap(int pid, const char *name) {
585 char title[255];
586 char arg[255];
587
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700588 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
589 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800590 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800591}
592
Felipe Leme678727a2016-09-21 17:22:11 -0700593int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700594 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800595
Felipe Lemef0292972016-11-22 13:57:05 -0800596 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800597
Felipe Lemef0292972016-11-22 13:57:05 -0800598 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800599
Felipe Leme46b85da2016-11-21 17:40:45 -0800600 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800601}
602
Felipe Leme71a74ac2016-03-17 15:43:25 -0700603int read_file_as_long(const char *path, long int *output) {
604 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
605 if (fd < 0) {
606 int err = errno;
607 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
608 return -1;
609 }
610 char buffer[50];
611 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
612 if (bytes_read == -1) {
613 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
614 return -2;
615 }
616 if (bytes_read == 0) {
617 MYLOGE("File %s is empty\n", path);
618 return -3;
619 }
620 *output = atoi(buffer);
621 return 0;
622}
623
Mark Salyzyn326842f2015-04-30 09:49:41 -0700624/* calls skip to gate calling dump_from_fd recursively
625 * in the specified directory. dump_from_fd defaults to
626 * dump_file_from_fd above when set to NULL. skip defaults
627 * to false when set to NULL. dump_from_fd will always be
628 * called with title NULL.
629 */
Felipe Leme678727a2016-09-21 17:22:11 -0700630int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
631 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800632 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700633 DIR *dirp;
634 struct dirent *d;
635 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800636 const char *slash = "/";
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100637 int retval = 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700638
Felipe Leme678727a2016-09-21 17:22:11 -0700639 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800640 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700641 }
Felipe Lemef0292972016-11-22 13:57:05 -0800642 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700643
644 if (dir[strlen(dir) - 1] == '/') {
645 ++slash;
646 }
647 dirp = opendir(dir);
648 if (dirp == NULL) {
649 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800650 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700651 return retval;
652 }
653
654 if (!dump_from_fd) {
655 dump_from_fd = dump_file_from_fd;
656 }
657 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
658 if ((d->d_name[0] == '.')
659 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
660 || (d->d_name[1] == '\0'))) {
661 continue;
662 }
663 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
664 (d->d_type == DT_DIR) ? "/" : "");
665 if (!newpath) {
666 retval = -errno;
667 continue;
668 }
669 if (skip && (*skip)(newpath)) {
670 continue;
671 }
672 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700673 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700674 if (ret < 0) {
675 retval = ret;
676 }
677 continue;
678 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100679 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
680 if (fd.get() < 0) {
681 retval = -1;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800682 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700683 continue;
684 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100685 (*dump_from_fd)(NULL, newpath, fd.get());
Mark Salyzyn326842f2015-04-30 09:49:41 -0700686 }
687 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700688 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800689 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700690 }
691 return retval;
692}
693
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800694/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
695 * it's possible to avoid issues where opening the file itself can get
696 * stuck.
697 */
698int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800699 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700700
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800701 int flags = fcntl(fd, F_GETFL);
702 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800703 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800704 return -1;
705 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800706 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800707 return -1;
708 }
Felipe Lemef0292972016-11-22 13:57:05 -0800709 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700710}
711
Felipe Leme46b85da2016-11-21 17:40:45 -0800712int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
713 const CommandOptions& options) {
714 DurationReporter duration_reporter(title);
715
Felipe Lemef0292972016-11-22 13:57:05 -0800716 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800717
Felipe Lemef0292972016-11-22 13:57:05 -0800718 /* TODO: for now we're simplifying the progress calculation by using the
719 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
720 * where its weight should be much higher proportionally to its timeout.
721 * Ideally, it should use a options.EstimatedDuration() instead...*/
722 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800723
Felipe Leme46b85da2016-11-21 17:40:45 -0800724 return status;
725}
726
Felipe Leme9a523ae2016-10-20 15:10:33 -0700727void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Vishnu Nair6921f802017-11-22 09:17:23 -0800728 const CommandOptions& options, long dumpsysTimeoutMs) {
729 long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
730 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700731 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700732 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700733}
734
Felipe Leme2628e9e2016-04-12 16:36:51 -0700735int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700736 int s = android_get_control_socket(service);
737 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800738 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700739 exit(1);
740 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700741 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700742 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800743 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700744 exit(1);
745 }
746
747 struct sockaddr addr;
748 socklen_t alen = sizeof(addr);
749 int fd = accept(s, &addr, &alen);
750 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800751 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700752 exit(1);
753 }
754
Felipe Leme2628e9e2016-04-12 16:36:51 -0700755 return fd;
756}
757
758/* redirect output to a service control socket */
759void redirect_to_socket(FILE *redirect, const char *service) {
760 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700761 fflush(redirect);
762 dup2(fd, fileno(redirect));
763 close(fd);
764}
765
Felipe Leme2628e9e2016-04-12 16:36:51 -0700766// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800767void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800768 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700769
770 /* skip initial slash */
771 if (chp[0] == '/')
772 chp++;
773
774 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800775 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700776 while (chp && chp[0]) {
777 chp = strchr(chp, '/');
778 if (chp) {
779 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800780 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800781 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800782 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800783 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800784 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800785 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800786 }
787 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700788 *chp++ = '/';
789 }
790 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800791}
792
Felipe Leme0f3fb202016-06-10 17:10:53 -0700793void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800794 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700795
Felipe Leme0f3fb202016-06-10 17:10:53 -0700796 int fd = TEMP_FAILURE_RETRY(open(path,
797 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800798 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700799 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800800 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700801 exit(1);
802 }
803
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800804 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700805 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700806}
807
Felipe Leme0f3fb202016-06-10 17:10:53 -0700808void redirect_to_file(FILE *redirect, char *path) {
809 _redirect_to_file(redirect, path, O_TRUNC);
810}
811
812void redirect_to_existing_file(FILE *redirect, char *path) {
813 _redirect_to_file(redirect, path, O_APPEND);
814}
815
Steven Moreland17b29e12017-03-21 18:38:05 -0700816static bool should_dump_hal_interface(const char* interface) {
817 for (const char** i = hal_interfaces_to_dump; *i; i++) {
818 if (!strcmp(*i, interface)) {
819 return true;
820 }
821 }
822 return false;
823}
824
Jeff Brownbf7f4922012-06-07 16:40:01 -0700825static bool should_dump_native_traces(const char* path) {
826 for (const char** p = native_processes_to_dump; *p; p++) {
827 if (!strcmp(*p, path)) {
828 return true;
829 }
830 }
831 return false;
832}
833
Steven Moreland17b29e12017-03-21 18:38:05 -0700834std::set<int> get_interesting_hal_pids() {
835 using android::hidl::manager::V1_0::IServiceManager;
836 using android::sp;
837 using android::hardware::Return;
838
839 sp<IServiceManager> manager = IServiceManager::getService();
840 std::set<int> pids;
841
842 Return<void> ret = manager->debugDump([&](auto& hals) {
843 for (const auto &info : hals) {
844 if (info.pid == static_cast<int>(IServiceManager::PidConstant::NO_PID)) {
845 continue;
846 }
847
Scott Randolph5a0c4852017-04-03 14:05:49 -0700848 if (!should_dump_hal_interface(info.interfaceName.c_str())) {
Steven Moreland17b29e12017-03-21 18:38:05 -0700849 continue;
850 }
851
852 pids.insert(info.pid);
853 }
854 });
855
856 if (!ret.isOk()) {
857 MYLOGE("Could not get list of HAL PIDs: %s\n", ret.description().c_str());
858 }
859
860 return pids; // whether it was okay or not
861}
862
Narayan Kamath8f788292017-05-25 13:20:39 +0100863const char* DumpTraces(const std::string& traces_path);
864const char* DumpTracesTombstoned(const std::string& traces_dir);
865
Jeff Brownbf7f4922012-06-07 16:40:01 -0700866/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
867const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -0700868 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -0700869
Narayan Kamath8f788292017-05-25 13:20:39 +0100870 const std::string traces_dir = android::base::GetProperty("dalvik.vm.stack-trace-dir", "");
871 if (!traces_dir.empty()) {
872 return DumpTracesTombstoned(traces_dir);
873 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700874
Narayan Kamath8f788292017-05-25 13:20:39 +0100875 const std::string traces_file = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
876 if (!traces_file.empty()) {
877 return DumpTraces(traces_file);
878 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700879
Narayan Kamath8f788292017-05-25 13:20:39 +0100880 return nullptr;
881}
882
883static bool IsZygote(int pid) {
884 static const std::string kZygotePrefix = "zygote";
885
886 std::string cmdline;
887 if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid),
888 &cmdline)) {
889 return true;
890 }
891
892 return (cmdline.find(kZygotePrefix) == 0);
893}
894
895const char* DumpTracesTombstoned(const std::string& traces_dir) {
896 const std::string temp_file_pattern = traces_dir + "/dumptrace_XXXXXX";
897
898 const size_t buf_size = temp_file_pattern.length() + 1;
899 std::unique_ptr<char[]> file_name_buf(new char[buf_size]);
900 memcpy(file_name_buf.get(), temp_file_pattern.c_str(), buf_size);
901
902 // Create a new, empty file to receive all trace dumps.
903 //
904 // TODO: This can be simplified once we remove support for the old style
905 // dumps. We can have a file descriptor passed in to dump_traces instead
906 // of creating a file, closing it and then reopening it again.
907 android::base::unique_fd fd(mkostemp(file_name_buf.get(), O_APPEND | O_CLOEXEC));
908 if (fd < 0) {
909 MYLOGE("mkostemp on pattern %s: %s\n", file_name_buf.get(), strerror(errno));
910 return nullptr;
911 }
912
913 // Nobody should have access to this temporary file except dumpstate, but we
914 // temporarily grant 'read' to 'others' here because this file is created
915 // when tombstoned is still running as root, but dumped after dropping. This
916 // can go away once support for old style dumping has.
917 const int chmod_ret = fchmod(fd, 0666);
918 if (chmod_ret < 0) {
919 MYLOGE("fchmod on %s failed: %s\n", file_name_buf.get(), strerror(errno));
920 return nullptr;
921 }
922
923 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
924 if (proc.get() == nullptr) {
925 MYLOGE("opendir /proc failed: %s\n", strerror(errno));
926 return nullptr;
927 }
928
929 // Number of times process dumping has timed out. If we encounter too many
930 // failures, we'll give up.
931 int timeout_failures = 0;
932 bool dalvik_found = false;
933
934 const std::set<int> hal_pids = get_interesting_hal_pids();
935
936 struct dirent* d;
937 while ((d = readdir(proc.get()))) {
938 int pid = atoi(d->d_name);
939 if (pid <= 0) {
940 continue;
941 }
942
943 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
944 std::string exe;
945 if (!android::base::Readlink(link_name, &exe)) {
946 continue;
947 }
948
949 bool is_java_process;
950 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
951 // Don't bother dumping backtraces for the zygote.
952 if (IsZygote(pid)) {
953 continue;
954 }
955
956 dalvik_found = true;
957 is_java_process = true;
958 } else if (should_dump_native_traces(exe.c_str()) || hal_pids.find(pid) != hal_pids.end()) {
959 is_java_process = false;
960 } else {
961 // Probably a native process we don't care about, continue.
962 continue;
963 }
964
965 // If 3 backtrace dumps fail in a row, consider debuggerd dead.
966 if (timeout_failures == 3) {
967 dprintf(fd, "ERROR: Too many stack dump failures, exiting.\n");
968 break;
969 }
970
971 const uint64_t start = Nanotime();
972 const int ret = dump_backtrace_to_file_timeout(
973 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
974 is_java_process ? 5 : 20, fd);
975
976 if (ret == -1) {
977 dprintf(fd, "dumping failed, likely due to a timeout\n");
978 timeout_failures++;
979 continue;
980 }
981
982 // We've successfully dumped stack traces, reset the failure count
983 // and write a summary of the elapsed time to the file and continue with the
984 // next process.
985 timeout_failures = 0;
986
987 dprintf(fd, "[dump %s stack %d: %.3fs elapsed]\n", is_java_process ? "dalvik" : "native",
988 pid, (float)(Nanotime() - start) / NANOS_PER_SEC);
989 }
990
991 if (!dalvik_found) {
992 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
993 }
994
995 return file_name_buf.release();
996}
997
998const char* DumpTraces(const std::string& traces_path) {
999 const char* result = NULL;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001000 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -07001001 std::string anrtraces_path = traces_path + ".anr";
1002 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
1003 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001004 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001005 }
1006
Colin Crossf45fa6b2012-03-26 12:38:26 -07001007 /* create a new, empty traces.txt file to receive stack dumps */
Josh Gao989b8122017-01-13 22:09:40 -08001008 int fd = TEMP_FAILURE_RETRY(
Josh Gaoe75d9632017-01-18 16:14:03 -08001009 open(traces_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
Josh Gao989b8122017-01-13 22:09:40 -08001010 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001011 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001012 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001013 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001014 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001015 int chmod_ret = fchmod(fd, 0666);
1016 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001017 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001018 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001019 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001020 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001021
Felipe Leme8620bb42015-11-10 11:04:45 -08001022 /* Variables below must be initialized before 'goto' statements */
1023 int dalvik_found = 0;
1024 int ifd, wfd = -1;
Steven Moreland17b29e12017-03-21 18:38:05 -07001025 std::set<int> hal_pids = get_interesting_hal_pids();
Felipe Leme8620bb42015-11-10 11:04:45 -08001026
Colin Crossf45fa6b2012-03-26 12:38:26 -07001027 /* walk /proc and kill -QUIT all Dalvik processes */
1028 DIR *proc = opendir("/proc");
1029 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001030 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001031 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001032 }
1033
1034 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001035 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001036 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001037 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001038 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001039 }
1040
Felipe Lemee184f662016-10-27 10:04:47 -07001041 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001042 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001043 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001044 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001045 }
1046
1047 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001048 while ((d = readdir(proc))) {
1049 int pid = atoi(d->d_name);
1050 if (pid <= 0) continue;
1051
Jeff Brownbf7f4922012-06-07 16:40:01 -07001052 char path[PATH_MAX];
1053 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001054 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001055 ssize_t len = readlink(path, data, sizeof(data) - 1);
1056 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001057 continue;
1058 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001059 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001060
Colin Cross0d6180f2014-07-16 19:00:46 -07001061 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001062 /* skip zygote -- it won't dump its stack anyway */
1063 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001064 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001065 len = read(cfd, data, sizeof(data) - 1);
1066 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001067 if (len <= 0) {
1068 continue;
1069 }
1070 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001071 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001072 continue;
1073 }
1074
1075 ++dalvik_found;
Felipe Lemef0292972016-11-22 13:57:05 -08001076 uint64_t start = Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001077 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001078 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001079 continue;
1080 }
1081
1082 /* wait for the writable-close notification from inotify */
1083 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001084 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001085 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001086 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001087 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001088 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001089 } else {
1090 struct inotify_event ie;
1091 read(ifd, &ie, sizeof(ie));
1092 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001093
1094 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001095 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001096 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001097 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -08001098 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001099 }
Steven Moreland17b29e12017-03-21 18:38:05 -07001100 } else if (should_dump_native_traces(data) ||
1101 hal_pids.find(pid) != hal_pids.end()) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001102 /* dump native process if appropriate */
1103 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001104 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001105 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001106 static uint16_t timeout_failures = 0;
Felipe Lemef0292972016-11-22 13:57:05 -08001107 uint64_t start = Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001108
1109 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1110 if (timeout_failures == 3) {
1111 dprintf(fd, "too many stack dump failures, skipping...\n");
Narayan Kamath93b36d12017-05-31 10:33:28 +01001112 } else if (dump_backtrace_to_file_timeout(
1113 pid, kDebuggerdNativeBacktrace, 20, fd) == -1) {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001114 dprintf(fd, "dumping failed, likely due to a timeout\n");
1115 timeout_failures++;
1116 } else {
1117 timeout_failures = 0;
1118 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001119 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -08001120 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001121 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001122 }
1123 }
1124
Colin Crossf45fa6b2012-03-26 12:38:26 -07001125 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001126 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001127 }
1128
Felipe Lemee184f662016-10-27 10:04:47 -07001129 static std::string dumptraces_path = android::base::StringPrintf(
1130 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
1131 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
1132 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
1133 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001134 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001135 }
Felipe Lemee184f662016-10-27 10:04:47 -07001136 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001137
1138 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -07001139 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001140
1141error_close_ifd:
1142 close(ifd);
1143error_close_fd:
1144 close(fd);
1145 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001146}
1147
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001148void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001149 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -08001150 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001151 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001152 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001153 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001154 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001155 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001156 return;
1157 }
1158 char table[16];
1159 // Each line has an integer (the table number), a space, and a string (the table name). We only
1160 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1161 // Add a fixed max limit so this doesn't go awry.
1162 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001163 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1164 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001165 }
1166 fclose(fp);
1167}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001168
Felipe Leme71bbfc52015-11-23 14:14:51 -08001169// TODO: make this function thread safe if sections are generated in parallel.
Vishnu Nair6921f802017-11-22 09:17:23 -08001170void Dumpstate::UpdateProgress(int32_t delta_sec) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001171 if (progress_ == nullptr) {
1172 MYLOGE("UpdateProgress: progress_ not set\n");
1173 return;
1174 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001175
Felipe Leme7447d7c2016-11-03 18:12:22 -07001176 // Always update progess so stats can be tuned...
Vishnu Nair6921f802017-11-22 09:17:23 -08001177 bool max_changed = progress_->Inc(delta_sec);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001178
1179 // ...but only notifiy listeners when necessary.
1180 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001181
Felipe Leme009ecbb2016-11-07 10:18:44 -08001182 int progress = progress_->Get();
1183 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -08001184
1185 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -08001186 if (max_changed && listener_ != nullptr) {
1187 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001188 }
1189
Felipe Leme009ecbb2016-11-07 10:18:44 -08001190 int32_t last_update_delta = progress - last_updated_progress_;
1191 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1192 return;
1193 }
1194 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001195
Felipe Leme9a523ae2016-10-20 15:10:33 -07001196 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001197 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001198 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001199 }
1200
Felipe Leme75876a22016-10-27 16:31:27 -07001201 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001202 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001203 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001204 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001205 } else {
1206 // stderr is ignored on normal invocations, but useful when calling
1207 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001208 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001209 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001210 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001211 }
1212}
Felipe Lemee338bf62015-12-07 14:03:50 -08001213
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001214void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001215 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001216 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001217 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001218 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1219 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001220 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001221 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001222 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001223 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001224}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001225
Felipe Leme0c80cf02016-01-05 13:25:34 -08001226bool is_dir(const char* pathname) {
1227 struct stat info;
1228 if (stat(pathname, &info) == -1) {
1229 return false;
1230 }
1231 return S_ISDIR(info.st_mode);
1232}
1233
1234time_t get_mtime(int fd, time_t default_mtime) {
1235 struct stat info;
1236 if (fstat(fd, &info) == -1) {
1237 return default_mtime;
1238 }
1239 return info.st_mtime;
1240}
1241
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001242void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001243 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001244 struct hex {
1245 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001246 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001247 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1248 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1249 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1250 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1251
1252 std::string buffer;
1253 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1254 return;
1255 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001256
Felipe Lemed8b94e52016-12-08 10:21:44 -08001257 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001258
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001259 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001260 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001261 return;
1262 }
1263
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001264 int ext_csd_rev = 0;
1265 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1266 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001267 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001268 return;
1269 }
1270
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001271 static const char *ver_str[] = {
1272 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1273 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001274 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1275 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1276 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001277 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001278 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001279 return;
1280 }
1281
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001282 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001283 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001284 return;
1285 }
1286
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001287 int ext_pre_eol_info = 0;
1288 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1289 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001290 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001291 return;
1292 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001293
1294 static const char *eol_str[] = {
1295 "Undefined",
1296 "Normal",
1297 "Warning (consumed 80% of reserve)",
1298 "Urgent (consumed 90% of reserve)"
1299 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001300 printf(
1301 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -08001302 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1303 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001304
1305 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1306 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001307 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001308 int ext_device_life_time_est;
1309 static const char *est_str[] = {
1310 "Undefined",
1311 "0-10% of device lifetime used",
1312 "10-20% of device lifetime used",
1313 "20-30% of device lifetime used",
1314 "30-40% of device lifetime used",
1315 "40-50% of device lifetime used",
1316 "50-60% of device lifetime used",
1317 "60-70% of device lifetime used",
1318 "70-80% of device lifetime used",
1319 "80-90% of device lifetime used",
1320 "90-100% of device lifetime used",
1321 "Exceeded the maximum estimated device lifetime",
1322 };
1323
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001324 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001325 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001326 break;
1327 }
1328
1329 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001330 sub = buffer.substr(lifetime, sizeof(hex));
1331 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001332 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1333 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1334 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001335 continue;
1336 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001337 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1338 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1339 ext_device_life_time_est,
1340 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1341 ? ext_device_life_time_est
1342 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001343 }
1344
Felipe Lemed8b94e52016-12-08 10:21:44 -08001345 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001346}