blob: 1eccea565298f2d24bd57a8da43f015b68cea2b7 [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Felipe Lemef0292972016-11-22 13:57:05 -080017#define LOG_TAG "dumpstate"
18
19#include "dumpstate.h"
20
Colin Crossf45fa6b2012-03-26 12:38:26 -070021#include <dirent.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070022#include <fcntl.h>
Felipe Lemee184f662016-10-27 10:04:47 -070023#include <libgen.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070024#include <math.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070025#include <poll.h>
26#include <signal.h>
27#include <stdarg.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080031#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/inotify.h>
Felipe Lemee184f662016-10-27 10:04:47 -070033#include <sys/klog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070034#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070035#include <sys/stat.h>
36#include <sys/time.h>
37#include <sys/wait.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038#include <time.h>
39#include <unistd.h>
Mark Salyzyn261a7332016-05-24 12:38:40 -070040
Narayan Kamath8f788292017-05-25 13:20:39 +010041#include <memory>
Steven Moreland17b29e12017-03-21 18:38:05 -070042#include <set>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070043#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080044#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070045
Mark Salyzyn290f4b92016-05-16 08:33:59 -070046#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070047#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070048#include <android-base/stringprintf.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070049#include <android-base/strings.h>
Narayan Kamath8f788292017-05-25 13:20:39 +010050#include <android-base/unique_fd.h>
Steven Moreland17b29e12017-03-21 18:38:05 -070051#include <android/hidl/manager/1.0/IServiceManager.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070052#include <cutils/properties.h>
53#include <cutils/sockets.h>
Josh Gaod2db0242017-01-05 18:27:33 -080054#include <debuggerd/client.h>
Mark Salyzyn4eb13822017-01-12 13:57:51 -080055#include <log/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070056#include <private/android_filesystem_config.h>
57
Felipe Lemef0292972016-11-22 13:57:05 -080058#include "DumpstateInternal.h"
Jeff Brown1dc94e32014-09-11 14:15:27 -070059
Felipe Leme47e9be22016-12-21 15:37:07 -080060// TODO: remove once moved to namespace
61using android::os::dumpstate::CommandOptions;
62using android::os::dumpstate::DumpFileToFd;
63using android::os::dumpstate::PropertiesHelper;
64
Brian Carlstroma3322752017-03-19 17:48:01 -070065// Keep in sync with
66// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
Felipe Leme61884122016-06-13 09:23:30 -070067static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
68
Felipe Lemef0292972016-11-22 13:57:05 -080069/* Most simple commands have 10 as timeout, so 5 is a good estimate */
70static const int32_t WEIGHT_FILE = 5;
71
Felipe Lemee844a9d2016-09-21 15:01:39 -070072// TODO: temporary variables and functions used during C++ refactoring
73static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070074static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070075 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070076 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070077}
Felipe Lemee844a9d2016-09-21 15:01:39 -070078
Jeff Brownbf7f4922012-06-07 16:40:01 -070079/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070080// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070081static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080082 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080083 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070084 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070085 "/system/bin/mediadrmserver",
86 "/system/bin/mediaextractor", // media.extractor
Andy Hung756655c2018-01-04 12:09:50 -080087 "/system/bin/mediametrics", // media.metrics
Jeff Brownbf7f4922012-06-07 16:40:01 -070088 "/system/bin/mediaserver",
89 "/system/bin/sdcard",
Andreas Gampea3127a72018-01-24 17:55:55 -080090 "/system/bin/statsd",
Jeff Brownbf7f4922012-06-07 16:40:01 -070091 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070092 "/system/bin/vehicle_network_service",
Chong Zhangde00ee42017-06-02 16:13:16 -070093 "/vendor/bin/hw/android.hardware.media.omx@1.0-service", // media.codec
Jeff Brownbf7f4922012-06-07 16:40:01 -070094 NULL,
95};
96
Steven Moreland17b29e12017-03-21 18:38:05 -070097/* list of hal interface to dump containing process during native dumps */
98static const char* hal_interfaces_to_dump[] {
99 "android.hardware.audio@2.0::IDevicesFactory",
100 "android.hardware.bluetooth@1.0::IBluetoothHci",
101 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu108c0f02017-04-20 14:31:50 -0700102 "android.hardware.graphics.composer@2.1::IComposer",
Steven Moreland17b29e12017-03-21 18:38:05 -0700103 "android.hardware.media.omx@1.0::IOmx",
Peng Xuf1ab0ac2017-07-11 21:14:42 -0700104 "android.hardware.sensors@1.0::ISensors",
105 "android.hardware.vr@1.0::IVr",
Steven Moreland17b29e12017-03-21 18:38:05 -0700106 NULL,
107};
108
Felipe Leme7447d7c2016-11-03 18:12:22 -0700109// Reasonable value for max stats.
110static const int STATS_MAX_N_RUNS = 1000;
111static const long STATS_MAX_AVERAGE = 100000;
112
Felipe Lemebda15a02016-11-16 17:48:25 -0800113CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -0700114
Felipe Lemef0292972016-11-22 13:57:05 -0800115Dumpstate::Dumpstate(const std::string& version)
116 : pid_(getpid()), version_(version), now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700117}
118
119Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -0800120 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700121 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700122}
123
Felipe Leme46b85da2016-11-21 17:40:45 -0800124DurationReporter::DurationReporter(const std::string& title, bool log_only)
125 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700126 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800127 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800128 }
129}
130
131DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700132 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800133 uint64_t elapsed = Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800134 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700135 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800136 } else {
137 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800138 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
139 title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800140 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800141 }
142}
143
Felipe Leme7447d7c2016-11-03 18:12:22 -0700144const int32_t Progress::kDefaultMax = 5000;
145
146Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
147}
148
149Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
150 : Progress(initial_max, growth_factor, "") {
151 progress_ = progress;
152}
153
154Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
155 : initial_max_(initial_max),
156 progress_(0),
157 max_(initial_max),
158 growth_factor_(growth_factor),
159 n_runs_(0),
160 average_max_(0),
161 path_(path) {
162 if (!path_.empty()) {
163 Load();
164 }
165}
166
167void Progress::Load() {
168 MYLOGD("Loading stats from %s\n", path_.c_str());
169 std::string content;
170 if (!android::base::ReadFileToString(path_, &content)) {
171 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
172 return;
173 }
174 if (content.empty()) {
175 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
176 return;
177 }
178 std::vector<std::string> lines = android::base::Split(content, "\n");
179
180 if (lines.size() < 1) {
181 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
182 (int)lines.size(), max_);
183 return;
184 }
185 char* ptr;
186 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
187 average_max_ = strtol(ptr, nullptr, 10);
188 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
189 average_max_ > STATS_MAX_AVERAGE) {
190 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
191 initial_max_ = Progress::kDefaultMax;
192 } else {
193 initial_max_ = average_max_;
194 }
195 max_ = initial_max_;
196
197 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
198}
199
200void Progress::Save() {
201 int32_t total = n_runs_ * average_max_ + progress_;
202 int32_t runs = n_runs_ + 1;
203 int32_t average = floor(((float)total) / runs);
204 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
205 path_.c_str());
206 if (path_.empty()) {
207 return;
208 }
209
210 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
211 if (!android::base::WriteStringToFile(content, path_)) {
212 MYLOGE("Could not save stats on %s\n", path_.c_str());
213 }
214}
215
216int32_t Progress::Get() const {
217 return progress_;
218}
219
220bool Progress::Inc(int32_t delta) {
221 bool changed = false;
222 if (delta >= 0) {
223 progress_ += delta;
224 if (progress_ > max_) {
225 int32_t old_max = max_;
226 max_ = floor((float)progress_ * growth_factor_);
227 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
228 changed = true;
229 }
230 }
231 return changed;
232}
233
234int32_t Progress::GetMax() const {
235 return max_;
236}
237
238int32_t Progress::GetInitialMax() const {
239 return initial_max_;
240}
241
242void Progress::Dump(int fd, const std::string& prefix) const {
243 const char* pr = prefix.c_str();
244 dprintf(fd, "%sprogress: %d\n", pr, progress_);
245 dprintf(fd, "%smax: %d\n", pr, max_);
246 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
247 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
248 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
249 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
250 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
251}
252
Felipe Leme75876a22016-10-27 16:31:27 -0700253bool Dumpstate::IsZipping() const {
254 return zip_writer_ != nullptr;
255}
256
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700257std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700258 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700259 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700260}
261
Felipe Leme7447d7c2016-11-03 18:12:22 -0700262void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
263 progress_ = std::move(progress);
264}
265
John Spurlock5ecd4be2014-01-29 14:14:40 -0500266void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800267 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
268 "for_each_userid(%s)", header);
269 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800270 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700271
John Spurlock5ecd4be2014-01-29 14:14:40 -0500272 DIR *d;
273 struct dirent *de;
274
Felipe Lemed8b94e52016-12-08 10:21:44 -0800275 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500276 func(0);
277
278 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800279 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500280 return;
281 }
282
283 while ((de = readdir(d))) {
284 int userid;
285 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
286 continue;
287 }
288 func(userid);
289 }
290
291 closedir(d);
292}
293
Colin Cross0c22e8b2012-11-02 15:46:56 -0700294static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700295 DIR *d;
296 struct dirent *de;
297
298 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800299 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700300 return;
301 }
302
Felipe Lemed8b94e52016-12-08 10:21:44 -0800303 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700304 while ((de = readdir(d))) {
305 int pid;
306 int fd;
307 char cmdpath[255];
308 char cmdline[255];
309
310 if (!(pid = atoi(de->d_name))) {
311 continue;
312 }
313
Colin Crossf45fa6b2012-03-26 12:38:26 -0700314 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800315
316 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
317 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
318 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700319 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800320 if (cmdline[0]) {
321 helper(pid, cmdline, arg);
322 continue;
323 }
324 }
325
326 // if no cmdline, a kernel thread has comm
327 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
328 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
329 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
330 close(fd);
331 if (cmdline[1]) {
332 cmdline[0] = '[';
333 size_t len = strcspn(cmdline, "\f\b\r\n");
334 cmdline[len] = ']';
335 cmdline[len+1] = '\0';
336 }
337 }
338 if (!cmdline[0]) {
339 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700340 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700341 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700342 }
343
344 closedir(d);
345}
346
Colin Cross0c22e8b2012-11-02 15:46:56 -0700347static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800348 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700349 func(pid, cmdline);
350}
351
352void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800353 std::string title = header == nullptr ? "for_each_pid"
354 : android::base::StringPrintf("for_each_pid(%s)", header);
355 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800356 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700357
Felipe Leme515eb0d2015-12-14 15:09:56 -0800358 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700359}
360
361static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
362 DIR *d;
363 struct dirent *de;
364 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800365 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700366
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700367 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700368
369 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800370 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700371 return;
372 }
373
374 func(pid, pid, cmdline);
375
376 while ((de = readdir(d))) {
377 int tid;
378 int fd;
379 char commpath[255];
380 char comm[255];
381
382 if (!(tid = atoi(de->d_name))) {
383 continue;
384 }
385
386 if (tid == pid)
387 continue;
388
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700389 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800390 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700391 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700392 strcpy(comm, "N/A");
393 } else {
394 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800395 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700396 close(fd);
397
398 c = strrchr(comm, '\n');
399 if (c) {
400 *c = '\0';
401 }
402 }
403 func(pid, tid, comm);
404 }
405
406 closedir(d);
407}
408
409void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800410 std::string title = header == nullptr ? "for_each_tid"
411 : android::base::StringPrintf("for_each_tid(%s)", header);
412 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800413
Felipe Lemef0292972016-11-22 13:57:05 -0800414 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700415
Felipe Leme8620bb42015-11-10 11:04:45 -0800416 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700417}
418
419void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800420 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700421
Colin Crossf45fa6b2012-03-26 12:38:26 -0700422 char path[255];
423 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800424 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700425 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700426
427 memset(buffer, 0, sizeof(buffer));
428
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700429 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700430 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800431 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700432 return;
433 }
434
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800435 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
436 save_errno = errno;
437 close(fd);
438
439 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800440 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800441 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700442 }
443
Colin Cross0c22e8b2012-11-02 15:46:56 -0700444 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
445 pid == tid ? 0 : 3, "", name);
446
Felipe Lemed8b94e52016-12-08 10:21:44 -0800447 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700448
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800449 return;
450}
451
452// print time in centiseconds
453static void snprcent(char *buffer, size_t len, size_t spc,
454 unsigned long long time) {
455 static long hz; // cache discovered hz
456
457 if (hz <= 0) {
458 hz = sysconf(_SC_CLK_TCK);
459 if (hz <= 0) {
460 hz = 1000;
461 }
462 }
463
464 // convert to centiseconds
465 time = (time * 100 + (hz / 2)) / hz;
466
467 char str[16];
468
469 snprintf(str, sizeof(str), " %llu.%02u",
470 time / 100, (unsigned)(time % 100));
471 size_t offset = strlen(buffer);
472 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
473 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
474}
475
476// print permille as a percent
477static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
478 char str[16];
479
480 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
481 size_t offset = strlen(buffer);
482 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
483 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
484}
485
486void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800487 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700488
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800489 char path[255];
490 char buffer[1023];
491 int fd, ret, save_errno;
492
493 memset(buffer, 0, sizeof(buffer));
494
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700495 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800496 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800497 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800498 return;
499 }
500
501 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
502 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700503 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800504
505 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800506 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800507 return;
508 }
509
510 // field 14 is utime
511 // field 15 is stime
512 // field 42 is iotime
513 unsigned long long utime = 0, stime = 0, iotime = 0;
514 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800515 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
516 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
517 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
518 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800519 &utime, &stime, &iotime) != 3) {
520 return;
521 }
522
523 unsigned long long total = utime + stime;
524 if (!total) {
525 return;
526 }
527
528 unsigned permille = (iotime * 1000 + (total / 2)) / total;
529 if (permille > 1000) {
530 permille = 1000;
531 }
532
533 // try to beautify and stabilize columns at <80 characters
534 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
535 if ((name[0] != '[') || utime) {
536 snprcent(buffer, sizeof(buffer), 57, utime);
537 }
538 snprcent(buffer, sizeof(buffer), 65, stime);
539 if ((name[0] != '[') || iotime) {
540 snprcent(buffer, sizeof(buffer), 73, iotime);
541 }
542 if (iotime) {
543 snprdec(buffer, sizeof(buffer), 79, permille);
544 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800545 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800546
Colin Crossf45fa6b2012-03-26 12:38:26 -0700547 return;
548}
549
550void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800551 const char *title = "KERNEL LOG (dmesg)";
552 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800553 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800554
Felipe Lemef0292972016-11-22 13:57:05 -0800555 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700556
Elliott Hughes5f87b312012-09-17 11:43:40 -0700557 /* Get size of kernel buffer */
Yi Kong19d5c002018-07-20 13:39:55 -0700558 int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700559 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800560 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700561 return;
562 }
563 char *buf = (char *) malloc(size + 1);
Yi Kong19d5c002018-07-20 13:39:55 -0700564 if (buf == nullptr) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800565 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700566 return;
567 }
568 int retval = klogctl(KLOG_READ_ALL, buf, size);
569 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800570 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700571 free(buf);
572 return;
573 }
574 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800575 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700576 free(buf);
577 return;
578}
579
580void do_showmap(int pid, const char *name) {
581 char title[255];
582 char arg[255];
583
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700584 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
585 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800586 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800587}
588
Felipe Leme678727a2016-09-21 17:22:11 -0700589int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700590 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800591
Felipe Lemef0292972016-11-22 13:57:05 -0800592 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800593
Felipe Lemef0292972016-11-22 13:57:05 -0800594 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800595
Felipe Leme46b85da2016-11-21 17:40:45 -0800596 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800597}
598
Felipe Leme71a74ac2016-03-17 15:43:25 -0700599int read_file_as_long(const char *path, long int *output) {
600 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
601 if (fd < 0) {
602 int err = errno;
603 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
604 return -1;
605 }
606 char buffer[50];
607 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
608 if (bytes_read == -1) {
609 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
610 return -2;
611 }
612 if (bytes_read == 0) {
613 MYLOGE("File %s is empty\n", path);
614 return -3;
615 }
616 *output = atoi(buffer);
617 return 0;
618}
619
Mark Salyzyn326842f2015-04-30 09:49:41 -0700620/* calls skip to gate calling dump_from_fd recursively
621 * in the specified directory. dump_from_fd defaults to
622 * dump_file_from_fd above when set to NULL. skip defaults
623 * to false when set to NULL. dump_from_fd will always be
624 * called with title NULL.
625 */
Felipe Leme678727a2016-09-21 17:22:11 -0700626int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
627 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800628 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700629 DIR *dirp;
630 struct dirent *d;
Yi Kong19d5c002018-07-20 13:39:55 -0700631 char *newpath = nullptr;
Felipe Leme8620bb42015-11-10 11:04:45 -0800632 const char *slash = "/";
Narayan Kamathd3badba2017-10-27 11:15:51 +0100633 int retval = 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700634
Felipe Leme678727a2016-09-21 17:22:11 -0700635 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800636 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700637 }
Felipe Lemef0292972016-11-22 13:57:05 -0800638 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700639
640 if (dir[strlen(dir) - 1] == '/') {
641 ++slash;
642 }
643 dirp = opendir(dir);
Yi Kong19d5c002018-07-20 13:39:55 -0700644 if (dirp == nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700645 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800646 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700647 return retval;
648 }
649
650 if (!dump_from_fd) {
651 dump_from_fd = dump_file_from_fd;
652 }
Yi Kong19d5c002018-07-20 13:39:55 -0700653 for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700654 if ((d->d_name[0] == '.')
655 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
656 || (d->d_name[1] == '\0'))) {
657 continue;
658 }
659 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
660 (d->d_type == DT_DIR) ? "/" : "");
661 if (!newpath) {
662 retval = -errno;
663 continue;
664 }
665 if (skip && (*skip)(newpath)) {
666 continue;
667 }
668 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700669 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700670 if (ret < 0) {
671 retval = ret;
672 }
673 continue;
674 }
Narayan Kamathd3badba2017-10-27 11:15:51 +0100675 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
676 if (fd.get() < 0) {
677 retval = -1;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800678 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700679 continue;
680 }
Yi Kong19d5c002018-07-20 13:39:55 -0700681 (*dump_from_fd)(nullptr, newpath, fd.get());
Mark Salyzyn326842f2015-04-30 09:49:41 -0700682 }
683 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700684 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800685 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700686 }
687 return retval;
688}
689
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800690/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
691 * it's possible to avoid issues where opening the file itself can get
692 * stuck.
693 */
694int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800695 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700696
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800697 int flags = fcntl(fd, F_GETFL);
698 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800699 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800700 return -1;
701 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800702 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800703 return -1;
704 }
Felipe Lemef0292972016-11-22 13:57:05 -0800705 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700706}
707
Felipe Leme46b85da2016-11-21 17:40:45 -0800708int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
709 const CommandOptions& options) {
710 DurationReporter duration_reporter(title);
711
Felipe Lemef0292972016-11-22 13:57:05 -0800712 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800713
Felipe Lemef0292972016-11-22 13:57:05 -0800714 /* TODO: for now we're simplifying the progress calculation by using the
715 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
716 * where its weight should be much higher proportionally to its timeout.
717 * Ideally, it should use a options.EstimatedDuration() instead...*/
718 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800719
Felipe Leme46b85da2016-11-21 17:40:45 -0800720 return status;
721}
722
Felipe Leme9a523ae2016-10-20 15:10:33 -0700723void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700724 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700725 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
726 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700727 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700728 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700729}
730
Felipe Leme2628e9e2016-04-12 16:36:51 -0700731int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700732 int s = android_get_control_socket(service);
733 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800734 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700735 exit(1);
736 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700737 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700738 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800739 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700740 exit(1);
741 }
742
743 struct sockaddr addr;
744 socklen_t alen = sizeof(addr);
745 int fd = accept(s, &addr, &alen);
746 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800747 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700748 exit(1);
749 }
750
Felipe Leme2628e9e2016-04-12 16:36:51 -0700751 return fd;
752}
753
754/* redirect output to a service control socket */
755void redirect_to_socket(FILE *redirect, const char *service) {
756 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700757 fflush(redirect);
758 dup2(fd, fileno(redirect));
759 close(fd);
760}
761
Felipe Leme2628e9e2016-04-12 16:36:51 -0700762// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800763void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800764 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700765
766 /* skip initial slash */
767 if (chp[0] == '/')
768 chp++;
769
770 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800771 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700772 while (chp && chp[0]) {
773 chp = strchr(chp, '/');
774 if (chp) {
775 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800776 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800777 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800778 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800779 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800780 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800781 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800782 }
783 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700784 *chp++ = '/';
785 }
786 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800787}
788
Felipe Leme0f3fb202016-06-10 17:10:53 -0700789void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800790 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700791
Felipe Leme0f3fb202016-06-10 17:10:53 -0700792 int fd = TEMP_FAILURE_RETRY(open(path,
793 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800794 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700795 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800796 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700797 exit(1);
798 }
799
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800800 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700801 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700802}
803
Felipe Leme0f3fb202016-06-10 17:10:53 -0700804void redirect_to_file(FILE *redirect, char *path) {
805 _redirect_to_file(redirect, path, O_TRUNC);
806}
807
808void redirect_to_existing_file(FILE *redirect, char *path) {
809 _redirect_to_file(redirect, path, O_APPEND);
810}
811
Steven Moreland17b29e12017-03-21 18:38:05 -0700812static bool should_dump_hal_interface(const char* interface) {
813 for (const char** i = hal_interfaces_to_dump; *i; i++) {
814 if (!strcmp(*i, interface)) {
815 return true;
816 }
817 }
818 return false;
819}
820
Jeff Brownbf7f4922012-06-07 16:40:01 -0700821static bool should_dump_native_traces(const char* path) {
822 for (const char** p = native_processes_to_dump; *p; p++) {
823 if (!strcmp(*p, path)) {
824 return true;
825 }
826 }
827 return false;
828}
829
Steven Moreland17b29e12017-03-21 18:38:05 -0700830std::set<int> get_interesting_hal_pids() {
831 using android::hidl::manager::V1_0::IServiceManager;
832 using android::sp;
833 using android::hardware::Return;
834
835 sp<IServiceManager> manager = IServiceManager::getService();
836 std::set<int> pids;
837
838 Return<void> ret = manager->debugDump([&](auto& hals) {
839 for (const auto &info : hals) {
840 if (info.pid == static_cast<int>(IServiceManager::PidConstant::NO_PID)) {
841 continue;
842 }
843
Scott Randolph5a0c4852017-04-03 14:05:49 -0700844 if (!should_dump_hal_interface(info.interfaceName.c_str())) {
Steven Moreland17b29e12017-03-21 18:38:05 -0700845 continue;
846 }
847
848 pids.insert(info.pid);
849 }
850 });
851
852 if (!ret.isOk()) {
853 MYLOGE("Could not get list of HAL PIDs: %s\n", ret.description().c_str());
854 }
855
856 return pids; // whether it was okay or not
857}
858
Narayan Kamath8f788292017-05-25 13:20:39 +0100859static bool IsZygote(int pid) {
860 static const std::string kZygotePrefix = "zygote";
861
862 std::string cmdline;
863 if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid),
864 &cmdline)) {
865 return true;
866 }
867
868 return (cmdline.find(kZygotePrefix) == 0);
869}
870
Elliott Hughesd9fe0382018-03-23 11:04:25 -0700871// Dump Dalvik and native stack traces, return the trace file location (nullptr if none).
872const char* dump_traces() {
873 DurationReporter duration_reporter("DUMP TRACES");
874
875 const std::string temp_file_pattern = "/data/anr/dumptrace_XXXXXX";
Narayan Kamath8f788292017-05-25 13:20:39 +0100876
877 const size_t buf_size = temp_file_pattern.length() + 1;
878 std::unique_ptr<char[]> file_name_buf(new char[buf_size]);
879 memcpy(file_name_buf.get(), temp_file_pattern.c_str(), buf_size);
880
881 // Create a new, empty file to receive all trace dumps.
882 //
883 // TODO: This can be simplified once we remove support for the old style
884 // dumps. We can have a file descriptor passed in to dump_traces instead
885 // of creating a file, closing it and then reopening it again.
886 android::base::unique_fd fd(mkostemp(file_name_buf.get(), O_APPEND | O_CLOEXEC));
887 if (fd < 0) {
888 MYLOGE("mkostemp on pattern %s: %s\n", file_name_buf.get(), strerror(errno));
889 return nullptr;
890 }
891
892 // Nobody should have access to this temporary file except dumpstate, but we
893 // temporarily grant 'read' to 'others' here because this file is created
894 // when tombstoned is still running as root, but dumped after dropping. This
895 // can go away once support for old style dumping has.
896 const int chmod_ret = fchmod(fd, 0666);
897 if (chmod_ret < 0) {
898 MYLOGE("fchmod on %s failed: %s\n", file_name_buf.get(), strerror(errno));
899 return nullptr;
900 }
901
902 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
903 if (proc.get() == nullptr) {
904 MYLOGE("opendir /proc failed: %s\n", strerror(errno));
905 return nullptr;
906 }
907
908 // Number of times process dumping has timed out. If we encounter too many
909 // failures, we'll give up.
910 int timeout_failures = 0;
911 bool dalvik_found = false;
912
913 const std::set<int> hal_pids = get_interesting_hal_pids();
914
915 struct dirent* d;
916 while ((d = readdir(proc.get()))) {
917 int pid = atoi(d->d_name);
918 if (pid <= 0) {
919 continue;
920 }
921
922 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
923 std::string exe;
924 if (!android::base::Readlink(link_name, &exe)) {
925 continue;
926 }
927
928 bool is_java_process;
929 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
930 // Don't bother dumping backtraces for the zygote.
931 if (IsZygote(pid)) {
932 continue;
933 }
934
935 dalvik_found = true;
936 is_java_process = true;
937 } else if (should_dump_native_traces(exe.c_str()) || hal_pids.find(pid) != hal_pids.end()) {
938 is_java_process = false;
939 } else {
940 // Probably a native process we don't care about, continue.
941 continue;
942 }
943
944 // If 3 backtrace dumps fail in a row, consider debuggerd dead.
945 if (timeout_failures == 3) {
946 dprintf(fd, "ERROR: Too many stack dump failures, exiting.\n");
947 break;
948 }
949
950 const uint64_t start = Nanotime();
951 const int ret = dump_backtrace_to_file_timeout(
952 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
953 is_java_process ? 5 : 20, fd);
954
955 if (ret == -1) {
956 dprintf(fd, "dumping failed, likely due to a timeout\n");
957 timeout_failures++;
958 continue;
959 }
960
961 // We've successfully dumped stack traces, reset the failure count
962 // and write a summary of the elapsed time to the file and continue with the
963 // next process.
964 timeout_failures = 0;
965
966 dprintf(fd, "[dump %s stack %d: %.3fs elapsed]\n", is_java_process ? "dalvik" : "native",
967 pid, (float)(Nanotime() - start) / NANOS_PER_SEC);
968 }
969
970 if (!dalvik_found) {
971 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
972 }
973
974 return file_name_buf.release();
975}
976
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700977void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800978 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -0800979 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700980 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -0700981 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700982 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700983 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800984 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700985 return;
986 }
987 char table[16];
988 // Each line has an integer (the table number), a space, and a string (the table name). We only
989 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
990 // Add a fixed max limit so this doesn't go awry.
991 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700992 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
993 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700994 }
995 fclose(fp);
996}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800997
Felipe Leme71bbfc52015-11-23 14:14:51 -0800998// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700999void Dumpstate::UpdateProgress(int32_t delta) {
1000 if (progress_ == nullptr) {
1001 MYLOGE("UpdateProgress: progress_ not set\n");
1002 return;
1003 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001004
Felipe Leme7447d7c2016-11-03 18:12:22 -07001005 // Always update progess so stats can be tuned...
1006 bool max_changed = progress_->Inc(delta);
1007
1008 // ...but only notifiy listeners when necessary.
1009 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001010
Felipe Leme009ecbb2016-11-07 10:18:44 -08001011 int progress = progress_->Get();
1012 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -08001013
1014 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -08001015 if (max_changed && listener_ != nullptr) {
1016 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001017 }
1018
Felipe Leme009ecbb2016-11-07 10:18:44 -08001019 int32_t last_update_delta = progress - last_updated_progress_;
1020 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1021 return;
1022 }
1023 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001024
Felipe Leme9a523ae2016-10-20 15:10:33 -07001025 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001026 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001027 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001028 }
1029
Felipe Leme75876a22016-10-27 16:31:27 -07001030 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001031 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001032 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001033 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001034 } else {
1035 // stderr is ignored on normal invocations, but useful when calling
1036 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001037 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001038 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001039 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001040 }
1041}
Felipe Lemee338bf62015-12-07 14:03:50 -08001042
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001043void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001044 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001045 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001046 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001047 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1048 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001049 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001050 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001051 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001052 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001053}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001054
Felipe Leme0c80cf02016-01-05 13:25:34 -08001055bool is_dir(const char* pathname) {
1056 struct stat info;
1057 if (stat(pathname, &info) == -1) {
1058 return false;
1059 }
1060 return S_ISDIR(info.st_mode);
1061}
1062
1063time_t get_mtime(int fd, time_t default_mtime) {
1064 struct stat info;
1065 if (fstat(fd, &info) == -1) {
1066 return default_mtime;
1067 }
1068 return info.st_mtime;
1069}
1070
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001071void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001072 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001073 struct hex {
1074 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001075 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001076 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1077 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1078 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1079 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1080
1081 std::string buffer;
1082 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1083 return;
1084 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001085
Felipe Lemed8b94e52016-12-08 10:21:44 -08001086 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001087
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001088 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001089 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001090 return;
1091 }
1092
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001093 int ext_csd_rev = 0;
1094 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1095 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001096 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001097 return;
1098 }
1099
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001100 static const char *ver_str[] = {
1101 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1102 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001103 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1104 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1105 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001106 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001107 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001108 return;
1109 }
1110
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001111 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001112 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001113 return;
1114 }
1115
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001116 int ext_pre_eol_info = 0;
1117 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1118 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001119 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001120 return;
1121 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001122
1123 static const char *eol_str[] = {
1124 "Undefined",
1125 "Normal",
1126 "Warning (consumed 80% of reserve)",
1127 "Urgent (consumed 90% of reserve)"
1128 };
Felipe Lemed8b94e52016-12-08 10:21:44 -08001129 printf(
1130 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -08001131 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1132 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001133
1134 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1135 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001136 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001137 int ext_device_life_time_est;
1138 static const char *est_str[] = {
1139 "Undefined",
1140 "0-10% of device lifetime used",
1141 "10-20% of device lifetime used",
1142 "20-30% of device lifetime used",
1143 "30-40% of device lifetime used",
1144 "40-50% of device lifetime used",
1145 "50-60% of device lifetime used",
1146 "60-70% of device lifetime used",
1147 "70-80% of device lifetime used",
1148 "80-90% of device lifetime used",
1149 "90-100% of device lifetime used",
1150 "Exceeded the maximum estimated device lifetime",
1151 };
1152
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001153 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001154 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001155 break;
1156 }
1157
1158 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001159 sub = buffer.substr(lifetime, sizeof(hex));
1160 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -08001161 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1162 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1163 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001164 continue;
1165 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001166 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1167 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1168 ext_device_life_time_est,
1169 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1170 ? ext_device_life_time_est
1171 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001172 }
1173
Felipe Lemed8b94e52016-12-08 10:21:44 -08001174 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001175}