blob: 6ff0dae01cb5a828a2616e2e855476f0bb445414 [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",
Chong Zhangde00ee42017-06-02 16:13:16 -070091 "/vendor/bin/hw/android.hardware.media.omx@1.0-service", // media.codec
Jeff Brownbf7f4922012-06-07 16:40:01 -070092 NULL,
93};
94
Steven Moreland17b29e12017-03-21 18:38:05 -070095/* list of hal interface to dump containing process during native dumps */
96static const char* hal_interfaces_to_dump[] {
97 "android.hardware.audio@2.0::IDevicesFactory",
98 "android.hardware.bluetooth@1.0::IBluetoothHci",
99 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu108c0f02017-04-20 14:31:50 -0700100 "android.hardware.graphics.composer@2.1::IComposer",
Steven Moreland17b29e12017-03-21 18:38:05 -0700101 "android.hardware.media.omx@1.0::IOmx",
Peng Xuf1ab0ac2017-07-11 21:14:42 -0700102 "android.hardware.sensors@1.0::ISensors",
103 "android.hardware.vr@1.0::IVr",
Steven Moreland17b29e12017-03-21 18:38:05 -0700104 NULL,
105};
106
Felipe Leme7447d7c2016-11-03 18:12:22 -0700107// Reasonable value for max stats.
108static const int STATS_MAX_N_RUNS = 1000;
109static const long STATS_MAX_AVERAGE = 100000;
110
Felipe Lemebda15a02016-11-16 17:48:25 -0800111CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -0700112
Felipe Lemef0292972016-11-22 13:57:05 -0800113Dumpstate::Dumpstate(const std::string& version)
114 : pid_(getpid()), version_(version), now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700115}
116
117Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -0800118 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700119 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700120}
121
Felipe Leme46b85da2016-11-21 17:40:45 -0800122DurationReporter::DurationReporter(const std::string& title, bool log_only)
123 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700124 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800125 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800126 }
127}
128
129DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700130 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800131 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800132 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700133 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800134 } else {
135 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800136 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
137 title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800138 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800139 }
140}
141
Felipe Leme7447d7c2016-11-03 18:12:22 -0700142const int32_t Progress::kDefaultMax = 5000;
143
144Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
145}
146
147Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
148 : Progress(initial_max, growth_factor, "") {
149 progress_ = progress;
150}
151
152Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
153 : initial_max_(initial_max),
154 progress_(0),
155 max_(initial_max),
156 growth_factor_(growth_factor),
157 n_runs_(0),
158 average_max_(0),
159 path_(path) {
160 if (!path_.empty()) {
161 Load();
162 }
163}
164
165void Progress::Load() {
166 MYLOGD("Loading stats from %s\n", path_.c_str());
167 std::string content;
168 if (!android::base::ReadFileToString(path_, &content)) {
169 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
170 return;
171 }
172 if (content.empty()) {
173 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
174 return;
175 }
176 std::vector<std::string> lines = android::base::Split(content, "\n");
177
178 if (lines.size() < 1) {
179 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
180 (int)lines.size(), max_);
181 return;
182 }
183 char* ptr;
184 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
185 average_max_ = strtol(ptr, nullptr, 10);
186 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
187 average_max_ > STATS_MAX_AVERAGE) {
188 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
189 initial_max_ = Progress::kDefaultMax;
190 } else {
191 initial_max_ = average_max_;
192 }
193 max_ = initial_max_;
194
195 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
196}
197
198void Progress::Save() {
199 int32_t total = n_runs_ * average_max_ + progress_;
200 int32_t runs = n_runs_ + 1;
201 int32_t average = floor(((float)total) / runs);
202 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
203 path_.c_str());
204 if (path_.empty()) {
205 return;
206 }
207
208 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
209 if (!android::base::WriteStringToFile(content, path_)) {
210 MYLOGE("Could not save stats on %s\n", path_.c_str());
211 }
212}
213
214int32_t Progress::Get() const {
215 return progress_;
216}
217
218bool Progress::Inc(int32_t delta) {
219 bool changed = false;
220 if (delta >= 0) {
221 progress_ += delta;
222 if (progress_ > max_) {
223 int32_t old_max = max_;
224 max_ = floor((float)progress_ * growth_factor_);
225 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
226 changed = true;
227 }
228 }
229 return changed;
230}
231
232int32_t Progress::GetMax() const {
233 return max_;
234}
235
236int32_t Progress::GetInitialMax() const {
237 return initial_max_;
238}
239
240void Progress::Dump(int fd, const std::string& prefix) const {
241 const char* pr = prefix.c_str();
242 dprintf(fd, "%sprogress: %d\n", pr, progress_);
243 dprintf(fd, "%smax: %d\n", pr, max_);
244 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
245 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
246 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
247 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
248 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
249}
250
Felipe Leme75876a22016-10-27 16:31:27 -0700251bool Dumpstate::IsZipping() const {
252 return zip_writer_ != nullptr;
253}
254
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700255std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700256 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700257 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700258}
259
Vishnu Nair780b1282017-10-10 13:57:24 -0700260bool Dumpstate::CurrentVersionSupportsPriorityDumps() const {
261 return (version_ == VERSION_PRIORITY_DUMPS);
262}
263
Felipe Leme7447d7c2016-11-03 18:12:22 -0700264void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
265 progress_ = std::move(progress);
266}
267
John Spurlock5ecd4be2014-01-29 14:14:40 -0500268void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800269 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
270 "for_each_userid(%s)", header);
271 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800272 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700273
John Spurlock5ecd4be2014-01-29 14:14:40 -0500274 DIR *d;
275 struct dirent *de;
276
Felipe Lemed8b94e52016-12-08 10:21:44 -0800277 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500278 func(0);
279
280 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800281 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500282 return;
283 }
284
285 while ((de = readdir(d))) {
286 int userid;
287 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
288 continue;
289 }
290 func(userid);
291 }
292
293 closedir(d);
294}
295
Colin Cross0c22e8b2012-11-02 15:46:56 -0700296static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700297 DIR *d;
298 struct dirent *de;
299
300 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800301 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700302 return;
303 }
304
Felipe Lemed8b94e52016-12-08 10:21:44 -0800305 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700306 while ((de = readdir(d))) {
307 int pid;
308 int fd;
309 char cmdpath[255];
310 char cmdline[255];
311
312 if (!(pid = atoi(de->d_name))) {
313 continue;
314 }
315
Colin Crossf45fa6b2012-03-26 12:38:26 -0700316 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800317
318 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
319 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
320 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700321 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800322 if (cmdline[0]) {
323 helper(pid, cmdline, arg);
324 continue;
325 }
326 }
327
328 // if no cmdline, a kernel thread has comm
329 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
330 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
331 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
332 close(fd);
333 if (cmdline[1]) {
334 cmdline[0] = '[';
335 size_t len = strcspn(cmdline, "\f\b\r\n");
336 cmdline[len] = ']';
337 cmdline[len+1] = '\0';
338 }
339 }
340 if (!cmdline[0]) {
341 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700342 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700343 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700344 }
345
346 closedir(d);
347}
348
Colin Cross0c22e8b2012-11-02 15:46:56 -0700349static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800350 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700351 func(pid, cmdline);
352}
353
354void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800355 std::string title = header == nullptr ? "for_each_pid"
356 : android::base::StringPrintf("for_each_pid(%s)", header);
357 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800358 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700359
Felipe Leme515eb0d2015-12-14 15:09:56 -0800360 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700361}
362
363static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
364 DIR *d;
365 struct dirent *de;
366 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800367 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700368
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700369 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700370
371 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800372 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700373 return;
374 }
375
376 func(pid, pid, cmdline);
377
378 while ((de = readdir(d))) {
379 int tid;
380 int fd;
381 char commpath[255];
382 char comm[255];
383
384 if (!(tid = atoi(de->d_name))) {
385 continue;
386 }
387
388 if (tid == pid)
389 continue;
390
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700391 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800392 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700393 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700394 strcpy(comm, "N/A");
395 } else {
396 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800397 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700398 close(fd);
399
400 c = strrchr(comm, '\n');
401 if (c) {
402 *c = '\0';
403 }
404 }
405 func(pid, tid, comm);
406 }
407
408 closedir(d);
409}
410
411void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800412 std::string title = header == nullptr ? "for_each_tid"
413 : android::base::StringPrintf("for_each_tid(%s)", header);
414 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800415
Felipe Lemef0292972016-11-22 13:57:05 -0800416 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700417
Felipe Leme8620bb42015-11-10 11:04:45 -0800418 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700419}
420
421void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800422 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700423
Colin Crossf45fa6b2012-03-26 12:38:26 -0700424 char path[255];
425 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800426 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700427 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700428
429 memset(buffer, 0, sizeof(buffer));
430
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700431 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700432 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800433 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700434 return;
435 }
436
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800437 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
438 save_errno = errno;
439 close(fd);
440
441 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800442 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800443 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700444 }
445
Colin Cross0c22e8b2012-11-02 15:46:56 -0700446 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
447 pid == tid ? 0 : 3, "", name);
448
Felipe Lemed8b94e52016-12-08 10:21:44 -0800449 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700450
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800451 return;
452}
453
454// print time in centiseconds
455static void snprcent(char *buffer, size_t len, size_t spc,
456 unsigned long long time) {
457 static long hz; // cache discovered hz
458
459 if (hz <= 0) {
460 hz = sysconf(_SC_CLK_TCK);
461 if (hz <= 0) {
462 hz = 1000;
463 }
464 }
465
466 // convert to centiseconds
467 time = (time * 100 + (hz / 2)) / hz;
468
469 char str[16];
470
471 snprintf(str, sizeof(str), " %llu.%02u",
472 time / 100, (unsigned)(time % 100));
473 size_t offset = strlen(buffer);
474 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
475 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
476}
477
478// print permille as a percent
479static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
480 char str[16];
481
482 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
483 size_t offset = strlen(buffer);
484 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
485 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
486}
487
488void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800489 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700490
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800491 char path[255];
492 char buffer[1023];
493 int fd, ret, save_errno;
494
495 memset(buffer, 0, sizeof(buffer));
496
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700497 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800498 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800499 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800500 return;
501 }
502
503 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
504 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700505 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800506
507 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800508 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800509 return;
510 }
511
512 // field 14 is utime
513 // field 15 is stime
514 // field 42 is iotime
515 unsigned long long utime = 0, stime = 0, iotime = 0;
516 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800517 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
518 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
519 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
520 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800521 &utime, &stime, &iotime) != 3) {
522 return;
523 }
524
525 unsigned long long total = utime + stime;
526 if (!total) {
527 return;
528 }
529
530 unsigned permille = (iotime * 1000 + (total / 2)) / total;
531 if (permille > 1000) {
532 permille = 1000;
533 }
534
535 // try to beautify and stabilize columns at <80 characters
536 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
537 if ((name[0] != '[') || utime) {
538 snprcent(buffer, sizeof(buffer), 57, utime);
539 }
540 snprcent(buffer, sizeof(buffer), 65, stime);
541 if ((name[0] != '[') || iotime) {
542 snprcent(buffer, sizeof(buffer), 73, iotime);
543 }
544 if (iotime) {
545 snprdec(buffer, sizeof(buffer), 79, permille);
546 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800547 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800548
Colin Crossf45fa6b2012-03-26 12:38:26 -0700549 return;
550}
551
552void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800553 const char *title = "KERNEL LOG (dmesg)";
554 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800555 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800556
Felipe Lemef0292972016-11-22 13:57:05 -0800557 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700558
Elliott Hughes5f87b312012-09-17 11:43:40 -0700559 /* Get size of kernel buffer */
560 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700561 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800562 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700563 return;
564 }
565 char *buf = (char *) malloc(size + 1);
566 if (buf == NULL) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800567 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700568 return;
569 }
570 int retval = klogctl(KLOG_READ_ALL, buf, size);
571 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800572 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700573 free(buf);
574 return;
575 }
576 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800577 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700578 free(buf);
579 return;
580}
581
582void do_showmap(int pid, const char *name) {
583 char title[255];
584 char arg[255];
585
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700586 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
587 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800588 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800589}
590
Felipe Leme678727a2016-09-21 17:22:11 -0700591int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700592 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800593
Felipe Lemef0292972016-11-22 13:57:05 -0800594 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800595
Felipe Lemef0292972016-11-22 13:57:05 -0800596 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800597
Felipe Leme46b85da2016-11-21 17:40:45 -0800598 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800599}
600
Felipe Leme71a74ac2016-03-17 15:43:25 -0700601int read_file_as_long(const char *path, long int *output) {
602 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
603 if (fd < 0) {
604 int err = errno;
605 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
606 return -1;
607 }
608 char buffer[50];
609 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
610 if (bytes_read == -1) {
611 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
612 return -2;
613 }
614 if (bytes_read == 0) {
615 MYLOGE("File %s is empty\n", path);
616 return -3;
617 }
618 *output = atoi(buffer);
619 return 0;
620}
621
Mark Salyzyn326842f2015-04-30 09:49:41 -0700622/* calls skip to gate calling dump_from_fd recursively
623 * in the specified directory. dump_from_fd defaults to
624 * dump_file_from_fd above when set to NULL. skip defaults
625 * to false when set to NULL. dump_from_fd will always be
626 * called with title NULL.
627 */
Felipe Leme678727a2016-09-21 17:22:11 -0700628int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
629 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800630 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700631 DIR *dirp;
632 struct dirent *d;
633 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800634 const char *slash = "/";
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100635 int retval = 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700636
Felipe Leme678727a2016-09-21 17:22:11 -0700637 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800638 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700639 }
Felipe Lemef0292972016-11-22 13:57:05 -0800640 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700641
642 if (dir[strlen(dir) - 1] == '/') {
643 ++slash;
644 }
645 dirp = opendir(dir);
646 if (dirp == NULL) {
647 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800648 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700649 return retval;
650 }
651
652 if (!dump_from_fd) {
653 dump_from_fd = dump_file_from_fd;
654 }
655 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
656 if ((d->d_name[0] == '.')
657 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
658 || (d->d_name[1] == '\0'))) {
659 continue;
660 }
661 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
662 (d->d_type == DT_DIR) ? "/" : "");
663 if (!newpath) {
664 retval = -errno;
665 continue;
666 }
667 if (skip && (*skip)(newpath)) {
668 continue;
669 }
670 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700671 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700672 if (ret < 0) {
673 retval = ret;
674 }
675 continue;
676 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100677 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
678 if (fd.get() < 0) {
679 retval = -1;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800680 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700681 continue;
682 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100683 (*dump_from_fd)(NULL, newpath, fd.get());
Mark Salyzyn326842f2015-04-30 09:49:41 -0700684 }
685 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700686 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800687 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700688 }
689 return retval;
690}
691
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800692/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
693 * it's possible to avoid issues where opening the file itself can get
694 * stuck.
695 */
696int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800697 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700698
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800699 int flags = fcntl(fd, F_GETFL);
700 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800701 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800702 return -1;
703 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800704 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800705 return -1;
706 }
Felipe Lemef0292972016-11-22 13:57:05 -0800707 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700708}
709
Felipe Leme46b85da2016-11-21 17:40:45 -0800710int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
711 const CommandOptions& options) {
712 DurationReporter duration_reporter(title);
713
Felipe Lemef0292972016-11-22 13:57:05 -0800714 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800715
Felipe Lemef0292972016-11-22 13:57:05 -0800716 /* TODO: for now we're simplifying the progress calculation by using the
717 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
718 * where its weight should be much higher proportionally to its timeout.
719 * Ideally, it should use a options.EstimatedDuration() instead...*/
720 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800721
Felipe Leme46b85da2016-11-21 17:40:45 -0800722 return status;
723}
724
Felipe Leme9a523ae2016-10-20 15:10:33 -0700725void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700726 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700727 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
728 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700729 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700730 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700731}
732
Felipe Leme2628e9e2016-04-12 16:36:51 -0700733int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700734 int s = android_get_control_socket(service);
735 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800736 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700737 exit(1);
738 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700739 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700740 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800741 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700742 exit(1);
743 }
744
745 struct sockaddr addr;
746 socklen_t alen = sizeof(addr);
747 int fd = accept(s, &addr, &alen);
748 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800749 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700750 exit(1);
751 }
752
Felipe Leme2628e9e2016-04-12 16:36:51 -0700753 return fd;
754}
755
756/* redirect output to a service control socket */
757void redirect_to_socket(FILE *redirect, const char *service) {
758 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700759 fflush(redirect);
760 dup2(fd, fileno(redirect));
761 close(fd);
762}
763
Felipe Leme2628e9e2016-04-12 16:36:51 -0700764// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800765void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800766 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700767
768 /* skip initial slash */
769 if (chp[0] == '/')
770 chp++;
771
772 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800773 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700774 while (chp && chp[0]) {
775 chp = strchr(chp, '/');
776 if (chp) {
777 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800778 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800779 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800780 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800781 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800782 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800783 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800784 }
785 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700786 *chp++ = '/';
787 }
788 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800789}
790
Felipe Leme0f3fb202016-06-10 17:10:53 -0700791void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800792 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700793
Felipe Leme0f3fb202016-06-10 17:10:53 -0700794 int fd = TEMP_FAILURE_RETRY(open(path,
795 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800796 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700797 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800798 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700799 exit(1);
800 }
801
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800802 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700803 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700804}
805
Felipe Leme0f3fb202016-06-10 17:10:53 -0700806void redirect_to_file(FILE *redirect, char *path) {
807 _redirect_to_file(redirect, path, O_TRUNC);
808}
809
810void redirect_to_existing_file(FILE *redirect, char *path) {
811 _redirect_to_file(redirect, path, O_APPEND);
812}
813
Steven Moreland17b29e12017-03-21 18:38:05 -0700814static bool should_dump_hal_interface(const char* interface) {
815 for (const char** i = hal_interfaces_to_dump; *i; i++) {
816 if (!strcmp(*i, interface)) {
817 return true;
818 }
819 }
820 return false;
821}
822
Jeff Brownbf7f4922012-06-07 16:40:01 -0700823static bool should_dump_native_traces(const char* path) {
824 for (const char** p = native_processes_to_dump; *p; p++) {
825 if (!strcmp(*p, path)) {
826 return true;
827 }
828 }
829 return false;
830}
831
Steven Moreland17b29e12017-03-21 18:38:05 -0700832std::set<int> get_interesting_hal_pids() {
833 using android::hidl::manager::V1_0::IServiceManager;
834 using android::sp;
835 using android::hardware::Return;
836
837 sp<IServiceManager> manager = IServiceManager::getService();
838 std::set<int> pids;
839
840 Return<void> ret = manager->debugDump([&](auto& hals) {
841 for (const auto &info : hals) {
842 if (info.pid == static_cast<int>(IServiceManager::PidConstant::NO_PID)) {
843 continue;
844 }
845
Scott Randolph5a0c4852017-04-03 14:05:49 -0700846 if (!should_dump_hal_interface(info.interfaceName.c_str())) {
Steven Moreland17b29e12017-03-21 18:38:05 -0700847 continue;
848 }
849
850 pids.insert(info.pid);
851 }
852 });
853
854 if (!ret.isOk()) {
855 MYLOGE("Could not get list of HAL PIDs: %s\n", ret.description().c_str());
856 }
857
858 return pids; // whether it was okay or not
859}
860
Narayan Kamath8f788292017-05-25 13:20:39 +0100861const char* DumpTraces(const std::string& traces_path);
862const char* DumpTracesTombstoned(const std::string& traces_dir);
863
Jeff Brownbf7f4922012-06-07 16:40:01 -0700864/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
865const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -0700866 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -0700867
Narayan Kamath8f788292017-05-25 13:20:39 +0100868 const std::string traces_dir = android::base::GetProperty("dalvik.vm.stack-trace-dir", "");
869 if (!traces_dir.empty()) {
870 return DumpTracesTombstoned(traces_dir);
871 }
Jeff Brownbf7f4922012-06-07 16:40:01 -0700872
Narayan Kamath8f788292017-05-25 13:20:39 +0100873 const std::string traces_file = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
874 if (!traces_file.empty()) {
875 return DumpTraces(traces_file);
876 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700877
Narayan Kamath8f788292017-05-25 13:20:39 +0100878 return nullptr;
879}
880
881static bool IsZygote(int pid) {
882 static const std::string kZygotePrefix = "zygote";
883
884 std::string cmdline;
885 if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid),
886 &cmdline)) {
887 return true;
888 }
889
890 return (cmdline.find(kZygotePrefix) == 0);
891}
892
893const char* DumpTracesTombstoned(const std::string& traces_dir) {
894 const std::string temp_file_pattern = traces_dir + "/dumptrace_XXXXXX";
895
896 const size_t buf_size = temp_file_pattern.length() + 1;
897 std::unique_ptr<char[]> file_name_buf(new char[buf_size]);
898 memcpy(file_name_buf.get(), temp_file_pattern.c_str(), buf_size);
899
900 // Create a new, empty file to receive all trace dumps.
901 //
902 // TODO: This can be simplified once we remove support for the old style
903 // dumps. We can have a file descriptor passed in to dump_traces instead
904 // of creating a file, closing it and then reopening it again.
905 android::base::unique_fd fd(mkostemp(file_name_buf.get(), O_APPEND | O_CLOEXEC));
906 if (fd < 0) {
907 MYLOGE("mkostemp on pattern %s: %s\n", file_name_buf.get(), strerror(errno));
908 return nullptr;
909 }
910
911 // Nobody should have access to this temporary file except dumpstate, but we
912 // temporarily grant 'read' to 'others' here because this file is created
913 // when tombstoned is still running as root, but dumped after dropping. This
914 // can go away once support for old style dumping has.
915 const int chmod_ret = fchmod(fd, 0666);
916 if (chmod_ret < 0) {
917 MYLOGE("fchmod on %s failed: %s\n", file_name_buf.get(), strerror(errno));
918 return nullptr;
919 }
920
921 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
922 if (proc.get() == nullptr) {
923 MYLOGE("opendir /proc failed: %s\n", strerror(errno));
924 return nullptr;
925 }
926
927 // Number of times process dumping has timed out. If we encounter too many
928 // failures, we'll give up.
929 int timeout_failures = 0;
930 bool dalvik_found = false;
931
932 const std::set<int> hal_pids = get_interesting_hal_pids();
933
934 struct dirent* d;
935 while ((d = readdir(proc.get()))) {
936 int pid = atoi(d->d_name);
937 if (pid <= 0) {
938 continue;
939 }
940
941 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
942 std::string exe;
943 if (!android::base::Readlink(link_name, &exe)) {
944 continue;
945 }
946
947 bool is_java_process;
948 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
949 // Don't bother dumping backtraces for the zygote.
950 if (IsZygote(pid)) {
951 continue;
952 }
953
954 dalvik_found = true;
955 is_java_process = true;
956 } else if (should_dump_native_traces(exe.c_str()) || hal_pids.find(pid) != hal_pids.end()) {
957 is_java_process = false;
958 } else {
959 // Probably a native process we don't care about, continue.
960 continue;
961 }
962
963 // If 3 backtrace dumps fail in a row, consider debuggerd dead.
964 if (timeout_failures == 3) {
965 dprintf(fd, "ERROR: Too many stack dump failures, exiting.\n");
966 break;
967 }
968
969 const uint64_t start = Nanotime();
970 const int ret = dump_backtrace_to_file_timeout(
971 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
972 is_java_process ? 5 : 20, fd);
973
974 if (ret == -1) {
975 dprintf(fd, "dumping failed, likely due to a timeout\n");
976 timeout_failures++;
977 continue;
978 }
979
980 // We've successfully dumped stack traces, reset the failure count
981 // and write a summary of the elapsed time to the file and continue with the
982 // next process.
983 timeout_failures = 0;
984
985 dprintf(fd, "[dump %s stack %d: %.3fs elapsed]\n", is_java_process ? "dalvik" : "native",
986 pid, (float)(Nanotime() - start) / NANOS_PER_SEC);
987 }
988
989 if (!dalvik_found) {
990 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
991 }
992
993 return file_name_buf.release();
994}
995
996const char* DumpTraces(const std::string& traces_path) {
997 const char* result = NULL;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700998 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -0700999 std::string anrtraces_path = traces_path + ".anr";
1000 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
1001 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001002 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001003 }
1004
Colin Crossf45fa6b2012-03-26 12:38:26 -07001005 /* create a new, empty traces.txt file to receive stack dumps */
Josh Gao989b8122017-01-13 22:09:40 -08001006 int fd = TEMP_FAILURE_RETRY(
Josh Gaoe75d9632017-01-18 16:14:03 -08001007 open(traces_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
Josh Gao989b8122017-01-13 22:09:40 -08001008 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001009 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001010 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001011 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001012 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001013 int chmod_ret = fchmod(fd, 0666);
1014 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001015 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001016 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001017 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001018 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001019
Felipe Leme8620bb42015-11-10 11:04:45 -08001020 /* Variables below must be initialized before 'goto' statements */
1021 int dalvik_found = 0;
1022 int ifd, wfd = -1;
Steven Moreland17b29e12017-03-21 18:38:05 -07001023 std::set<int> hal_pids = get_interesting_hal_pids();
Felipe Leme8620bb42015-11-10 11:04:45 -08001024
Colin Crossf45fa6b2012-03-26 12:38:26 -07001025 /* walk /proc and kill -QUIT all Dalvik processes */
1026 DIR *proc = opendir("/proc");
1027 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001028 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001029 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001030 }
1031
1032 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001033 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001034 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001035 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001036 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001037 }
1038
Felipe Lemee184f662016-10-27 10:04:47 -07001039 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001040 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001041 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001042 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001043 }
1044
1045 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001046 while ((d = readdir(proc))) {
1047 int pid = atoi(d->d_name);
1048 if (pid <= 0) continue;
1049
Jeff Brownbf7f4922012-06-07 16:40:01 -07001050 char path[PATH_MAX];
1051 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001052 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001053 ssize_t len = readlink(path, data, sizeof(data) - 1);
1054 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001055 continue;
1056 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001057 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001058
Colin Cross0d6180f2014-07-16 19:00:46 -07001059 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001060 /* skip zygote -- it won't dump its stack anyway */
1061 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001062 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001063 len = read(cfd, data, sizeof(data) - 1);
1064 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001065 if (len <= 0) {
1066 continue;
1067 }
1068 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001069 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001070 continue;
1071 }
1072
1073 ++dalvik_found;
Felipe Lemef0292972016-11-22 13:57:05 -08001074 uint64_t start = Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001075 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001076 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001077 continue;
1078 }
1079
1080 /* wait for the writable-close notification from inotify */
1081 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001082 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001083 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001084 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001085 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001086 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001087 } else {
1088 struct inotify_event ie;
1089 read(ifd, &ie, sizeof(ie));
1090 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001091
1092 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001093 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001094 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001095 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -08001096 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001097 }
Steven Moreland17b29e12017-03-21 18:38:05 -07001098 } else if (should_dump_native_traces(data) ||
1099 hal_pids.find(pid) != hal_pids.end()) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001100 /* dump native process if appropriate */
1101 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001102 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001103 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001104 static uint16_t timeout_failures = 0;
Felipe Lemef0292972016-11-22 13:57:05 -08001105 uint64_t start = Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001106
1107 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1108 if (timeout_failures == 3) {
1109 dprintf(fd, "too many stack dump failures, skipping...\n");
Narayan Kamath93b36d12017-05-31 10:33:28 +01001110 } else if (dump_backtrace_to_file_timeout(
1111 pid, kDebuggerdNativeBacktrace, 20, fd) == -1) {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001112 dprintf(fd, "dumping failed, likely due to a timeout\n");
1113 timeout_failures++;
1114 } else {
1115 timeout_failures = 0;
1116 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001117 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
Felipe Lemef0292972016-11-22 13:57:05 -08001118 (float)(Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001119 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001120 }
1121 }
1122
Colin Crossf45fa6b2012-03-26 12:38:26 -07001123 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001124 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001125 }
1126
Felipe Lemee184f662016-10-27 10:04:47 -07001127 static std::string dumptraces_path = android::base::StringPrintf(
1128 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
1129 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
1130 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
1131 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001132 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001133 }
Felipe Lemee184f662016-10-27 10:04:47 -07001134 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001135
1136 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -07001137 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001138
1139error_close_ifd:
1140 close(ifd);
1141error_close_fd:
1142 close(fd);
1143 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001144}
1145
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001146void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001147 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -08001148 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001149 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001150 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001151 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001152 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001153 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001154 return;
1155 }
1156 char table[16];
1157 // Each line has an integer (the table number), a space, and a string (the table name). We only
1158 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1159 // Add a fixed max limit so this doesn't go awry.
1160 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001161 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1162 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001163 }
1164 fclose(fp);
1165}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001166
Felipe Leme71bbfc52015-11-23 14:14:51 -08001167// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001168void Dumpstate::UpdateProgress(int32_t delta) {
1169 if (progress_ == nullptr) {
1170 MYLOGE("UpdateProgress: progress_ not set\n");
1171 return;
1172 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001173
Felipe Leme7447d7c2016-11-03 18:12:22 -07001174 // Always update progess so stats can be tuned...
1175 bool max_changed = progress_->Inc(delta);
1176
1177 // ...but only notifiy listeners when necessary.
1178 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001179
Felipe Leme009ecbb2016-11-07 10:18:44 -08001180 int progress = progress_->Get();
1181 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -08001182
1183 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -08001184 if (max_changed && listener_ != nullptr) {
1185 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001186 }
1187
Felipe Leme009ecbb2016-11-07 10:18:44 -08001188 int32_t last_update_delta = progress - last_updated_progress_;
1189 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1190 return;
1191 }
1192 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001193
Felipe Leme9a523ae2016-10-20 15:10:33 -07001194 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001195 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001196 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001197 }
1198
Felipe Leme75876a22016-10-27 16:31:27 -07001199 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001200 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001201 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001202 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001203 } else {
1204 // stderr is ignored on normal invocations, but useful when calling
1205 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001206 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001207 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001208 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001209 }
1210}
Felipe Lemee338bf62015-12-07 14:03:50 -08001211
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001212void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001213 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001214 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001215 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001216 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1217 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001218 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001219 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001220 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001221 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001222}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001223
Felipe Leme0c80cf02016-01-05 13:25:34 -08001224bool is_dir(const char* pathname) {
1225 struct stat info;
1226 if (stat(pathname, &info) == -1) {
1227 return false;
1228 }
1229 return S_ISDIR(info.st_mode);
1230}
1231
1232time_t get_mtime(int fd, time_t default_mtime) {
1233 struct stat info;
1234 if (fstat(fd, &info) == -1) {
1235 return default_mtime;
1236 }
1237 return info.st_mtime;
1238}
1239
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001240void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001241 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001242 struct hex {
1243 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001244 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001245 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1246 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1247 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1248 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1249
1250 std::string buffer;
1251 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1252 return;
1253 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001254
Felipe Lemed8b94e52016-12-08 10:21:44 -08001255 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001256
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001257 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001258 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001259 return;
1260 }
1261
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001262 int ext_csd_rev = 0;
1263 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1264 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001265 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001266 return;
1267 }
1268
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001269 static const char *ver_str[] = {
1270 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1271 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001272 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1273 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1274 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001275 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001276 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001277 return;
1278 }
1279
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001280 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001281 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001282 return;
1283 }
1284
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001285 int ext_pre_eol_info = 0;
1286 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1287 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001288 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001289 return;
1290 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001291
1292 static const char *eol_str[] = {
1293 "Undefined",
1294 "Normal",
1295 "Warning (consumed 80% of reserve)",
1296 "Urgent (consumed 90% of reserve)"
1297 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001298 printf(
1299 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -08001300 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1301 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001302
1303 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1304 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001305 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001306 int ext_device_life_time_est;
1307 static const char *est_str[] = {
1308 "Undefined",
1309 "0-10% of device lifetime used",
1310 "10-20% of device lifetime used",
1311 "20-30% of device lifetime used",
1312 "30-40% of device lifetime used",
1313 "40-50% of device lifetime used",
1314 "50-60% of device lifetime used",
1315 "60-70% of device lifetime used",
1316 "70-80% of device lifetime used",
1317 "80-90% of device lifetime used",
1318 "90-100% of device lifetime used",
1319 "Exceeded the maximum estimated device lifetime",
1320 };
1321
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001322 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001323 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001324 break;
1325 }
1326
1327 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001328 sub = buffer.substr(lifetime, sizeof(hex));
1329 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001330 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1331 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1332 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001333 continue;
1334 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001335 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1336 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1337 ext_device_life_time_est,
1338 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1339 ? ext_device_life_time_est
1340 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001341 }
1342
Felipe Lemed8b94e52016-12-08 10:21:44 -08001343 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001344}