blob: 5698d1b9792449cf06c32f5c1897d4ec9844a181 [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
Jeff Brownbf7f4922012-06-07 16:40:01 -070087 "/system/bin/mediaserver",
88 "/system/bin/sdcard",
89 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070090 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070091 NULL,
92};
93
Steven Moreland17b29e12017-03-21 18:38:05 -070094/* list of hal interface to dump containing process during native dumps */
95static const char* hal_interfaces_to_dump[] {
96 "android.hardware.audio@2.0::IDevicesFactory",
97 "android.hardware.bluetooth@1.0::IBluetoothHci",
98 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu108c0f02017-04-20 14:31:50 -070099 "android.hardware.graphics.composer@2.1::IComposer",
Steven Moreland17b29e12017-03-21 18:38:05 -0700100 "android.hardware.vr@1.0::IVr",
101 "android.hardware.media.omx@1.0::IOmx",
102 NULL,
103};
104
Felipe Leme7447d7c2016-11-03 18:12:22 -0700105// Reasonable value for max stats.
106static const int STATS_MAX_N_RUNS = 1000;
107static const long STATS_MAX_AVERAGE = 100000;
108
Felipe Lemebda15a02016-11-16 17:48:25 -0800109CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -0700110
Felipe Lemef0292972016-11-22 13:57:05 -0800111Dumpstate::Dumpstate(const std::string& version)
112 : pid_(getpid()), version_(version), now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700113}
114
115Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -0800116 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700117 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700118}
119
Felipe Leme46b85da2016-11-21 17:40:45 -0800120DurationReporter::DurationReporter(const std::string& title, bool log_only)
121 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700122 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800123 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800124 }
125}
126
127DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700128 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800129 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800130 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700131 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800132 } else {
133 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800134 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
135 title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800136 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800137 }
138}
139
Felipe Leme7447d7c2016-11-03 18:12:22 -0700140const int32_t Progress::kDefaultMax = 5000;
141
142Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
143}
144
145Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
146 : Progress(initial_max, growth_factor, "") {
147 progress_ = progress;
148}
149
150Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
151 : initial_max_(initial_max),
152 progress_(0),
153 max_(initial_max),
154 growth_factor_(growth_factor),
155 n_runs_(0),
156 average_max_(0),
157 path_(path) {
158 if (!path_.empty()) {
159 Load();
160 }
161}
162
163void Progress::Load() {
164 MYLOGD("Loading stats from %s\n", path_.c_str());
165 std::string content;
166 if (!android::base::ReadFileToString(path_, &content)) {
167 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
168 return;
169 }
170 if (content.empty()) {
171 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
172 return;
173 }
174 std::vector<std::string> lines = android::base::Split(content, "\n");
175
176 if (lines.size() < 1) {
177 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
178 (int)lines.size(), max_);
179 return;
180 }
181 char* ptr;
182 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
183 average_max_ = strtol(ptr, nullptr, 10);
184 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
185 average_max_ > STATS_MAX_AVERAGE) {
186 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
187 initial_max_ = Progress::kDefaultMax;
188 } else {
189 initial_max_ = average_max_;
190 }
191 max_ = initial_max_;
192
193 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
194}
195
196void Progress::Save() {
197 int32_t total = n_runs_ * average_max_ + progress_;
198 int32_t runs = n_runs_ + 1;
199 int32_t average = floor(((float)total) / runs);
200 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
201 path_.c_str());
202 if (path_.empty()) {
203 return;
204 }
205
206 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
207 if (!android::base::WriteStringToFile(content, path_)) {
208 MYLOGE("Could not save stats on %s\n", path_.c_str());
209 }
210}
211
212int32_t Progress::Get() const {
213 return progress_;
214}
215
216bool Progress::Inc(int32_t delta) {
217 bool changed = false;
218 if (delta >= 0) {
219 progress_ += delta;
220 if (progress_ > max_) {
221 int32_t old_max = max_;
222 max_ = floor((float)progress_ * growth_factor_);
223 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
224 changed = true;
225 }
226 }
227 return changed;
228}
229
230int32_t Progress::GetMax() const {
231 return max_;
232}
233
234int32_t Progress::GetInitialMax() const {
235 return initial_max_;
236}
237
238void Progress::Dump(int fd, const std::string& prefix) const {
239 const char* pr = prefix.c_str();
240 dprintf(fd, "%sprogress: %d\n", pr, progress_);
241 dprintf(fd, "%smax: %d\n", pr, max_);
242 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
243 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
244 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
245 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
246 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
247}
248
Felipe Leme75876a22016-10-27 16:31:27 -0700249bool Dumpstate::IsZipping() const {
250 return zip_writer_ != nullptr;
251}
252
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700253std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700254 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700255 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700256}
257
Felipe Leme7447d7c2016-11-03 18:12:22 -0700258void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
259 progress_ = std::move(progress);
260}
261
John Spurlock5ecd4be2014-01-29 14:14:40 -0500262void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800263 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
264 "for_each_userid(%s)", header);
265 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800266 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700267
John Spurlock5ecd4be2014-01-29 14:14:40 -0500268 DIR *d;
269 struct dirent *de;
270
Felipe Lemed8b94e52016-12-08 10:21:44 -0800271 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500272 func(0);
273
274 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800275 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500276 return;
277 }
278
279 while ((de = readdir(d))) {
280 int userid;
281 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
282 continue;
283 }
284 func(userid);
285 }
286
287 closedir(d);
288}
289
Colin Cross0c22e8b2012-11-02 15:46:56 -0700290static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700291 DIR *d;
292 struct dirent *de;
293
294 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800295 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700296 return;
297 }
298
Felipe Lemed8b94e52016-12-08 10:21:44 -0800299 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700300 while ((de = readdir(d))) {
301 int pid;
302 int fd;
303 char cmdpath[255];
304 char cmdline[255];
305
306 if (!(pid = atoi(de->d_name))) {
307 continue;
308 }
309
Colin Crossf45fa6b2012-03-26 12:38:26 -0700310 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800311
312 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
313 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
314 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700315 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800316 if (cmdline[0]) {
317 helper(pid, cmdline, arg);
318 continue;
319 }
320 }
321
322 // if no cmdline, a kernel thread has comm
323 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
324 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
325 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
326 close(fd);
327 if (cmdline[1]) {
328 cmdline[0] = '[';
329 size_t len = strcspn(cmdline, "\f\b\r\n");
330 cmdline[len] = ']';
331 cmdline[len+1] = '\0';
332 }
333 }
334 if (!cmdline[0]) {
335 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700336 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700337 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700338 }
339
340 closedir(d);
341}
342
Colin Cross0c22e8b2012-11-02 15:46:56 -0700343static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800344 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700345 func(pid, cmdline);
346}
347
348void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800349 std::string title = header == nullptr ? "for_each_pid"
350 : android::base::StringPrintf("for_each_pid(%s)", header);
351 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800352 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700353
Felipe Leme515eb0d2015-12-14 15:09:56 -0800354 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700355}
356
357static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
358 DIR *d;
359 struct dirent *de;
360 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800361 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700362
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700363 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700364
365 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800366 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700367 return;
368 }
369
370 func(pid, pid, cmdline);
371
372 while ((de = readdir(d))) {
373 int tid;
374 int fd;
375 char commpath[255];
376 char comm[255];
377
378 if (!(tid = atoi(de->d_name))) {
379 continue;
380 }
381
382 if (tid == pid)
383 continue;
384
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700385 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800386 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700387 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700388 strcpy(comm, "N/A");
389 } else {
390 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800391 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700392 close(fd);
393
394 c = strrchr(comm, '\n');
395 if (c) {
396 *c = '\0';
397 }
398 }
399 func(pid, tid, comm);
400 }
401
402 closedir(d);
403}
404
405void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800406 std::string title = header == nullptr ? "for_each_tid"
407 : android::base::StringPrintf("for_each_tid(%s)", header);
408 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800409
Felipe Lemef0292972016-11-22 13:57:05 -0800410 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700411
Felipe Leme8620bb42015-11-10 11:04:45 -0800412 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700413}
414
415void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800416 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700417
Colin Crossf45fa6b2012-03-26 12:38:26 -0700418 char path[255];
419 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800420 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700421 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700422
423 memset(buffer, 0, sizeof(buffer));
424
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700425 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700426 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800427 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700428 return;
429 }
430
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800431 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
432 save_errno = errno;
433 close(fd);
434
435 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800436 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800437 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700438 }
439
Colin Cross0c22e8b2012-11-02 15:46:56 -0700440 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
441 pid == tid ? 0 : 3, "", name);
442
Felipe Lemed8b94e52016-12-08 10:21:44 -0800443 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700444
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800445 return;
446}
447
448// print time in centiseconds
449static void snprcent(char *buffer, size_t len, size_t spc,
450 unsigned long long time) {
451 static long hz; // cache discovered hz
452
453 if (hz <= 0) {
454 hz = sysconf(_SC_CLK_TCK);
455 if (hz <= 0) {
456 hz = 1000;
457 }
458 }
459
460 // convert to centiseconds
461 time = (time * 100 + (hz / 2)) / hz;
462
463 char str[16];
464
465 snprintf(str, sizeof(str), " %llu.%02u",
466 time / 100, (unsigned)(time % 100));
467 size_t offset = strlen(buffer);
468 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
469 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
470}
471
472// print permille as a percent
473static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
474 char str[16];
475
476 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
477 size_t offset = strlen(buffer);
478 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
479 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
480}
481
482void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800483 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700484
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800485 char path[255];
486 char buffer[1023];
487 int fd, ret, save_errno;
488
489 memset(buffer, 0, sizeof(buffer));
490
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700491 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800492 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800493 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800494 return;
495 }
496
497 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
498 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700499 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800500
501 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800502 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800503 return;
504 }
505
506 // field 14 is utime
507 // field 15 is stime
508 // field 42 is iotime
509 unsigned long long utime = 0, stime = 0, iotime = 0;
510 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800511 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
512 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
513 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
514 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800515 &utime, &stime, &iotime) != 3) {
516 return;
517 }
518
519 unsigned long long total = utime + stime;
520 if (!total) {
521 return;
522 }
523
524 unsigned permille = (iotime * 1000 + (total / 2)) / total;
525 if (permille > 1000) {
526 permille = 1000;
527 }
528
529 // try to beautify and stabilize columns at <80 characters
530 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
531 if ((name[0] != '[') || utime) {
532 snprcent(buffer, sizeof(buffer), 57, utime);
533 }
534 snprcent(buffer, sizeof(buffer), 65, stime);
535 if ((name[0] != '[') || iotime) {
536 snprcent(buffer, sizeof(buffer), 73, iotime);
537 }
538 if (iotime) {
539 snprdec(buffer, sizeof(buffer), 79, permille);
540 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800541 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800542
Colin Crossf45fa6b2012-03-26 12:38:26 -0700543 return;
544}
545
546void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800547 const char *title = "KERNEL LOG (dmesg)";
548 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800549 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800550
Felipe Lemef0292972016-11-22 13:57:05 -0800551 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700552
Elliott Hughes5f87b312012-09-17 11:43:40 -0700553 /* Get size of kernel buffer */
554 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700555 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800556 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700557 return;
558 }
559 char *buf = (char *) malloc(size + 1);
560 if (buf == NULL) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800561 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700562 return;
563 }
564 int retval = klogctl(KLOG_READ_ALL, buf, size);
565 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800566 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700567 free(buf);
568 return;
569 }
570 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800571 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700572 free(buf);
573 return;
574}
575
576void do_showmap(int pid, const char *name) {
577 char title[255];
578 char arg[255];
579
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700580 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
581 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800582 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800583}
584
Felipe Leme678727a2016-09-21 17:22:11 -0700585int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700586 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800587
Felipe Lemef0292972016-11-22 13:57:05 -0800588 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800589
Felipe Lemef0292972016-11-22 13:57:05 -0800590 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800591
Felipe Leme46b85da2016-11-21 17:40:45 -0800592 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800593}
594
Felipe Leme71a74ac2016-03-17 15:43:25 -0700595int read_file_as_long(const char *path, long int *output) {
596 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
597 if (fd < 0) {
598 int err = errno;
599 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
600 return -1;
601 }
602 char buffer[50];
603 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
604 if (bytes_read == -1) {
605 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
606 return -2;
607 }
608 if (bytes_read == 0) {
609 MYLOGE("File %s is empty\n", path);
610 return -3;
611 }
612 *output = atoi(buffer);
613 return 0;
614}
615
Mark Salyzyn326842f2015-04-30 09:49:41 -0700616/* calls skip to gate calling dump_from_fd recursively
617 * in the specified directory. dump_from_fd defaults to
618 * dump_file_from_fd above when set to NULL. skip defaults
619 * to false when set to NULL. dump_from_fd will always be
620 * called with title NULL.
621 */
Felipe Leme678727a2016-09-21 17:22:11 -0700622int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
623 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800624 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700625 DIR *dirp;
626 struct dirent *d;
627 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800628 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700629 int fd, retval = 0;
630
Felipe Leme678727a2016-09-21 17:22:11 -0700631 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800632 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700633 }
Felipe Lemef0292972016-11-22 13:57:05 -0800634 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700635
636 if (dir[strlen(dir) - 1] == '/') {
637 ++slash;
638 }
639 dirp = opendir(dir);
640 if (dirp == NULL) {
641 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800642 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700643 return retval;
644 }
645
646 if (!dump_from_fd) {
647 dump_from_fd = dump_file_from_fd;
648 }
649 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
650 if ((d->d_name[0] == '.')
651 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
652 || (d->d_name[1] == '\0'))) {
653 continue;
654 }
655 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
656 (d->d_type == DT_DIR) ? "/" : "");
657 if (!newpath) {
658 retval = -errno;
659 continue;
660 }
661 if (skip && (*skip)(newpath)) {
662 continue;
663 }
664 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700665 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700666 if (ret < 0) {
667 retval = ret;
668 }
669 continue;
670 }
671 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
672 if (fd < 0) {
673 retval = fd;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800674 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700675 continue;
676 }
677 (*dump_from_fd)(NULL, newpath, fd);
678 }
679 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700680 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800681 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700682 }
683 return retval;
684}
685
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800686/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
687 * it's possible to avoid issues where opening the file itself can get
688 * stuck.
689 */
690int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800691 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700692
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800693 int flags = fcntl(fd, F_GETFL);
694 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800695 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800696 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800697 return -1;
698 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800699 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800700 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800701 return -1;
702 }
Felipe Lemef0292972016-11-22 13:57:05 -0800703 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700704}
705
Felipe Leme46b85da2016-11-21 17:40:45 -0800706int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
707 const CommandOptions& options) {
708 DurationReporter duration_reporter(title);
709
Felipe Lemef0292972016-11-22 13:57:05 -0800710 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800711
Felipe Lemef0292972016-11-22 13:57:05 -0800712 /* TODO: for now we're simplifying the progress calculation by using the
713 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
714 * where its weight should be much higher proportionally to its timeout.
715 * Ideally, it should use a options.EstimatedDuration() instead...*/
716 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800717
Felipe Leme46b85da2016-11-21 17:40:45 -0800718 return status;
719}
720
Felipe Leme9a523ae2016-10-20 15:10:33 -0700721void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700722 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700723 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
724 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700725 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700726 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700727}
728
Felipe Leme2628e9e2016-04-12 16:36:51 -0700729int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700730 int s = android_get_control_socket(service);
731 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800732 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700733 exit(1);
734 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700735 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700736 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800737 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700738 exit(1);
739 }
740
741 struct sockaddr addr;
742 socklen_t alen = sizeof(addr);
743 int fd = accept(s, &addr, &alen);
744 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800745 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700746 exit(1);
747 }
748
Felipe Leme2628e9e2016-04-12 16:36:51 -0700749 return fd;
750}
751
752/* redirect output to a service control socket */
753void redirect_to_socket(FILE *redirect, const char *service) {
754 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700755 fflush(redirect);
756 dup2(fd, fileno(redirect));
757 close(fd);
758}
759
Felipe Leme2628e9e2016-04-12 16:36:51 -0700760// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800761void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800762 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700763
764 /* skip initial slash */
765 if (chp[0] == '/')
766 chp++;
767
768 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800769 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700770 while (chp && chp[0]) {
771 chp = strchr(chp, '/');
772 if (chp) {
773 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800774 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800775 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800776 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800777 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800778 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800779 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800780 }
781 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700782 *chp++ = '/';
783 }
784 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800785}
786
Felipe Leme0f3fb202016-06-10 17:10:53 -0700787void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800788 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700789
Felipe Leme0f3fb202016-06-10 17:10:53 -0700790 int fd = TEMP_FAILURE_RETRY(open(path,
791 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800792 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700793 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800794 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700795 exit(1);
796 }
797
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800798 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700799 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700800}
801
Felipe Leme0f3fb202016-06-10 17:10:53 -0700802void redirect_to_file(FILE *redirect, char *path) {
803 _redirect_to_file(redirect, path, O_TRUNC);
804}
805
806void redirect_to_existing_file(FILE *redirect, char *path) {
807 _redirect_to_file(redirect, path, O_APPEND);
808}
809
Steven Moreland17b29e12017-03-21 18:38:05 -0700810static bool should_dump_hal_interface(const char* interface) {
811 for (const char** i = hal_interfaces_to_dump; *i; i++) {
812 if (!strcmp(*i, interface)) {
813 return true;
814 }
815 }
816 return false;
817}
818
Jeff Brownbf7f4922012-06-07 16:40:01 -0700819static bool should_dump_native_traces(const char* path) {
820 for (const char** p = native_processes_to_dump; *p; p++) {
821 if (!strcmp(*p, path)) {
822 return true;
823 }
824 }
825 return false;
826}
827
Steven Moreland17b29e12017-03-21 18:38:05 -0700828std::set<int> get_interesting_hal_pids() {
829 using android::hidl::manager::V1_0::IServiceManager;
830 using android::sp;
831 using android::hardware::Return;
832
833 sp<IServiceManager> manager = IServiceManager::getService();
834 std::set<int> pids;
835
836 Return<void> ret = manager->debugDump([&](auto& hals) {
837 for (const auto &info : hals) {
838 if (info.pid == static_cast<int>(IServiceManager::PidConstant::NO_PID)) {
839 continue;
840 }
841
Scott Randolph5a0c4852017-04-03 14:05:49 -0700842 if (!should_dump_hal_interface(info.interfaceName.c_str())) {
Steven Moreland17b29e12017-03-21 18:38:05 -0700843 continue;
844 }
845
846 pids.insert(info.pid);
847 }
848 });
849
850 if (!ret.isOk()) {
851 MYLOGE("Could not get list of HAL PIDs: %s\n", ret.description().c_str());
852 }
853
854 return pids; // whether it was okay or not
855}
856
Narayan Kamath8f788292017-05-25 13:20:39 +0100857const char* DumpTraces(const std::string& traces_path);
858const char* DumpTracesTombstoned(const std::string& traces_dir);
859
Jeff Brownbf7f4922012-06-07 16:40:01 -0700860/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
861const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -0700862 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -0700863
Narayan Kamath8f788292017-05-25 13:20:39 +0100864 const std::string traces_dir = android::base::GetProperty("dalvik.vm.stack-trace-dir", "");
865 if (!traces_dir.empty()) {
866 return DumpTracesTombstoned(traces_dir);
867 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700868
Narayan Kamath8f788292017-05-25 13:20:39 +0100869 const std::string traces_file = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
870 if (!traces_file.empty()) {
871 return DumpTraces(traces_file);
872 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700873
Narayan Kamath8f788292017-05-25 13:20:39 +0100874 return nullptr;
875}
876
877static bool IsZygote(int pid) {
878 static const std::string kZygotePrefix = "zygote";
879
880 std::string cmdline;
881 if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid),
882 &cmdline)) {
883 return true;
884 }
885
886 return (cmdline.find(kZygotePrefix) == 0);
887}
888
889const char* DumpTracesTombstoned(const std::string& traces_dir) {
890 const std::string temp_file_pattern = traces_dir + "/dumptrace_XXXXXX";
891
892 const size_t buf_size = temp_file_pattern.length() + 1;
893 std::unique_ptr<char[]> file_name_buf(new char[buf_size]);
894 memcpy(file_name_buf.get(), temp_file_pattern.c_str(), buf_size);
895
896 // Create a new, empty file to receive all trace dumps.
897 //
898 // TODO: This can be simplified once we remove support for the old style
899 // dumps. We can have a file descriptor passed in to dump_traces instead
900 // of creating a file, closing it and then reopening it again.
901 android::base::unique_fd fd(mkostemp(file_name_buf.get(), O_APPEND | O_CLOEXEC));
902 if (fd < 0) {
903 MYLOGE("mkostemp on pattern %s: %s\n", file_name_buf.get(), strerror(errno));
904 return nullptr;
905 }
906
907 // Nobody should have access to this temporary file except dumpstate, but we
908 // temporarily grant 'read' to 'others' here because this file is created
909 // when tombstoned is still running as root, but dumped after dropping. This
910 // can go away once support for old style dumping has.
911 const int chmod_ret = fchmod(fd, 0666);
912 if (chmod_ret < 0) {
913 MYLOGE("fchmod on %s failed: %s\n", file_name_buf.get(), strerror(errno));
914 return nullptr;
915 }
916
917 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
918 if (proc.get() == nullptr) {
919 MYLOGE("opendir /proc failed: %s\n", strerror(errno));
920 return nullptr;
921 }
922
923 // Number of times process dumping has timed out. If we encounter too many
924 // failures, we'll give up.
925 int timeout_failures = 0;
926 bool dalvik_found = false;
927
928 const std::set<int> hal_pids = get_interesting_hal_pids();
929
930 struct dirent* d;
931 while ((d = readdir(proc.get()))) {
932 int pid = atoi(d->d_name);
933 if (pid <= 0) {
934 continue;
935 }
936
937 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
938 std::string exe;
939 if (!android::base::Readlink(link_name, &exe)) {
940 continue;
941 }
942
943 bool is_java_process;
944 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
945 // Don't bother dumping backtraces for the zygote.
946 if (IsZygote(pid)) {
947 continue;
948 }
949
950 dalvik_found = true;
951 is_java_process = true;
952 } else if (should_dump_native_traces(exe.c_str()) || hal_pids.find(pid) != hal_pids.end()) {
953 is_java_process = false;
954 } else {
955 // Probably a native process we don't care about, continue.
956 continue;
957 }
958
959 // If 3 backtrace dumps fail in a row, consider debuggerd dead.
960 if (timeout_failures == 3) {
961 dprintf(fd, "ERROR: Too many stack dump failures, exiting.\n");
962 break;
963 }
964
965 const uint64_t start = Nanotime();
966 const int ret = dump_backtrace_to_file_timeout(
967 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
968 is_java_process ? 5 : 20, fd);
969
970 if (ret == -1) {
971 dprintf(fd, "dumping failed, likely due to a timeout\n");
972 timeout_failures++;
973 continue;
974 }
975
976 // We've successfully dumped stack traces, reset the failure count
977 // and write a summary of the elapsed time to the file and continue with the
978 // next process.
979 timeout_failures = 0;
980
981 dprintf(fd, "[dump %s stack %d: %.3fs elapsed]\n", is_java_process ? "dalvik" : "native",
982 pid, (float)(Nanotime() - start) / NANOS_PER_SEC);
983 }
984
985 if (!dalvik_found) {
986 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
987 }
988
989 return file_name_buf.release();
990}
991
992const char* DumpTraces(const std::string& traces_path) {
993 const char* result = NULL;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700994 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -0700995 std::string anrtraces_path = traces_path + ".anr";
996 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
997 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700998 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -0700999 }
1000
Colin Crossf45fa6b2012-03-26 12:38:26 -07001001 /* create a new, empty traces.txt file to receive stack dumps */
Josh Gao989b8122017-01-13 22:09:40 -08001002 int fd = TEMP_FAILURE_RETRY(
Josh Gaoe75d9632017-01-18 16:14:03 -08001003 open(traces_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
Josh Gao989b8122017-01-13 22:09:40 -08001004 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001005 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001006 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001007 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001008 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001009 int chmod_ret = fchmod(fd, 0666);
1010 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001011 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001012 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001013 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001014 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001015
Felipe Leme8620bb42015-11-10 11:04:45 -08001016 /* Variables below must be initialized before 'goto' statements */
1017 int dalvik_found = 0;
1018 int ifd, wfd = -1;
Steven Moreland17b29e12017-03-21 18:38:05 -07001019 std::set<int> hal_pids = get_interesting_hal_pids();
Felipe Leme8620bb42015-11-10 11:04:45 -08001020
Colin Crossf45fa6b2012-03-26 12:38:26 -07001021 /* walk /proc and kill -QUIT all Dalvik processes */
1022 DIR *proc = opendir("/proc");
1023 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001024 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001025 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026 }
1027
1028 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001029 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001030 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001031 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001032 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001033 }
1034
Felipe Lemee184f662016-10-27 10:04:47 -07001035 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001036 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001037 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001038 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001039 }
1040
1041 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001042 while ((d = readdir(proc))) {
1043 int pid = atoi(d->d_name);
1044 if (pid <= 0) continue;
1045
Jeff Brownbf7f4922012-06-07 16:40:01 -07001046 char path[PATH_MAX];
1047 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001048 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001049 ssize_t len = readlink(path, data, sizeof(data) - 1);
1050 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001051 continue;
1052 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001053 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001054
Colin Cross0d6180f2014-07-16 19:00:46 -07001055 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001056 /* skip zygote -- it won't dump its stack anyway */
1057 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001058 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001059 len = read(cfd, data, sizeof(data) - 1);
1060 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001061 if (len <= 0) {
1062 continue;
1063 }
1064 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001065 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001066 continue;
1067 }
1068
1069 ++dalvik_found;
Felipe Lemef0292972016-11-22 13:57:05 -08001070 uint64_t start = Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001071 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001072 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001073 continue;
1074 }
1075
1076 /* wait for the writable-close notification from inotify */
1077 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001078 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001079 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001080 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001081 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001082 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001083 } else {
1084 struct inotify_event ie;
1085 read(ifd, &ie, sizeof(ie));
1086 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001087
1088 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001089 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001090 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001091 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -08001092 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001093 }
Steven Moreland17b29e12017-03-21 18:38:05 -07001094 } else if (should_dump_native_traces(data) ||
1095 hal_pids.find(pid) != hal_pids.end()) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001096 /* dump native process if appropriate */
1097 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001098 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001099 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001100 static uint16_t timeout_failures = 0;
Felipe Lemef0292972016-11-22 13:57:05 -08001101 uint64_t start = Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001102
1103 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1104 if (timeout_failures == 3) {
1105 dprintf(fd, "too many stack dump failures, skipping...\n");
Narayan Kamath93b36d12017-05-31 10:33:28 +01001106 } else if (dump_backtrace_to_file_timeout(
1107 pid, kDebuggerdNativeBacktrace, 20, fd) == -1) {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001108 dprintf(fd, "dumping failed, likely due to a timeout\n");
1109 timeout_failures++;
1110 } else {
1111 timeout_failures = 0;
1112 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001113 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -08001114 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001115 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001116 }
1117 }
1118
Colin Crossf45fa6b2012-03-26 12:38:26 -07001119 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001120 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001121 }
1122
Felipe Lemee184f662016-10-27 10:04:47 -07001123 static std::string dumptraces_path = android::base::StringPrintf(
1124 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
1125 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
1126 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
1127 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001128 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001129 }
Felipe Lemee184f662016-10-27 10:04:47 -07001130 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001131
1132 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -07001133 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001134
1135error_close_ifd:
1136 close(ifd);
1137error_close_fd:
1138 close(fd);
1139 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001140}
1141
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001142void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001143 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -08001144 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001145 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001146 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001147 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001148 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001149 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001150 return;
1151 }
1152 char table[16];
1153 // Each line has an integer (the table number), a space, and a string (the table name). We only
1154 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1155 // Add a fixed max limit so this doesn't go awry.
1156 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001157 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1158 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001159 }
1160 fclose(fp);
1161}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001162
Felipe Leme71bbfc52015-11-23 14:14:51 -08001163// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001164void Dumpstate::UpdateProgress(int32_t delta) {
1165 if (progress_ == nullptr) {
1166 MYLOGE("UpdateProgress: progress_ not set\n");
1167 return;
1168 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001169
Felipe Leme7447d7c2016-11-03 18:12:22 -07001170 // Always update progess so stats can be tuned...
1171 bool max_changed = progress_->Inc(delta);
1172
1173 // ...but only notifiy listeners when necessary.
1174 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001175
Felipe Leme009ecbb2016-11-07 10:18:44 -08001176 int progress = progress_->Get();
1177 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -08001178
1179 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -08001180 if (max_changed && listener_ != nullptr) {
1181 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001182 }
1183
Felipe Leme009ecbb2016-11-07 10:18:44 -08001184 int32_t last_update_delta = progress - last_updated_progress_;
1185 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1186 return;
1187 }
1188 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001189
Felipe Leme9a523ae2016-10-20 15:10:33 -07001190 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001191 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001192 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001193 }
1194
Felipe Leme75876a22016-10-27 16:31:27 -07001195 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001196 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001197 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001198 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001199 } else {
1200 // stderr is ignored on normal invocations, but useful when calling
1201 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001202 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001203 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001204 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001205 }
1206}
Felipe Lemee338bf62015-12-07 14:03:50 -08001207
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001208void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001209 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001210 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001211 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001212 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1213 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001214 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001215 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001216 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001217 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001218}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001219
Felipe Leme0c80cf02016-01-05 13:25:34 -08001220bool is_dir(const char* pathname) {
1221 struct stat info;
1222 if (stat(pathname, &info) == -1) {
1223 return false;
1224 }
1225 return S_ISDIR(info.st_mode);
1226}
1227
1228time_t get_mtime(int fd, time_t default_mtime) {
1229 struct stat info;
1230 if (fstat(fd, &info) == -1) {
1231 return default_mtime;
1232 }
1233 return info.st_mtime;
1234}
1235
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001236void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001237 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001238 struct hex {
1239 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001240 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001241 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1242 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1243 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1244 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1245
1246 std::string buffer;
1247 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1248 return;
1249 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001250
Felipe Lemed8b94e52016-12-08 10:21:44 -08001251 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001252
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001253 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001254 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001255 return;
1256 }
1257
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001258 int ext_csd_rev = 0;
1259 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1260 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001261 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001262 return;
1263 }
1264
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001265 static const char *ver_str[] = {
1266 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1267 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001268 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1269 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1270 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001271 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001272 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001273 return;
1274 }
1275
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001276 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001277 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001278 return;
1279 }
1280
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001281 int ext_pre_eol_info = 0;
1282 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1283 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001284 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001285 return;
1286 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001287
1288 static const char *eol_str[] = {
1289 "Undefined",
1290 "Normal",
1291 "Warning (consumed 80% of reserve)",
1292 "Urgent (consumed 90% of reserve)"
1293 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001294 printf(
1295 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -08001296 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1297 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001298
1299 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1300 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001301 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001302 int ext_device_life_time_est;
1303 static const char *est_str[] = {
1304 "Undefined",
1305 "0-10% of device lifetime used",
1306 "10-20% of device lifetime used",
1307 "20-30% of device lifetime used",
1308 "30-40% of device lifetime used",
1309 "40-50% of device lifetime used",
1310 "50-60% of device lifetime used",
1311 "60-70% of device lifetime used",
1312 "70-80% of device lifetime used",
1313 "80-90% of device lifetime used",
1314 "90-100% of device lifetime used",
1315 "Exceeded the maximum estimated device lifetime",
1316 };
1317
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001318 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001319 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001320 break;
1321 }
1322
1323 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001324 sub = buffer.substr(lifetime, sizeof(hex));
1325 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001326 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1327 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1328 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001329 continue;
1330 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001331 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1332 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1333 ext_device_life_time_est,
1334 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1335 ? ext_device_life_time_est
1336 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001337 }
1338
Felipe Lemed8b94e52016-12-08 10:21:44 -08001339 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001340}