blob: b475c90c04fded3af667ca3221ffa076a278aa88 [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 */
Felipe Lemef0292972016-11-22 13:57:05 -080016
Mark Salyzyn6c3d90f2016-09-27 14:55:27 -070017#define LOG_TAG "dumpstate"
Colin Crossf45fa6b2012-03-26 12:38:26 -070018
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -070019#include <dirent.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070020#include <errno.h>
21#include <fcntl.h>
Nikita Ioffea325a572019-05-16 19:49:47 +010022#include <inttypes.h>
Felipe Lemead5f6c42015-11-30 14:26:46 -080023#include <libgen.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070024#include <limits.h>
Abhijeet Kaurcf234e82019-07-01 14:53:55 +010025#include <math.h>
26#include <poll.h>
Mark Salyzyn8f37aa52015-06-12 12:28:24 -070027#include <stdbool.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070028#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Vishnu Naire97d6122018-01-18 13:58:56 -080031#include <sys/poll.h>
Christopher Ferris7dc7f322014-07-22 16:08:19 -070032#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070033#include <sys/resource.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <sys/wait.h>
Abhijeet Kaurcf234e82019-07-01 14:53:55 +010037#include <signal.h>
38#include <stdarg.h>
39#include <string.h>
40#include <sys/capability.h>
41#include <sys/inotify.h>
42#include <sys/klog.h>
43#include <time.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070044#include <unistd.h>
Luis Hector Chavez7aecd382018-03-19 11:16:59 -070045
46#include <chrono>
Hridya Valsarajuac582cd2019-08-05 15:39:54 -070047#include <cmath>
Abhijeet Kaurd3cca0d2019-03-25 12:04:16 +000048#include <fstream>
Luis Hector Chavez7aecd382018-03-19 11:16:59 -070049#include <functional>
50#include <future>
Narayan Kamath8f788292017-05-25 13:20:39 +010051#include <memory>
Hridya Valsarajuac582cd2019-08-05 15:39:54 -070052#include <numeric>
Narayan Kamath8f788292017-05-25 13:20:39 +010053#include <regex>
54#include <set>
55#include <string>
Luis Hector Chavez7aecd382018-03-19 11:16:59 -070056#include <utility>
Narayan Kamath8f788292017-05-25 13:20:39 +010057#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070058
Felipe Leme96c2bbb2016-09-26 09:21:21 -070059#include <android-base/file.h>
60#include <android-base/properties.h>
Luis Hector Chavez7aecd382018-03-19 11:16:59 -070061#include <android-base/scopeguard.h>
Elliott Hughes9dc117c2015-12-07 14:21:50 -080062#include <android-base/stringprintf.h>
Naveen Kalla058e1e82016-10-19 21:38:44 -070063#include <android-base/strings.h>
Andreas Gampeaff68432016-07-18 18:01:27 -070064#include <android-base/unique_fd.h>
Nikita Ioffea325a572019-05-16 19:49:47 +010065#include <android/content/pm/IPackageManagerNative.h>
Felipe Leme6f674ae2016-11-18 17:10:33 -080066#include <android/hardware/dumpstate/1.0/IDumpstateDevice.h>
Hunter Knepshield8540faf2020-02-04 19:47:20 -080067#include <android/hardware/dumpstate/1.1/IDumpstateDevice.h>
68#include <android/hardware/dumpstate/1.1/types.h>
Steven Moreland44cd9482018-01-04 16:24:13 -080069#include <android/hidl/manager/1.0/IServiceManager.h>
Nandana Duttd2f5f082019-01-18 17:13:52 +000070#include <android/os/IIncidentCompanion.h>
Nikita Ioffea325a572019-05-16 19:49:47 +010071#include <binder/IServiceManager.h>
Felipe Leme6f674ae2016-11-18 17:10:33 -080072#include <cutils/native_handle.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070073#include <cutils/properties.h>
Abhijeet Kaurcf234e82019-07-01 14:53:55 +010074#include <cutils/sockets.h>
Nandana Duttfaafd522019-03-11 09:23:09 +000075#include <debuggerd/client.h>
Vishnu Naire97d6122018-01-18 13:58:56 -080076#include <dumpsys.h>
Nandana Duttfaafd522019-03-11 09:23:09 +000077#include <dumputils/dump_utils.h>
Sahana Raof35ed432019-07-12 10:47:52 +010078#include <hardware_legacy/power.h>
Steven Moreland44cd9482018-01-04 16:24:13 -080079#include <hidl/ServiceManagement.h>
Abhijeet Kaurcf234e82019-07-01 14:53:55 +010080#include <log/log.h>
Felipe Leme75876a22016-10-27 16:31:27 -070081#include <openssl/sha.h>
Mark Salyzyn6c3d90f2016-09-27 14:55:27 -070082#include <private/android_filesystem_config.h>
83#include <private/android_logger.h>
Vishnu Naire97d6122018-01-18 13:58:56 -080084#include <serviceutils/PriorityDumper.h>
Luis Hector Chavez7aecd382018-03-19 11:16:59 -070085#include <utils/StrongPointer.h>
Felipe Lemef0292972016-11-22 13:57:05 -080086#include "DumpstateInternal.h"
Felipe Leme75876a22016-10-27 16:31:27 -070087#include "DumpstateService.h"
Colin Crossf45fa6b2012-03-26 12:38:26 -070088#include "dumpstate.h"
Felipe Leme6e01fa62015-11-11 19:35:14 -080089
Hunter Knepshield8540faf2020-02-04 19:47:20 -080090using IDumpstateDevice_1_0 = ::android::hardware::dumpstate::V1_0::IDumpstateDevice;
91using IDumpstateDevice_1_1 = ::android::hardware::dumpstate::V1_1::IDumpstateDevice;
92using ::android::hardware::dumpstate::V1_1::DumpstateMode;
93using ::android::hardware::dumpstate::V1_1::DumpstateStatus;
94using ::android::hardware::dumpstate::V1_1::toString;
Vishnu Naire97d6122018-01-18 13:58:56 -080095using ::std::literals::chrono_literals::operator""ms;
96using ::std::literals::chrono_literals::operator""s;
Steven Morelandcb7ef822016-11-29 13:20:37 -080097
Felipe Leme47e9be22016-12-21 15:37:07 -080098// TODO: remove once moved to namespace
Vishnu Naire97d6122018-01-18 13:58:56 -080099using android::defaultServiceManager;
100using android::Dumpsys;
101using android::INVALID_OPERATION;
102using android::IServiceManager;
103using android::OK;
104using android::sp;
105using android::status_t;
106using android::String16;
107using android::String8;
108using android::TIMED_OUT;
109using android::UNKNOWN_ERROR;
110using android::Vector;
Nandana Dutt979388e2018-11-30 16:48:55 +0000111using android::base::StringPrintf;
Nandana Duttd2f5f082019-01-18 17:13:52 +0000112using android::os::IDumpstateListener;
Felipe Leme47e9be22016-12-21 15:37:07 -0800113using android::os::dumpstate::CommandOptions;
114using android::os::dumpstate::DumpFileToFd;
Vishnu Naire97d6122018-01-18 13:58:56 -0800115using android::os::dumpstate::PropertiesHelper;
Felipe Leme47e9be22016-12-21 15:37:07 -0800116
Abhijeet Kaurcf234e82019-07-01 14:53:55 +0100117// Keep in sync with
118// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
119static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
120
121/* Most simple commands have 10 as timeout, so 5 is a good estimate */
122static const int32_t WEIGHT_FILE = 5;
123
124// TODO: temporary variables and functions used during C++ refactoring
125static Dumpstate& ds = Dumpstate::GetInstance();
126static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Nandana Dutt8d945c02019-08-14 13:30:07 +0100127 const CommandOptions& options = CommandOptions::DEFAULT,
128 bool verbose_duration = false) {
129 return ds.RunCommand(title, full_command, options, verbose_duration);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +0100130}
131
132// Reasonable value for max stats.
133static const int STATS_MAX_N_RUNS = 1000;
134static const long STATS_MAX_AVERAGE = 100000;
135
136CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
137
Nandana Duttd2f5f082019-01-18 17:13:52 +0000138typedef Dumpstate::ConsentCallback::ConsentResult UserConsentResult;
139
Colin Crossf45fa6b2012-03-26 12:38:26 -0700140/* read before root is shed */
141static char cmdline_buf[16384] = "(unknown)";
Yi Kong19d5c002018-07-20 13:39:55 -0700142static const char *dump_traces_path = nullptr;
Nandana Duttd2f5f082019-01-18 17:13:52 +0000143static const uint64_t USER_CONSENT_TIMEOUT_MS = 30 * 1000;
Hunter Knepshield70610fa2020-01-03 15:27:33 -0800144// Because telephony reports are significantly faster to collect (< 10 seconds vs. > 2 minutes),
145// it's often the case that they time out far too quickly for consent with such a hefty dialog for
146// the user to read. For telephony reports only, we increase the default timeout to 2 minutes to
147// roughly match full reports' durations.
148static const uint64_t TELEPHONY_REPORT_USER_CONSENT_TIMEOUT_MS = 2 * 60 * 1000;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700149
Felipe Leme1d486fe2016-10-14 18:06:47 -0700150// TODO: variables and functions below should be part of dumpstate object
151
Felipe Leme635ca312016-01-05 14:23:02 -0800152static std::set<std::string> mount_points;
153void add_mountinfo();
Felipe Leme78f2c862015-12-21 09:55:22 -0800154
Todd Poynor2a83daa2013-11-22 15:44:22 -0800155#define PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops"
Mark Salyzyn7d0a7622016-06-24 14:06:15 -0700156#define ALT_PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops-0"
Wei Wang509bb5d2017-06-09 14:42:12 -0700157#define BLK_DEV_SYS_DIR "/sys/block"
Todd Poynor2a83daa2013-11-22 15:44:22 -0800158
Felipe Lemee82a27d2016-01-05 13:35:44 -0800159#define RECOVERY_DIR "/cache/recovery"
Mark Salyzynd6ab0112016-03-25 12:56:39 -0700160#define RECOVERY_DATA_DIR "/data/misc/recovery"
Tianjie Xu75d53362018-04-11 16:42:28 -0700161#define UPDATE_ENGINE_LOG_DIR "/data/misc/update_engine_log"
Mark Salyzyn4d42dea2016-04-01 10:03:14 -0700162#define LOGPERSIST_DATA_DIR "/data/misc/logd"
Jerry Changa1df8a92020-01-02 16:03:39 +0800163#define PREREBOOT_DATA_DIR "/data/misc/prereboot"
David Brazdild2991962016-06-03 14:40:44 +0100164#define PROFILE_DATA_DIR_CUR "/data/misc/profiles/cur"
165#define PROFILE_DATA_DIR_REF "/data/misc/profiles/ref"
Benedict Wong8f9d8a42019-01-03 16:19:38 -0800166#define XFRM_STAT_PROC_FILE "/proc/net/xfrm_stat"
Erik Kline08165202016-05-30 11:55:44 +0900167#define WLUTIL "/vendor/xbin/wlutil"
Vishnu Nair36b4cdb2017-11-17 10:27:05 -0800168#define WMTRACE_DATA_DIR "/data/misc/wmtrace"
Yifan Hong3945e1b2019-10-29 12:59:23 -0700169#define OTA_METADATA_DIR "/metadata/ota"
Yifan Hong0efa7972020-02-03 16:45:02 -0800170#define SNAPSHOTCTL_LOG_DIR "/data/misc/snapshotctl_log"
Kiyoung Kimc2d22ac2020-02-04 19:43:36 +0900171#define LINKERCONFIG_DIR "/linkerconfig"
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700172
Narayan Kamath8f788292017-05-25 13:20:39 +0100173// TODO(narayan): Since this information has to be kept in sync
174// with tombstoned, we should just put it in a common header.
175//
176// File: system/core/debuggerd/tombstoned/tombstoned.cpp
Narayan Kamathbd863722017-06-01 18:50:12 +0100177static const std::string TOMBSTONE_DIR = "/data/tombstones/";
178static const std::string TOMBSTONE_FILE_PREFIX = "tombstone_";
179static const std::string ANR_DIR = "/data/anr/";
180static const std::string ANR_FILE_PREFIX = "anr_";
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700181
Felipe Lemee844a9d2016-09-21 15:01:39 -0700182// TODO: temporary variables and functions used during C++ refactoring
Nandana Dutt979388e2018-11-30 16:48:55 +0000183
Nandana Dutt5c390032019-03-12 10:52:56 +0000184#define RETURN_IF_USER_DENIED_CONSENT() \
185 if (ds.IsUserConsentDenied()) { \
186 MYLOGE("Returning early as user denied consent to share bugreport with calling app."); \
187 return Dumpstate::RunStatus::USER_CONSENT_DENIED; \
188 }
189
190// Runs func_ptr, but checks user consent before and after running it. Returns USER_CONSENT_DENIED
191// if consent is found to be denied.
192#define RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(func_ptr, ...) \
193 RETURN_IF_USER_DENIED_CONSENT(); \
194 func_ptr(__VA_ARGS__); \
195 RETURN_IF_USER_DENIED_CONSENT();
196
Sahana Raof35ed432019-07-12 10:47:52 +0100197static const char* WAKE_LOCK_NAME = "dumpstate_wakelock";
198
Nandana Dutt979388e2018-11-30 16:48:55 +0000199namespace android {
200namespace os {
201namespace {
202
203static int Open(std::string path, int flags, mode_t mode = 0) {
204 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
205 if (fd == -1) {
206 MYLOGE("open(%s, %s)\n", path.c_str(), strerror(errno));
207 }
208 return fd;
209}
210
Nandana Dutt979388e2018-11-30 16:48:55 +0000211
212static int OpenForRead(std::string path) {
213 return Open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
214}
215
216bool CopyFile(int in_fd, int out_fd) {
217 char buf[4096];
218 ssize_t byte_count;
219 while ((byte_count = TEMP_FAILURE_RETRY(read(in_fd, buf, sizeof(buf)))) > 0) {
220 if (!android::base::WriteFully(out_fd, buf, byte_count)) {
221 return false;
222 }
223 }
224 return (byte_count != -1);
225}
226
227static bool CopyFileToFd(const std::string& input_file, int out_fd) {
Nandana Dutt16d1aee2019-02-15 16:13:53 +0000228 MYLOGD("Going to copy file (%s) to %d\n", input_file.c_str(), out_fd);
Nandana Dutt979388e2018-11-30 16:48:55 +0000229
230 // Obtain a handle to the source file.
231 android::base::unique_fd in_fd(OpenForRead(input_file));
232 if (out_fd != -1 && in_fd.get() != -1) {
233 if (CopyFile(in_fd.get(), out_fd)) {
234 return true;
235 }
Nandana Dutt16d1aee2019-02-15 16:13:53 +0000236 MYLOGE("Failed to copy file: %s\n", strerror(errno));
Nandana Dutt979388e2018-11-30 16:48:55 +0000237 }
238 return false;
239}
240
Nandana Duttd2f5f082019-01-18 17:13:52 +0000241static bool UnlinkAndLogOnError(const std::string& file) {
Nandana Dutt8ae16e62020-03-27 10:20:22 +0000242 if (file.empty()) {
243 return false;
244 }
Nandana Dutt16d1aee2019-02-15 16:13:53 +0000245 if (unlink(file.c_str())) {
246 MYLOGE("Failed to unlink file (%s): %s\n", file.c_str(), strerror(errno));
Nandana Duttd2f5f082019-01-18 17:13:52 +0000247 return false;
248 }
249 return true;
250}
Nandana Dutt979388e2018-11-30 16:48:55 +0000251
Nikita Ioffea325a572019-05-16 19:49:47 +0100252int64_t GetModuleMetadataVersion() {
253 auto binder = defaultServiceManager()->getService(android::String16("package_native"));
254 if (binder == nullptr) {
255 MYLOGE("Failed to retrieve package_native service");
256 return 0L;
257 }
258 auto package_service = android::interface_cast<content::pm::IPackageManagerNative>(binder);
259 std::string package_name;
260 auto status = package_service->getModuleMetadataPackageName(&package_name);
261 if (!status.isOk()) {
262 MYLOGE("Failed to retrieve module metadata package name: %s", status.toString8().c_str());
263 return 0L;
264 }
Nandana Duttdb379fa2019-10-09 16:54:41 +0100265 MYLOGD("Module metadata package name: %s\n", package_name.c_str());
Nikita Ioffea325a572019-05-16 19:49:47 +0100266 int64_t version_code;
267 status = package_service->getVersionCodeForPackage(android::String16(package_name.c_str()),
268 &version_code);
269 if (!status.isOk()) {
270 MYLOGE("Failed to retrieve module metadata version: %s", status.toString8().c_str());
271 return 0L;
272 }
273 return version_code;
274}
275
Nandana Dutt979388e2018-11-30 16:48:55 +0000276} // namespace
277} // namespace os
278} // namespace android
279
Felipe Leme678727a2016-09-21 17:22:11 -0700280static void RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
Felipe Lemebda15a02016-11-16 17:48:25 -0800281 const CommandOptions& options = Dumpstate::DEFAULT_DUMPSYS,
Vishnu Nair6921f802017-11-22 09:17:23 -0800282 long dumpsysTimeoutMs = 0) {
283 return ds.RunDumpsys(title, dumpsysArgs, options, dumpsysTimeoutMs);
Felipe Leme678727a2016-09-21 17:22:11 -0700284}
285static int DumpFile(const std::string& title, const std::string& path) {
286 return ds.DumpFile(title, path);
287}
Felipe Lemee82a27d2016-01-05 13:35:44 -0800288
Felipe Lemee844a9d2016-09-21 15:01:39 -0700289// Relative directory (inside the zip) for all files copied as-is into the bugreport.
290static const std::string ZIP_ROOT_DIR = "FS";
291
Vishnu Naire97d6122018-01-18 13:58:56 -0800292static const std::string kProtoPath = "proto/";
293static const std::string kProtoExt = ".proto";
Jie Song9fbfad02017-06-20 16:29:42 -0700294static const std::string kDumpstateBoardFiles[] = {
295 "dumpstate_board.txt",
Felipe Leme95d6ca52017-08-01 16:35:56 -0700296 "dumpstate_board.bin"
Jie Song9fbfad02017-06-20 16:29:42 -0700297};
298static const int NUM_OF_DUMPS = arraysize(kDumpstateBoardFiles);
299
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700300static constexpr char PROPERTY_LAST_ID[] = "dumpstate.last_id";
Felipe Lemed071c682016-10-20 16:48:00 -0700301static constexpr char PROPERTY_VERSION[] = "dumpstate.version";
Felipe Leme9ce6aa42016-09-21 10:02:25 -0700302
Felipe Lemef0292972016-11-22 13:57:05 -0800303static const CommandOptions AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
304
Narayan Kamath8f788292017-05-25 13:20:39 +0100305/*
Narayan Kamathbd863722017-06-01 18:50:12 +0100306 * Returns a vector of dump fds under |dir_path| with a given |file_prefix|.
307 * The returned vector is sorted by the mtimes of the dumps. If |limit_by_mtime|
308 * is set, the vector only contains files that were written in the last 30 minutes.
Narayan Kamath8f788292017-05-25 13:20:39 +0100309 */
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -0700310static std::vector<DumpData> GetDumpFds(const std::string& dir_path,
311 const std::string& file_prefix,
Elliott Hughesdb6d2112019-09-26 15:24:51 -0700312 bool limit_by_mtime) {
Narayan Kamath8f788292017-05-25 13:20:39 +0100313 const time_t thirty_minutes_ago = ds.now_ - 60 * 30;
314
Narayan Kamathbd863722017-06-01 18:50:12 +0100315 std::unique_ptr<DIR, decltype(&closedir)> dump_dir(opendir(dir_path.c_str()), closedir);
Narayan Kamath8f788292017-05-25 13:20:39 +0100316
Luis Hector Chavezd0512712018-03-14 12:15:56 -0700317 if (dump_dir == nullptr) {
318 MYLOGW("Unable to open directory %s: %s\n", dir_path.c_str(), strerror(errno));
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -0700319 return std::vector<DumpData>();
Luis Hector Chavezd0512712018-03-14 12:15:56 -0700320 }
321
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -0700322 std::vector<DumpData> dump_data;
Narayan Kamathbd863722017-06-01 18:50:12 +0100323 struct dirent* entry = nullptr;
324 while ((entry = readdir(dump_dir.get()))) {
325 if (entry->d_type != DT_REG) {
Narayan Kamath8f788292017-05-25 13:20:39 +0100326 continue;
327 }
328
Narayan Kamathbd863722017-06-01 18:50:12 +0100329 const std::string base_name(entry->d_name);
330 if (base_name.find(file_prefix) != 0) {
331 continue;
332 }
333
334 const std::string abs_path = dir_path + base_name;
335 android::base::unique_fd fd(
336 TEMP_FAILURE_RETRY(open(abs_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)));
337 if (fd == -1) {
Luis Hector Chavezd0512712018-03-14 12:15:56 -0700338 MYLOGW("Unable to open dump file %s: %s\n", abs_path.c_str(), strerror(errno));
Narayan Kamathbd863722017-06-01 18:50:12 +0100339 break;
340 }
341
342 struct stat st = {};
343 if (fstat(fd, &st) == -1) {
Luis Hector Chavezd0512712018-03-14 12:15:56 -0700344 MYLOGW("Unable to stat dump file %s: %s\n", abs_path.c_str(), strerror(errno));
Narayan Kamath8f788292017-05-25 13:20:39 +0100345 continue;
346 }
347
Narayan Kamath3f31b632018-02-22 19:42:36 +0000348 if (limit_by_mtime && st.st_mtime < thirty_minutes_ago) {
Narayan Kamathbd863722017-06-01 18:50:12 +0100349 MYLOGI("Excluding stale dump file: %s\n", abs_path.c_str());
Narayan Kamath8f788292017-05-25 13:20:39 +0100350 continue;
351 }
352
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -0700353 dump_data.emplace_back(DumpData{abs_path, std::move(fd), st.st_mtime});
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700354 }
Narayan Kamath8f788292017-05-25 13:20:39 +0100355
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -0700356 return dump_data;
Narayan Kamath8f788292017-05-25 13:20:39 +0100357}
358
Narayan Kamathbd863722017-06-01 18:50:12 +0100359static bool AddDumps(const std::vector<DumpData>::const_iterator start,
360 const std::vector<DumpData>::const_iterator end,
361 const char* type_name, const bool add_to_zip) {
Narayan Kamath8f788292017-05-25 13:20:39 +0100362 bool dumped = false;
Narayan Kamathbd863722017-06-01 18:50:12 +0100363 for (auto it = start; it != end; ++it) {
364 const std::string& name = it->name;
365 const int fd = it->fd;
Narayan Kamath8f788292017-05-25 13:20:39 +0100366 dumped = true;
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100367
368 // Seek to the beginning of the file before dumping any data. A given
369 // DumpData entry might be dumped multiple times in the report.
370 //
371 // For example, the most recent ANR entry is dumped to the body of the
372 // main entry and it also shows up as a separate entry in the bugreport
373 // ZIP file.
374 if (lseek(fd, 0, SEEK_SET) != static_cast<off_t>(0)) {
375 MYLOGE("Unable to add %s to zip file, lseek failed: %s\n", name.c_str(),
376 strerror(errno));
377 }
378
Narayan Kamath8f788292017-05-25 13:20:39 +0100379 if (ds.IsZipping() && add_to_zip) {
Vishnu Naire97d6122018-01-18 13:58:56 -0800380 if (ds.AddZipEntryFromFd(ZIP_ROOT_DIR + name, fd, /* timeout = */ 0ms) != OK) {
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100381 MYLOGE("Unable to add %s to zip file, addZipEntryFromFd failed\n", name.c_str());
Narayan Kamath8f788292017-05-25 13:20:39 +0100382 }
383 } else {
384 dump_file_from_fd(type_name, name.c_str(), fd);
385 }
Narayan Kamath8f788292017-05-25 13:20:39 +0100386 }
387
388 return dumped;
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700389}
390
Felipe Leme635ca312016-01-05 14:23:02 -0800391// for_each_pid() callback to get mount info about a process.
Felipe Leme4c2d6632016-09-28 14:32:00 -0700392void do_mountinfo(int pid, const char* name __attribute__((unused))) {
Felipe Leme635ca312016-01-05 14:23:02 -0800393 char path[PATH_MAX];
394
395 // Gets the the content of the /proc/PID/ns/mnt link, so only unique mount points
396 // are added.
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700397 snprintf(path, sizeof(path), "/proc/%d/ns/mnt", pid);
Felipe Leme635ca312016-01-05 14:23:02 -0800398 char linkname[PATH_MAX];
399 ssize_t r = readlink(path, linkname, PATH_MAX);
400 if (r == -1) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800401 MYLOGE("Unable to read link for %s: %s\n", path, strerror(errno));
Felipe Leme635ca312016-01-05 14:23:02 -0800402 return;
403 }
404 linkname[r] = '\0';
405
406 if (mount_points.find(linkname) == mount_points.end()) {
407 // First time this mount point was found: add it
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700408 snprintf(path, sizeof(path), "/proc/%d/mountinfo", pid);
Felipe Leme1d486fe2016-10-14 18:06:47 -0700409 if (ds.AddZipEntry(ZIP_ROOT_DIR + path, path)) {
Felipe Leme635ca312016-01-05 14:23:02 -0800410 mount_points.insert(linkname);
411 } else {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800412 MYLOGE("Unable to add mountinfo %s to zip file\n", path);
Felipe Leme635ca312016-01-05 14:23:02 -0800413 }
414 }
415}
416
417void add_mountinfo() {
Felipe Leme1d486fe2016-10-14 18:06:47 -0700418 if (!ds.IsZipping()) return;
Felipe Leme678727a2016-09-21 17:22:11 -0700419 std::string title = "MOUNT INFO";
Felipe Leme635ca312016-01-05 14:23:02 -0800420 mount_points.clear();
Felipe Leme46b85da2016-11-21 17:40:45 -0800421 DurationReporter duration_reporter(title, true);
Felipe Leme678727a2016-09-21 17:22:11 -0700422 for_each_pid(do_mountinfo, nullptr);
423 MYLOGD("%s: %d entries added to zip file\n", title.c_str(), (int)mount_points.size());
Felipe Leme635ca312016-01-05 14:23:02 -0800424}
425
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -0700426static void dump_dev_files(const char *title, const char *driverpath, const char *filename)
427{
428 DIR *d;
429 struct dirent *de;
430 char path[PATH_MAX];
431
432 d = opendir(driverpath);
Yi Kong19d5c002018-07-20 13:39:55 -0700433 if (d == nullptr) {
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -0700434 return;
435 }
436
437 while ((de = readdir(d))) {
438 if (de->d_type != DT_LNK) {
439 continue;
440 }
441 snprintf(path, sizeof(path), "%s/%s/%s", driverpath, de->d_name, filename);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700442 DumpFile(title, path);
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -0700443 }
444
445 closedir(d);
446}
447
Mark Salyzyn326842f2015-04-30 09:49:41 -0700448static bool skip_not_stat(const char *path) {
449 static const char stat[] = "/stat";
450 size_t len = strlen(path);
451 if (path[len - 1] == '/') { /* Directory? */
452 return false;
453 }
454 return strcmp(path + len - sizeof(stat) + 1, stat); /* .../stat? */
455}
456
Felipe Leme4c2d6632016-09-28 14:32:00 -0700457static bool skip_none(const char* path __attribute__((unused))) {
Felipe Lemee82a27d2016-01-05 13:35:44 -0800458 return false;
459}
460
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700461unsigned long worst_write_perf = 20000; /* in KB/s */
Mark Salyzyn326842f2015-04-30 09:49:41 -0700462
Mark Salyzyn01d6c392016-02-04 09:20:44 -0800463//
464// stat offsets
465// Name units description
466// ---- ----- -----------
467// read I/Os requests number of read I/Os processed
468#define __STAT_READ_IOS 0
469// read merges requests number of read I/Os merged with in-queue I/O
470#define __STAT_READ_MERGES 1
471// read sectors sectors number of sectors read
472#define __STAT_READ_SECTORS 2
473// read ticks milliseconds total wait time for read requests
474#define __STAT_READ_TICKS 3
475// write I/Os requests number of write I/Os processed
476#define __STAT_WRITE_IOS 4
477// write merges requests number of write I/Os merged with in-queue I/O
478#define __STAT_WRITE_MERGES 5
479// write sectors sectors number of sectors written
480#define __STAT_WRITE_SECTORS 6
481// write ticks milliseconds total wait time for write requests
482#define __STAT_WRITE_TICKS 7
483// in_flight requests number of I/Os currently in flight
484#define __STAT_IN_FLIGHT 8
485// io_ticks milliseconds total time this block device has been active
486#define __STAT_IO_TICKS 9
487// time_in_queue milliseconds total wait time for all requests
488#define __STAT_IN_QUEUE 10
489#define __STAT_NUMBER_FIELD 11
490//
491// read I/Os, write I/Os
492// =====================
493//
494// These values increment when an I/O request completes.
495//
496// read merges, write merges
497// =========================
498//
499// These values increment when an I/O request is merged with an
500// already-queued I/O request.
501//
502// read sectors, write sectors
503// ===========================
504//
505// These values count the number of sectors read from or written to this
506// block device. The "sectors" in question are the standard UNIX 512-byte
507// sectors, not any device- or filesystem-specific block size. The
508// counters are incremented when the I/O completes.
509#define SECTOR_SIZE 512
510//
511// read ticks, write ticks
512// =======================
513//
514// These values count the number of milliseconds that I/O requests have
515// waited on this block device. If there are multiple I/O requests waiting,
516// these values will increase at a rate greater than 1000/second; for
517// example, if 60 read requests wait for an average of 30 ms, the read_ticks
518// field will increase by 60*30 = 1800.
519//
520// in_flight
521// =========
522//
523// This value counts the number of I/O requests that have been issued to
524// the device driver but have not yet completed. It does not include I/O
525// requests that are in the queue but not yet issued to the device driver.
526//
527// io_ticks
528// ========
529//
530// This value counts the number of milliseconds during which the device has
531// had I/O requests queued.
532//
533// time_in_queue
534// =============
535//
536// This value counts the number of milliseconds that I/O requests have waited
537// on this block device. If there are multiple I/O requests waiting, this
538// value will increase as the product of the number of milliseconds times the
539// number of requests waiting (see "read ticks" above for an example).
540#define S_TO_MS 1000
541//
542
Mark Salyzyn326842f2015-04-30 09:49:41 -0700543static int dump_stat_from_fd(const char *title __unused, const char *path, int fd) {
Mark Salyzyn01d6c392016-02-04 09:20:44 -0800544 unsigned long long fields[__STAT_NUMBER_FIELD];
Mark Salyzyn326842f2015-04-30 09:49:41 -0700545 bool z;
Yi Kong19d5c002018-07-20 13:39:55 -0700546 char *cp, *buffer = nullptr;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700547 size_t i = 0;
Josh Gao7c4258c2018-06-25 13:40:08 -0700548 FILE *fp = fdopen(dup(fd), "rb");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700549 getline(&buffer, &i, fp);
550 fclose(fp);
551 if (!buffer) {
552 return -errno;
553 }
554 i = strlen(buffer);
555 while ((i > 0) && (buffer[i - 1] == '\n')) {
556 buffer[--i] = '\0';
557 }
558 if (!*buffer) {
559 free(buffer);
560 return 0;
561 }
562 z = true;
563 for (cp = buffer, i = 0; i < (sizeof(fields) / sizeof(fields[0])); ++i) {
Mark Salyzyn01d6c392016-02-04 09:20:44 -0800564 fields[i] = strtoull(cp, &cp, 10);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700565 if (fields[i] != 0) {
566 z = false;
567 }
568 }
569 if (z) { /* never accessed */
570 free(buffer);
571 return 0;
572 }
573
Wei Wang509bb5d2017-06-09 14:42:12 -0700574 if (!strncmp(path, BLK_DEV_SYS_DIR, sizeof(BLK_DEV_SYS_DIR) - 1)) {
575 path += sizeof(BLK_DEV_SYS_DIR) - 1;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700576 }
Wei Wang1dc1ef52017-06-12 11:28:37 -0700577
578 printf("%-30s:%9s%9s%9s%9s%9s%9s%9s%9s%9s%9s%9s\n%-30s:\t%s\n", "Block-Dev",
579 "R-IOs", "R-merg", "R-sect", "R-wait", "W-IOs", "W-merg", "W-sect",
580 "W-wait", "in-fli", "activ", "T-wait", path, buffer);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700581 free(buffer);
582
Mark Salyzyn01d6c392016-02-04 09:20:44 -0800583 if (fields[__STAT_IO_TICKS]) {
584 unsigned long read_perf = 0;
585 unsigned long read_ios = 0;
586 if (fields[__STAT_READ_TICKS]) {
587 unsigned long long divisor = fields[__STAT_READ_TICKS]
588 * fields[__STAT_IO_TICKS];
589 read_perf = ((unsigned long long)SECTOR_SIZE
590 * fields[__STAT_READ_SECTORS]
591 * fields[__STAT_IN_QUEUE] + (divisor >> 1))
592 / divisor;
593 read_ios = ((unsigned long long)S_TO_MS * fields[__STAT_READ_IOS]
594 * fields[__STAT_IN_QUEUE] + (divisor >> 1))
595 / divisor;
596 }
597
598 unsigned long write_perf = 0;
599 unsigned long write_ios = 0;
600 if (fields[__STAT_WRITE_TICKS]) {
601 unsigned long long divisor = fields[__STAT_WRITE_TICKS]
602 * fields[__STAT_IO_TICKS];
603 write_perf = ((unsigned long long)SECTOR_SIZE
604 * fields[__STAT_WRITE_SECTORS]
605 * fields[__STAT_IN_QUEUE] + (divisor >> 1))
606 / divisor;
607 write_ios = ((unsigned long long)S_TO_MS * fields[__STAT_WRITE_IOS]
608 * fields[__STAT_IN_QUEUE] + (divisor >> 1))
609 / divisor;
610 }
611
612 unsigned queue = (fields[__STAT_IN_QUEUE]
613 + (fields[__STAT_IO_TICKS] >> 1))
614 / fields[__STAT_IO_TICKS];
615
616 if (!write_perf && !write_ios) {
Wei Wang1dc1ef52017-06-12 11:28:37 -0700617 printf("%-30s: perf(ios) rd: %luKB/s(%lu/s) q: %u\n", path, read_perf, read_ios, queue);
Mark Salyzyn01d6c392016-02-04 09:20:44 -0800618 } else {
Wei Wang1dc1ef52017-06-12 11:28:37 -0700619 printf("%-30s: perf(ios) rd: %luKB/s(%lu/s) wr: %luKB/s(%lu/s) q: %u\n", path, read_perf,
Felipe Lemed8b94e52016-12-08 10:21:44 -0800620 read_ios, write_perf, write_ios, queue);
Mark Salyzyn01d6c392016-02-04 09:20:44 -0800621 }
622
623 /* bugreport timeout factor adjustment */
624 if ((write_perf > 1) && (write_perf < worst_write_perf)) {
625 worst_write_perf = write_perf;
626 }
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700627 }
Mark Salyzyn326842f2015-04-30 09:49:41 -0700628 return 0;
629}
630
Yao Chenbe3bbc12018-01-17 16:31:10 -0800631static const long MINIMUM_LOGCAT_TIMEOUT_MS = 50000;
632
633/* timeout in ms to read a list of buffers */
634static unsigned long logcat_timeout(const std::vector<std::string>& buffers) {
635 unsigned long timeout_ms = 0;
636 for (const auto& buffer : buffers) {
637 log_id_t id = android_name_to_log_id(buffer.c_str());
638 unsigned long property_size = __android_logger_get_buffer_size(id);
639 /* Engineering margin is ten-fold our guess */
640 timeout_ms += 10 * (property_size + worst_write_perf) / worst_write_perf;
641 }
642 return timeout_ms > MINIMUM_LOGCAT_TIMEOUT_MS ? timeout_ms : MINIMUM_LOGCAT_TIMEOUT_MS;
Mark Salyzyn8f37aa52015-06-12 12:28:24 -0700643}
644
Nandana Duttd2f5f082019-01-18 17:13:52 +0000645Dumpstate::ConsentCallback::ConsentCallback() : result_(UNAVAILABLE), start_time_(Nanotime()) {
646}
647
648android::binder::Status Dumpstate::ConsentCallback::onReportApproved() {
649 std::lock_guard<std::mutex> lock(lock_);
650 result_ = APPROVED;
651 MYLOGD("User approved consent to share bugreport\n");
Paul Chang0d2aad72020-02-13 20:04:03 +0800652
653 // Maybe copy screenshot so calling app can display the screenshot to the user as soon as
654 // consent is granted.
655 if (ds.options_->is_screenshot_copied) {
656 return android::binder::Status::ok();
657 }
658
659 if (!ds.options_->do_screenshot || ds.options_->screenshot_fd.get() == -1 ||
660 !ds.do_early_screenshot_) {
661 return android::binder::Status::ok();
662 }
663
664 bool copy_succeeded = android::os::CopyFileToFd(ds.screenshot_path_,
665 ds.options_->screenshot_fd.get());
666 ds.options_->is_screenshot_copied = copy_succeeded;
667 if (copy_succeeded) {
668 android::os::UnlinkAndLogOnError(ds.screenshot_path_);
669 }
Nandana Duttd2f5f082019-01-18 17:13:52 +0000670 return android::binder::Status::ok();
671}
672
673android::binder::Status Dumpstate::ConsentCallback::onReportDenied() {
674 std::lock_guard<std::mutex> lock(lock_);
675 result_ = DENIED;
676 MYLOGW("User denied consent to share bugreport\n");
677 return android::binder::Status::ok();
678}
679
680UserConsentResult Dumpstate::ConsentCallback::getResult() {
681 std::lock_guard<std::mutex> lock(lock_);
682 return result_;
683}
684
685uint64_t Dumpstate::ConsentCallback::getElapsedTimeMs() const {
Hunter Knepshieldf0a39052020-01-03 14:53:04 -0800686 return (Nanotime() - start_time_) / NANOS_PER_MILLI;
Nandana Duttd2f5f082019-01-18 17:13:52 +0000687}
688
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700689void Dumpstate::PrintHeader() const {
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700690 std::string build, fingerprint, radio, bootloader, network;
691 char date[80];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700692
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700693 build = android::base::GetProperty("ro.build.display.id", "(unknown)");
694 fingerprint = android::base::GetProperty("ro.build.fingerprint", "(unknown)");
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700695 radio = android::base::GetProperty("gsm.version.baseband", "(unknown)");
696 bootloader = android::base::GetProperty("ro.bootloader", "(unknown)");
697 network = android::base::GetProperty("gsm.operator.alpha", "(unknown)");
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700698 strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now_));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700699
Felipe Lemed8b94e52016-12-08 10:21:44 -0800700 printf("========================================================\n");
701 printf("== dumpstate: %s\n", date);
702 printf("========================================================\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700703
Felipe Lemed8b94e52016-12-08 10:21:44 -0800704 printf("\n");
705 printf("Build: %s\n", build.c_str());
Felipe Leme96c2bbb2016-09-26 09:21:21 -0700706 // NOTE: fingerprint entry format is important for other tools.
Felipe Lemed8b94e52016-12-08 10:21:44 -0800707 printf("Build fingerprint: '%s'\n", fingerprint.c_str());
708 printf("Bootloader: %s\n", bootloader.c_str());
709 printf("Radio: %s\n", radio.c_str());
710 printf("Network: %s\n", network.c_str());
Nikita Ioffea325a572019-05-16 19:49:47 +0100711 int64_t module_metadata_version = android::os::GetModuleMetadataVersion();
712 if (module_metadata_version != 0) {
713 printf("Module Metadata version: %" PRId64 "\n", module_metadata_version);
714 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700715
Felipe Lemed8b94e52016-12-08 10:21:44 -0800716 printf("Kernel: ");
Felipe Lemef0292972016-11-22 13:57:05 -0800717 DumpFileToFd(STDOUT_FILENO, "", "/proc/version");
Felipe Lemed8b94e52016-12-08 10:21:44 -0800718 printf("Command line: %s\n", strtok(cmdline_buf, "\n"));
Felipe Leme7709f8a2017-12-05 09:30:09 -0800719 printf("Uptime: ");
720 RunCommandToFd(STDOUT_FILENO, "", {"uptime", "-p"},
721 CommandOptions::WithTimeout(1).Always().Build());
Felipe Lemed8b94e52016-12-08 10:21:44 -0800722 printf("Bugreport format version: %s\n", version_.c_str());
Abhijeet Kaure370d682019-10-01 16:49:30 +0100723 printf("Dumpstate info: id=%d pid=%d dry_run=%d args=%s bugreport_mode=%s\n", id_, pid_,
724 PropertiesHelper::IsDryRun(), options_->args.c_str(), options_->bugreport_mode.c_str());
Felipe Lemed8b94e52016-12-08 10:21:44 -0800725 printf("\n");
Felipe Leme78f2c862015-12-21 09:55:22 -0800726}
727
Felipe Leme24b66ee2016-06-16 10:55:26 -0700728// List of file extensions that can cause a zip file attachment to be rejected by some email
729// service providers.
730static const std::set<std::string> PROBLEMATIC_FILE_EXTENSIONS = {
731 ".ade", ".adp", ".bat", ".chm", ".cmd", ".com", ".cpl", ".exe", ".hta", ".ins", ".isp",
732 ".jar", ".jse", ".lib", ".lnk", ".mde", ".msc", ".msp", ".mst", ".pif", ".scr", ".sct",
733 ".shb", ".sys", ".vb", ".vbe", ".vbs", ".vxd", ".wsc", ".wsf", ".wsh"
734};
735
Vishnu Naire97d6122018-01-18 13:58:56 -0800736status_t Dumpstate::AddZipEntryFromFd(const std::string& entry_name, int fd,
737 std::chrono::milliseconds timeout = 0ms) {
Felipe Leme1d486fe2016-10-14 18:06:47 -0700738 if (!IsZipping()) {
739 MYLOGD("Not adding zip entry %s from fd because it's not a zipped bugreport\n",
740 entry_name.c_str());
Vishnu Naire97d6122018-01-18 13:58:56 -0800741 return INVALID_OPERATION;
Felipe Leme111b9d02016-02-03 09:28:24 -0800742 }
Felipe Leme24b66ee2016-06-16 10:55:26 -0700743 std::string valid_name = entry_name;
744
745 // Rename extension if necessary.
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -0700746 size_t idx = entry_name.rfind('.');
Felipe Leme24b66ee2016-06-16 10:55:26 -0700747 if (idx != std::string::npos) {
748 std::string extension = entry_name.substr(idx);
749 std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
750 if (PROBLEMATIC_FILE_EXTENSIONS.count(extension) != 0) {
751 valid_name = entry_name + ".renamed";
752 MYLOGI("Renaming entry %s to %s\n", entry_name.c_str(), valid_name.c_str());
753 }
754 }
755
Felipe Leme6fe9db62016-02-12 09:04:16 -0800756 // Logging statement below is useful to time how long each entry takes, but it's too verbose.
757 // MYLOGD("Adding zip entry %s\n", entry_name.c_str());
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700758 int32_t err = zip_writer_->StartEntryWithTime(valid_name.c_str(), ZipWriter::kCompress,
759 get_mtime(fd, ds.now_));
Felipe Leme1d486fe2016-10-14 18:06:47 -0700760 if (err != 0) {
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700761 MYLOGE("zip_writer_->StartEntryWithTime(%s): %s\n", valid_name.c_str(),
Felipe Leme1d486fe2016-10-14 18:06:47 -0700762 ZipWriter::ErrorCodeString(err));
Vishnu Naire97d6122018-01-18 13:58:56 -0800763 return UNKNOWN_ERROR;
Felipe Lemee82a27d2016-01-05 13:35:44 -0800764 }
Narayan Kamath895f8fc2019-02-08 18:18:08 +0000765 bool finished_entry = false;
766 auto finish_entry = [this, &finished_entry] {
767 if (!finished_entry) {
768 // This should only be called when we're going to return an earlier error,
769 // which would've been logged. This may imply the file is already corrupt
770 // and any further logging from FinishEntry is more likely to mislead than
771 // not.
772 this->zip_writer_->FinishEntry();
773 }
774 };
775 auto scope_guard = android::base::make_scope_guard(finish_entry);
Vishnu Naire97d6122018-01-18 13:58:56 -0800776 auto start = std::chrono::steady_clock::now();
777 auto end = start + timeout;
778 struct pollfd pfd = {fd, POLLIN};
Felipe Lemee82a27d2016-01-05 13:35:44 -0800779
Felipe Leme770410d2016-01-26 17:07:14 -0800780 std::vector<uint8_t> buffer(65536);
Felipe Lemee82a27d2016-01-05 13:35:44 -0800781 while (1) {
Vishnu Naire97d6122018-01-18 13:58:56 -0800782 if (timeout.count() > 0) {
783 // lambda to recalculate the timeout.
784 auto time_left_ms = [end]() {
785 auto now = std::chrono::steady_clock::now();
786 auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - now);
787 return std::max(diff.count(), 0LL);
788 };
789
790 int rc = TEMP_FAILURE_RETRY(poll(&pfd, 1, time_left_ms()));
791 if (rc < 0) {
Narayan Kamath895f8fc2019-02-08 18:18:08 +0000792 MYLOGE("Error in poll while adding from fd to zip entry %s:%s\n",
793 entry_name.c_str(), strerror(errno));
Vishnu Naire97d6122018-01-18 13:58:56 -0800794 return -errno;
795 } else if (rc == 0) {
Narayan Kamath895f8fc2019-02-08 18:18:08 +0000796 MYLOGE("Timed out adding from fd to zip entry %s:%s Timeout:%lldms\n",
Vishnu Naire97d6122018-01-18 13:58:56 -0800797 entry_name.c_str(), strerror(errno), timeout.count());
798 return TIMED_OUT;
799 }
800 }
801
Zach Riggle22200402016-08-18 01:01:24 -0400802 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
Felipe Lemee82a27d2016-01-05 13:35:44 -0800803 if (bytes_read == 0) {
804 break;
805 } else if (bytes_read == -1) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800806 MYLOGE("read(%s): %s\n", entry_name.c_str(), strerror(errno));
Vishnu Naire97d6122018-01-18 13:58:56 -0800807 return -errno;
Felipe Lemee82a27d2016-01-05 13:35:44 -0800808 }
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700809 err = zip_writer_->WriteBytes(buffer.data(), bytes_read);
Felipe Lemee82a27d2016-01-05 13:35:44 -0800810 if (err) {
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700811 MYLOGE("zip_writer_->WriteBytes(): %s\n", ZipWriter::ErrorCodeString(err));
Vishnu Naire97d6122018-01-18 13:58:56 -0800812 return UNKNOWN_ERROR;
Felipe Lemee82a27d2016-01-05 13:35:44 -0800813 }
814 }
815
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700816 err = zip_writer_->FinishEntry();
Narayan Kamath895f8fc2019-02-08 18:18:08 +0000817 finished_entry = true;
Felipe Leme1d486fe2016-10-14 18:06:47 -0700818 if (err != 0) {
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700819 MYLOGE("zip_writer_->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err));
Vishnu Naire97d6122018-01-18 13:58:56 -0800820 return UNKNOWN_ERROR;
Felipe Lemee82a27d2016-01-05 13:35:44 -0800821 }
822
Vishnu Naire97d6122018-01-18 13:58:56 -0800823 return OK;
Felipe Lemee82a27d2016-01-05 13:35:44 -0800824}
825
Felipe Leme1d486fe2016-10-14 18:06:47 -0700826bool Dumpstate::AddZipEntry(const std::string& entry_name, const std::string& entry_path) {
827 android::base::unique_fd fd(
828 TEMP_FAILURE_RETRY(open(entry_path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
Andreas Gampeaff68432016-07-18 18:01:27 -0700829 if (fd == -1) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800830 MYLOGE("open(%s): %s\n", entry_path.c_str(), strerror(errno));
Felipe Lemee82a27d2016-01-05 13:35:44 -0800831 return false;
832 }
833
Vishnu Naire97d6122018-01-18 13:58:56 -0800834 return (AddZipEntryFromFd(entry_name, fd.get()) == OK);
Felipe Lemee82a27d2016-01-05 13:35:44 -0800835}
836
837/* adds a file to the existing zipped bugreport */
Felipe Leme4c2d6632016-09-28 14:32:00 -0700838static int _add_file_from_fd(const char* title __attribute__((unused)), const char* path, int fd) {
Vishnu Naire97d6122018-01-18 13:58:56 -0800839 return (ds.AddZipEntryFromFd(ZIP_ROOT_DIR + path, fd) == OK) ? 0 : 1;
Felipe Lemee82a27d2016-01-05 13:35:44 -0800840}
841
Felipe Leme1d486fe2016-10-14 18:06:47 -0700842void Dumpstate::AddDir(const std::string& dir, bool recursive) {
843 if (!IsZipping()) {
844 MYLOGD("Not adding dir %s because it's not a zipped bugreport\n", dir.c_str());
Felipe Leme111b9d02016-02-03 09:28:24 -0800845 return;
846 }
Felipe Leme678727a2016-09-21 17:22:11 -0700847 MYLOGD("Adding dir %s (recursive: %d)\n", dir.c_str(), recursive);
Felipe Leme46b85da2016-11-21 17:40:45 -0800848 DurationReporter duration_reporter(dir, true);
Felipe Leme678727a2016-09-21 17:22:11 -0700849 dump_files("", dir.c_str(), recursive ? skip_none : is_dir, _add_file_from_fd);
Felipe Lemee82a27d2016-01-05 13:35:44 -0800850}
851
Felipe Leme1d486fe2016-10-14 18:06:47 -0700852bool Dumpstate::AddTextZipEntry(const std::string& entry_name, const std::string& content) {
853 if (!IsZipping()) {
854 MYLOGD("Not adding text zip entry %s because it's not a zipped bugreport\n",
855 entry_name.c_str());
Felipe Leme111b9d02016-02-03 09:28:24 -0800856 return false;
857 }
Felipe Lemecbce55d2016-02-08 09:53:18 -0800858 MYLOGD("Adding zip text entry %s\n", entry_name.c_str());
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700859 int32_t err = zip_writer_->StartEntryWithTime(entry_name.c_str(), ZipWriter::kCompress, ds.now_);
Felipe Leme1d486fe2016-10-14 18:06:47 -0700860 if (err != 0) {
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700861 MYLOGE("zip_writer_->StartEntryWithTime(%s): %s\n", entry_name.c_str(),
Felipe Leme1d486fe2016-10-14 18:06:47 -0700862 ZipWriter::ErrorCodeString(err));
Felipe Leme809d74e2016-02-02 12:57:00 -0800863 return false;
864 }
865
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700866 err = zip_writer_->WriteBytes(content.c_str(), content.length());
Felipe Leme1d486fe2016-10-14 18:06:47 -0700867 if (err != 0) {
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700868 MYLOGE("zip_writer_->WriteBytes(%s): %s\n", entry_name.c_str(),
Felipe Leme1d486fe2016-10-14 18:06:47 -0700869 ZipWriter::ErrorCodeString(err));
Felipe Leme809d74e2016-02-02 12:57:00 -0800870 return false;
871 }
872
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700873 err = zip_writer_->FinishEntry();
Felipe Leme1d486fe2016-10-14 18:06:47 -0700874 if (err != 0) {
Felipe Lemec6bc8bc2016-10-27 15:58:27 -0700875 MYLOGE("zip_writer_->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err));
Felipe Leme809d74e2016-02-02 12:57:00 -0800876 return false;
877 }
878
879 return true;
880}
881
Felipe Leme6ec6ac42017-01-10 15:29:53 -0800882static void DoKmsg() {
883 struct stat st;
884 if (!stat(PSTORE_LAST_KMSG, &st)) {
885 /* Also TODO: Make console-ramoops CAP_SYSLOG protected. */
886 DumpFile("LAST KMSG", PSTORE_LAST_KMSG);
887 } else if (!stat(ALT_PSTORE_LAST_KMSG, &st)) {
888 DumpFile("LAST KMSG", ALT_PSTORE_LAST_KMSG);
889 } else {
890 /* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */
891 DumpFile("LAST KMSG", "/proc/last_kmsg");
892 }
893}
894
Siarhei Vishniakou4a0a8772017-12-05 16:22:49 -0800895static void DoKernelLogcat() {
Yao Chenbe3bbc12018-01-17 16:31:10 -0800896 unsigned long timeout_ms = logcat_timeout({"kernel"});
Siarhei Vishniakou4a0a8772017-12-05 16:22:49 -0800897 RunCommand(
898 "KERNEL LOG",
899 {"logcat", "-b", "kernel", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
900 CommandOptions::WithTimeoutInMs(timeout_ms).Build());
901}
902
Nandana Duttdb379fa2019-10-09 16:54:41 +0100903static void DoSystemLogcat(time_t since) {
904 char since_str[80];
905 strftime(since_str, sizeof(since_str), "%Y-%m-%d %H:%M:%S.000", localtime(&since));
906
907 unsigned long timeout_ms = logcat_timeout({"main", "system", "crash"});
908 RunCommand("SYSTEM LOG",
909 {"logcat", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v", "-T",
910 since_str},
911 CommandOptions::WithTimeoutInMs(timeout_ms).Build());
912}
913
Hunter Knepshield820f9bc2020-02-05 20:10:53 -0800914static void DoRadioLogcat() {
915 unsigned long timeout_ms = logcat_timeout({"radio"});
916 RunCommand(
917 "RADIO LOG",
918 {"logcat", "-b", "radio", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
919 CommandOptions::WithTimeoutInMs(timeout_ms).Build(), true /* verbose_duration */);
920}
921
Felipe Leme6ec6ac42017-01-10 15:29:53 -0800922static void DoLogcat() {
Vishnu Nair6921f802017-11-22 09:17:23 -0800923 unsigned long timeout_ms;
Felipe Leme6ec6ac42017-01-10 15:29:53 -0800924 // DumpFile("EVENT LOG TAGS", "/etc/event-log-tags");
925 // calculate timeout
Yao Chenbe3bbc12018-01-17 16:31:10 -0800926 timeout_ms = logcat_timeout({"main", "system", "crash"});
Tony Makae737652017-03-30 17:47:09 +0100927 RunCommand("SYSTEM LOG",
Vishnu Nair6921f802017-11-22 09:17:23 -0800928 {"logcat", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
929 CommandOptions::WithTimeoutInMs(timeout_ms).Build());
Yao Chenbe3bbc12018-01-17 16:31:10 -0800930 timeout_ms = logcat_timeout({"events"});
Siarhei Vishniakou4a0a8772017-12-05 16:22:49 -0800931 RunCommand(
932 "EVENT LOG",
933 {"logcat", "-b", "events", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
Nandana Dutt8d945c02019-08-14 13:30:07 +0100934 CommandOptions::WithTimeoutInMs(timeout_ms).Build(), true /* verbose_duration */);
Yao Chenbe3bbc12018-01-17 16:31:10 -0800935 timeout_ms = logcat_timeout({"stats"});
936 RunCommand(
937 "STATS LOG",
938 {"logcat", "-b", "stats", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
Nandana Dutt8d945c02019-08-14 13:30:07 +0100939 CommandOptions::WithTimeoutInMs(timeout_ms).Build(), true /* verbose_duration */);
Hunter Knepshield820f9bc2020-02-05 20:10:53 -0800940 DoRadioLogcat();
Felipe Leme6ec6ac42017-01-10 15:29:53 -0800941
942 RunCommand("LOG STATISTICS", {"logcat", "-b", "all", "-S"});
943
944 /* kernels must set CONFIG_PSTORE_PMSG, slice up pstore with device tree */
Siarhei Vishniakou4a0a8772017-12-05 16:22:49 -0800945 RunCommand("LAST LOGCAT", {"logcat", "-L", "-b", "all", "-v", "threadtime", "-v", "printable",
946 "-v", "uid", "-d", "*:v"});
Felipe Leme6ec6ac42017-01-10 15:29:53 -0800947}
948
Mike Ma5c267872019-08-21 11:31:34 -0700949static void DumpIncidentReport() {
950 if (!ds.IsZipping()) {
951 MYLOGD("Not dumping incident report because it's not a zipped bugreport\n");
952 return;
953 }
954 DurationReporter duration_reporter("INCIDENT REPORT");
955 const std::string path = ds.bugreport_internal_dir_ + "/tmp_incident_report";
956 auto fd = android::base::unique_fd(TEMP_FAILURE_RETRY(open(path.c_str(),
957 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
958 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
959 if (fd < 0) {
960 MYLOGE("Could not open %s to dump incident report.\n", path.c_str());
961 return;
962 }
963 RunCommandToFd(fd, "", {"incident", "-u"}, CommandOptions::WithTimeout(120).Build());
964 bool empty = 0 == lseek(fd, 0, SEEK_END);
965 if (!empty) {
966 // Use a different name from "incident.proto"
967 // /proto/incident.proto is reserved for incident service dump
968 // i.e. metadata for debugging.
969 ds.AddZipEntry(kProtoPath + "incident_report" + kProtoExt, path);
970 }
971 unlink(path.c_str());
972}
973
Sunny Goyal35949782019-11-19 15:54:36 -0800974static void DumpVisibleWindowViews() {
975 if (!ds.IsZipping()) {
976 MYLOGD("Not dumping visible views because it's not a zipped bugreport\n");
977 return;
978 }
979 DurationReporter duration_reporter("VISIBLE WINDOW VIEWS");
980 const std::string path = ds.bugreport_internal_dir_ + "/tmp_visible_window_views";
981 auto fd = android::base::unique_fd(TEMP_FAILURE_RETRY(open(path.c_str(),
982 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
983 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
984 if (fd < 0) {
985 MYLOGE("Could not open %s to dump visible views.\n", path.c_str());
986 return;
987 }
988 RunCommandToFd(fd, "", {"cmd", "window", "dump-visible-window-views"},
989 CommandOptions::WithTimeout(120).Build());
990 bool empty = 0 == lseek(fd, 0, SEEK_END);
991 if (!empty) {
992 ds.AddZipEntry("visible_windows.zip", path);
993 } else {
994 MYLOGW("Failed to dump visible windows\n");
995 }
996 unlink(path.c_str());
997}
998
Jayachandran Ca94c7172017-06-10 15:08:12 -0700999static void DumpIpTablesAsRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001000 RunCommand("IPTABLES", {"iptables", "-L", "-nvx"});
1001 RunCommand("IP6TABLES", {"ip6tables", "-L", "-nvx"});
Erik Kline32af8c22016-09-28 17:26:26 +09001002 RunCommand("IPTABLES NAT", {"iptables", "-t", "nat", "-L", "-nvx"});
Felipe Lemec0808152016-06-17 17:37:13 -07001003 /* no ip6 nat */
Erik Kline32af8c22016-09-28 17:26:26 +09001004 RunCommand("IPTABLES MANGLE", {"iptables", "-t", "mangle", "-L", "-nvx"});
1005 RunCommand("IP6TABLES MANGLE", {"ip6tables", "-t", "mangle", "-L", "-nvx"});
1006 RunCommand("IPTABLES RAW", {"iptables", "-t", "raw", "-L", "-nvx"});
1007 RunCommand("IP6TABLES RAW", {"ip6tables", "-t", "raw", "-L", "-nvx"});
Felipe Lemec0808152016-06-17 17:37:13 -07001008}
1009
David Andersond9ba4752018-12-11 18:26:59 -08001010static void DumpDynamicPartitionInfo() {
1011 if (!::android::base::GetBoolProperty("ro.boot.dynamic_partitions", false)) {
1012 return;
1013 }
1014
1015 RunCommand("LPDUMP", {"lpdump", "--all"});
David Anderson6650ade2019-10-02 15:18:59 -07001016 RunCommand("DEVICE-MAPPER", {"gsid", "dump-device-mapper"});
David Andersond9ba4752018-12-11 18:26:59 -08001017}
1018
Narayan Kamath8f788292017-05-25 13:20:39 +01001019static void AddAnrTraceDir(const bool add_to_zip, const std::string& anr_traces_dir) {
1020 MYLOGD("AddAnrTraceDir(): dump_traces_file=%s, anr_traces_dir=%s\n", dump_traces_path,
1021 anr_traces_dir.c_str());
1022
1023 // If we're here, dump_traces_path will always be a temporary file
1024 // (created with mkostemp or similar) that contains dumps taken earlier
1025 // on in the process.
1026 if (dump_traces_path != nullptr) {
1027 if (add_to_zip) {
1028 ds.AddZipEntry(ZIP_ROOT_DIR + anr_traces_dir + "/traces-just-now.txt", dump_traces_path);
1029 } else {
1030 MYLOGD("Dumping current ANR traces (%s) to the main bugreport entry\n",
1031 dump_traces_path);
1032 ds.DumpFile("VM TRACES JUST NOW", dump_traces_path);
1033 }
1034
1035 const int ret = unlink(dump_traces_path);
1036 if (ret == -1) {
1037 MYLOGW("Error unlinking temporary trace path %s: %s\n", dump_traces_path,
1038 strerror(errno));
Felipe Lemee184f662016-10-27 10:04:47 -07001039 }
1040 }
1041
Narayan Kamathbd863722017-06-01 18:50:12 +01001042 // Add a specific message for the first ANR Dump.
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -07001043 if (ds.anr_data_.size() > 0) {
1044 AddDumps(ds.anr_data_.begin(), ds.anr_data_.begin() + 1,
Narayan Kamathbd863722017-06-01 18:50:12 +01001045 "VM TRACES AT LAST ANR", add_to_zip);
1046
Narayan Kamath6b9516c2017-10-27 11:15:51 +01001047 // The "last" ANR will always be included as separate entry in the zip file. In addition,
1048 // it will be present in the body of the main entry if |add_to_zip| == false.
1049 //
1050 // Historical ANRs are always included as separate entries in the bugreport zip file.
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -07001051 AddDumps(ds.anr_data_.begin() + ((add_to_zip) ? 1 : 0), ds.anr_data_.end(),
Narayan Kamath6b9516c2017-10-27 11:15:51 +01001052 "HISTORICAL ANR", true /* add_to_zip */);
Narayan Kamathbd863722017-06-01 18:50:12 +01001053 } else {
Narayan Kamath8f788292017-05-25 13:20:39 +01001054 printf("*** NO ANRs to dump in %s\n\n", ANR_DIR.c_str());
1055 }
1056}
1057
1058static void AddAnrTraceFiles() {
1059 const bool add_to_zip = ds.IsZipping() && ds.version_ == VERSION_SPLIT_ANR;
1060
Elliott Hughes69fe5ec2018-03-23 11:04:25 -07001061 std::string anr_traces_dir = "/data/anr";
Narayan Kamath8f788292017-05-25 13:20:39 +01001062
Elliott Hughes69fe5ec2018-03-23 11:04:25 -07001063 AddAnrTraceDir(add_to_zip, anr_traces_dir);
Narayan Kamath8f788292017-05-25 13:20:39 +01001064
Makoto Onuki83ec63f2019-01-31 17:08:59 -08001065 RunCommand("ANR FILES", {"ls", "-lt", ANR_DIR});
1066
Elliott Hughes69fe5ec2018-03-23 11:04:25 -07001067 // Slow traces for slow operations.
Felipe Lemee184f662016-10-27 10:04:47 -07001068 struct stat st;
Elliott Hughes69fe5ec2018-03-23 11:04:25 -07001069 int i = 0;
1070 while (true) {
1071 const std::string slow_trace_path =
1072 anr_traces_dir + android::base::StringPrintf("slow%02d.txt", i);
1073 if (stat(slow_trace_path.c_str(), &st)) {
1074 // No traces file at this index, done with the files.
1075 break;
Felipe Lemee184f662016-10-27 10:04:47 -07001076 }
Elliott Hughes69fe5ec2018-03-23 11:04:25 -07001077 ds.DumpFile("VM TRACES WHEN SLOW", slow_trace_path.c_str());
1078 i++;
Felipe Lemee184f662016-10-27 10:04:47 -07001079 }
1080}
1081
Wei Wang509bb5d2017-06-09 14:42:12 -07001082static void DumpBlockStatFiles() {
1083 DurationReporter duration_reporter("DUMP BLOCK STAT");
Wei Wang509bb5d2017-06-09 14:42:12 -07001084
Wei Wang1dc1ef52017-06-12 11:28:37 -07001085 std::unique_ptr<DIR, std::function<int(DIR*)>> dirptr(opendir(BLK_DEV_SYS_DIR), closedir);
1086
1087 if (dirptr == nullptr) {
Wei Wang509bb5d2017-06-09 14:42:12 -07001088 MYLOGE("Failed to open %s: %s\n", BLK_DEV_SYS_DIR, strerror(errno));
1089 return;
1090 }
1091
1092 printf("------ DUMP BLOCK STAT ------\n\n");
Wei Wang1dc1ef52017-06-12 11:28:37 -07001093 while (struct dirent *d = readdir(dirptr.get())) {
Wei Wang509bb5d2017-06-09 14:42:12 -07001094 if ((d->d_name[0] == '.')
1095 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
1096 || (d->d_name[1] == '\0'))) {
1097 continue;
1098 }
1099 const std::string new_path =
1100 android::base::StringPrintf("%s/%s", BLK_DEV_SYS_DIR, d->d_name);
1101 printf("------ BLOCK STAT (%s) ------\n", new_path.c_str());
1102 dump_files("", new_path.c_str(), skip_not_stat, dump_stat_from_fd);
1103 printf("\n");
1104 }
Wei Wang1dc1ef52017-06-12 11:28:37 -07001105 return;
Wei Wang509bb5d2017-06-09 14:42:12 -07001106}
Jayachandran Ca94c7172017-06-10 15:08:12 -07001107
1108static void DumpPacketStats() {
1109 DumpFile("NETWORK DEV INFO", "/proc/net/dev");
1110 DumpFile("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all");
1111 DumpFile("QTAGUID NETWORK INTERFACES INFO (xt)", "/proc/net/xt_qtaguid/iface_stat_fmt");
1112 DumpFile("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl");
1113 DumpFile("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats");
1114}
1115
1116static void DumpIpAddrAndRules() {
1117 /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */
1118 RunCommand("NETWORK INTERFACES", {"ip", "link"});
1119 RunCommand("IPv4 ADDRESSES", {"ip", "-4", "addr", "show"});
1120 RunCommand("IPv6 ADDRESSES", {"ip", "-6", "addr", "show"});
1121 RunCommand("IP RULES", {"ip", "rule", "show"});
1122 RunCommand("IP RULES v6", {"ip", "-6", "rule", "show"});
1123}
1124
Nandana Dutt5c390032019-03-12 10:52:56 +00001125static Dumpstate::RunStatus RunDumpsysTextByPriority(const std::string& title, int priority,
1126 std::chrono::milliseconds timeout,
1127 std::chrono::milliseconds service_timeout) {
Vishnu Nair64afc022018-02-01 15:29:34 -08001128 auto start = std::chrono::steady_clock::now();
Vishnu Naire97d6122018-01-18 13:58:56 -08001129 sp<android::IServiceManager> sm = defaultServiceManager();
1130 Dumpsys dumpsys(sm.get());
Vishnu Naire97d6122018-01-18 13:58:56 -08001131 Vector<String16> args;
1132 Dumpsys::setServiceArgs(args, /* asProto = */ false, priority);
Vishnu Naire97d6122018-01-18 13:58:56 -08001133 Vector<String16> services = dumpsys.listServices(priority, /* supports_proto = */ false);
1134 for (const String16& service : services) {
Nandana Dutt5c390032019-03-12 10:52:56 +00001135 RETURN_IF_USER_DENIED_CONSENT();
Vishnu Naire97d6122018-01-18 13:58:56 -08001136 std::string path(title);
1137 path.append(" - ").append(String8(service).c_str());
Vishnu Naire97d6122018-01-18 13:58:56 -08001138 size_t bytes_written = 0;
Steven Moreland5a30d342019-10-08 13:53:28 -07001139 status_t status = dumpsys.startDumpThread(Dumpsys::Type::DUMP, service, args);
Vishnu Naire97d6122018-01-18 13:58:56 -08001140 if (status == OK) {
1141 dumpsys.writeDumpHeader(STDOUT_FILENO, service, priority);
1142 std::chrono::duration<double> elapsed_seconds;
1143 status = dumpsys.writeDump(STDOUT_FILENO, service, service_timeout,
1144 /* as_proto = */ false, elapsed_seconds, bytes_written);
Vishnu Naire97d6122018-01-18 13:58:56 -08001145 dumpsys.writeDumpFooter(STDOUT_FILENO, service, elapsed_seconds);
1146 bool dump_complete = (status == OK);
1147 dumpsys.stopDumpThread(dump_complete);
1148 }
Vishnu Naire97d6122018-01-18 13:58:56 -08001149
1150 auto elapsed_duration = std::chrono::duration_cast<std::chrono::milliseconds>(
1151 std::chrono::steady_clock::now() - start);
1152 if (elapsed_duration > timeout) {
1153 MYLOGE("*** command '%s' timed out after %llums\n", title.c_str(),
1154 elapsed_duration.count());
1155 break;
1156 }
1157 }
Nandana Dutt5c390032019-03-12 10:52:56 +00001158 return Dumpstate::RunStatus::OK;
Vishnu Naire97d6122018-01-18 13:58:56 -08001159}
1160
Vishnu Nair64afc022018-02-01 15:29:34 -08001161static void RunDumpsysText(const std::string& title, int priority,
1162 std::chrono::milliseconds timeout,
1163 std::chrono::milliseconds service_timeout) {
1164 DurationReporter duration_reporter(title);
1165 dprintf(STDOUT_FILENO, "------ %s (/system/bin/dumpsys) ------\n", title.c_str());
1166 fsync(STDOUT_FILENO);
1167 RunDumpsysTextByPriority(title, priority, timeout, service_timeout);
1168}
1169
1170/* Dump all services registered with Normal or Default priority. */
Nandana Dutt5c390032019-03-12 10:52:56 +00001171static Dumpstate::RunStatus RunDumpsysTextNormalPriority(const std::string& title,
1172 std::chrono::milliseconds timeout,
1173 std::chrono::milliseconds service_timeout) {
Vishnu Nair64afc022018-02-01 15:29:34 -08001174 DurationReporter duration_reporter(title);
1175 dprintf(STDOUT_FILENO, "------ %s (/system/bin/dumpsys) ------\n", title.c_str());
1176 fsync(STDOUT_FILENO);
1177 RunDumpsysTextByPriority(title, IServiceManager::DUMP_FLAG_PRIORITY_NORMAL, timeout,
1178 service_timeout);
Nandana Dutt5c390032019-03-12 10:52:56 +00001179
1180 RETURN_IF_USER_DENIED_CONSENT();
1181
1182 return RunDumpsysTextByPriority(title, IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT, timeout,
1183 service_timeout);
Vishnu Nair64afc022018-02-01 15:29:34 -08001184}
1185
Nandana Dutt5c390032019-03-12 10:52:56 +00001186static Dumpstate::RunStatus RunDumpsysProto(const std::string& title, int priority,
1187 std::chrono::milliseconds timeout,
1188 std::chrono::milliseconds service_timeout) {
Luis Hector Chavez1e27b082018-03-22 15:36:42 -07001189 if (!ds.IsZipping()) {
1190 MYLOGD("Not dumping %s because it's not a zipped bugreport\n", title.c_str());
Nandana Dutt5c390032019-03-12 10:52:56 +00001191 return Dumpstate::RunStatus::OK;
Luis Hector Chavez1e27b082018-03-22 15:36:42 -07001192 }
Vishnu Naire97d6122018-01-18 13:58:56 -08001193 sp<android::IServiceManager> sm = defaultServiceManager();
1194 Dumpsys dumpsys(sm.get());
1195 Vector<String16> args;
1196 Dumpsys::setServiceArgs(args, /* asProto = */ true, priority);
1197 DurationReporter duration_reporter(title);
1198
1199 auto start = std::chrono::steady_clock::now();
1200 Vector<String16> services = dumpsys.listServices(priority, /* supports_proto = */ true);
1201 for (const String16& service : services) {
Nandana Dutt5c390032019-03-12 10:52:56 +00001202 RETURN_IF_USER_DENIED_CONSENT();
Vishnu Naire97d6122018-01-18 13:58:56 -08001203 std::string path(kProtoPath);
1204 path.append(String8(service).c_str());
1205 if (priority == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL) {
1206 path.append("_CRITICAL");
1207 } else if (priority == IServiceManager::DUMP_FLAG_PRIORITY_HIGH) {
1208 path.append("_HIGH");
1209 }
1210 path.append(kProtoExt);
Steven Moreland5a30d342019-10-08 13:53:28 -07001211 status_t status = dumpsys.startDumpThread(Dumpsys::Type::DUMP, service, args);
Vishnu Naire97d6122018-01-18 13:58:56 -08001212 if (status == OK) {
1213 status = ds.AddZipEntryFromFd(path, dumpsys.getDumpFd(), service_timeout);
1214 bool dumpTerminated = (status == OK);
1215 dumpsys.stopDumpThread(dumpTerminated);
1216 }
1217 ZipWriter::FileEntry file_entry;
1218 ds.zip_writer_->GetLastEntry(&file_entry);
Vishnu Naire97d6122018-01-18 13:58:56 -08001219
1220 auto elapsed_duration = std::chrono::duration_cast<std::chrono::milliseconds>(
1221 std::chrono::steady_clock::now() - start);
1222 if (elapsed_duration > timeout) {
1223 MYLOGE("*** command '%s' timed out after %llums\n", title.c_str(),
1224 elapsed_duration.count());
1225 break;
1226 }
1227 }
Nandana Dutt5c390032019-03-12 10:52:56 +00001228 return Dumpstate::RunStatus::OK;
Vishnu Naire97d6122018-01-18 13:58:56 -08001229}
1230
Nandana Dutta7db6342018-11-21 14:53:34 +00001231// Runs dumpsys on services that must dump first and will take less than 100ms to dump.
Nandana Dutt5c390032019-03-12 10:52:56 +00001232static Dumpstate::RunStatus RunDumpsysCritical() {
Vishnu Nair64afc022018-02-01 15:29:34 -08001233 RunDumpsysText("DUMPSYS CRITICAL", IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL,
1234 /* timeout= */ 5s, /* service_timeout= */ 500ms);
Nandana Dutt5c390032019-03-12 10:52:56 +00001235
1236 RETURN_IF_USER_DENIED_CONSENT();
1237
1238 return RunDumpsysProto("DUMPSYS CRITICAL PROTO", IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL,
1239 /* timeout= */ 5s, /* service_timeout= */ 500ms);
Vishnu Nair780b1282017-10-10 13:57:24 -07001240}
1241
1242// Runs dumpsys on services that must dump first but can take up to 250ms to dump.
Nandana Dutt5c390032019-03-12 10:52:56 +00001243static Dumpstate::RunStatus RunDumpsysHigh() {
Vishnu Nair64afc022018-02-01 15:29:34 -08001244 // TODO meminfo takes ~10s, connectivity takes ~5sec to dump. They are both
1245 // high priority. Reduce timeout once they are able to dump in a shorter time or
1246 // moved to a parallel task.
1247 RunDumpsysText("DUMPSYS HIGH", IServiceManager::DUMP_FLAG_PRIORITY_HIGH,
1248 /* timeout= */ 90s, /* service_timeout= */ 30s);
Nandana Dutt5c390032019-03-12 10:52:56 +00001249
1250 RETURN_IF_USER_DENIED_CONSENT();
1251
1252 return RunDumpsysProto("DUMPSYS HIGH PROTO", IServiceManager::DUMP_FLAG_PRIORITY_HIGH,
1253 /* timeout= */ 5s, /* service_timeout= */ 1s);
Vishnu Nair780b1282017-10-10 13:57:24 -07001254}
1255
1256// Runs dumpsys on services that must dump but can take up to 10s to dump.
Nandana Dutt5c390032019-03-12 10:52:56 +00001257static Dumpstate::RunStatus RunDumpsysNormal() {
Vishnu Nair64afc022018-02-01 15:29:34 -08001258 RunDumpsysTextNormalPriority("DUMPSYS", /* timeout= */ 90s, /* service_timeout= */ 10s);
Nandana Dutt5c390032019-03-12 10:52:56 +00001259
1260 RETURN_IF_USER_DENIED_CONSENT();
1261
1262 return RunDumpsysProto("DUMPSYS PROTO", IServiceManager::DUMP_FLAG_PRIORITY_NORMAL,
1263 /* timeout= */ 90s, /* service_timeout= */ 10s);
Vishnu Nair780b1282017-10-10 13:57:24 -07001264}
1265
Steven Moreland44cd9482018-01-04 16:24:13 -08001266static void DumpHals() {
Nandana Dutt6ad9a602019-03-11 16:33:24 +00001267 if (!ds.IsZipping()) {
1268 RunCommand("HARDWARE HALS", {"lshal", "-lVSietrpc", "--types=b,c,l,z", "--debug"},
1269 CommandOptions::WithTimeout(10).AsRootIfAvailable().Build());
1270 return;
1271 }
1272 DurationReporter duration_reporter("DUMP HALS");
1273 RunCommand("HARDWARE HALS", {"lshal", "-lVSietrpc", "--types=b,c,l,z"},
Greg Kaiser3dfeda32019-05-16 10:32:51 -07001274 CommandOptions::WithTimeout(10).AsRootIfAvailable().Build());
Nandana Dutt6ad9a602019-03-11 16:33:24 +00001275
Steven Moreland44cd9482018-01-04 16:24:13 -08001276 using android::hidl::manager::V1_0::IServiceManager;
1277 using android::hardware::defaultServiceManager;
1278
1279 sp<IServiceManager> sm = defaultServiceManager();
1280 if (sm == nullptr) {
1281 MYLOGE("Could not retrieve hwservicemanager to dump hals.\n");
1282 return;
1283 }
1284
1285 auto ret = sm->list([&](const auto& interfaces) {
1286 for (const std::string& interface : interfaces) {
1287 std::string cleanName = interface;
1288 std::replace_if(cleanName.begin(),
1289 cleanName.end(),
1290 [](char c) {
1291 return !isalnum(c) &&
1292 std::string("@-_:.").find(c) == std::string::npos;
1293 }, '_');
Nandana Dutt979388e2018-11-30 16:48:55 +00001294 const std::string path = ds.bugreport_internal_dir_ + "/lshal_debug_" + cleanName;
Steven Moreland44cd9482018-01-04 16:24:13 -08001295
1296 {
1297 auto fd = android::base::unique_fd(
1298 TEMP_FAILURE_RETRY(open(path.c_str(),
1299 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1300 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1301 if (fd < 0) {
1302 MYLOGE("Could not open %s to dump additional hal information.\n", path.c_str());
1303 continue;
1304 }
1305 RunCommandToFd(fd,
1306 "",
Steven Morelandc81cd3c2018-01-18 14:36:26 -08001307 {"lshal", "debug", "-E", interface},
Steven Moreland44cd9482018-01-04 16:24:13 -08001308 CommandOptions::WithTimeout(2).AsRootIfAvailable().Build());
1309
1310 bool empty = 0 == lseek(fd, 0, SEEK_END);
1311 if (!empty) {
1312 ds.AddZipEntry("lshal-debug/" + cleanName + ".txt", path);
1313 }
1314 }
1315
1316 unlink(path.c_str());
1317 }
1318 });
1319
1320 if (!ret.isOk()) {
1321 MYLOGE("Could not list hals from hwservicemanager.\n");
1322 }
1323}
1324
Hridya Valsarajuac582cd2019-08-05 15:39:54 -07001325static void DumpExternalFragmentationInfo() {
1326 struct stat st;
1327 if (stat("/proc/buddyinfo", &st) != 0) {
1328 MYLOGE("Unable to dump external fragmentation info\n");
1329 return;
1330 }
1331
1332 printf("------ EXTERNAL FRAGMENTATION INFO ------\n");
1333 std::ifstream ifs("/proc/buddyinfo");
1334 auto unusable_index_regex = std::regex{"Node\\s+([0-9]+),\\s+zone\\s+(\\S+)\\s+(.*)"};
1335 for (std::string line; std::getline(ifs, line);) {
1336 std::smatch match_results;
1337 if (std::regex_match(line, match_results, unusable_index_regex)) {
1338 std::stringstream free_pages(std::string{match_results[3]});
1339 std::vector<int> free_pages_per_order(std::istream_iterator<int>{free_pages},
1340 std::istream_iterator<int>());
1341
1342 int total_free_pages = 0;
1343 for (size_t i = 0; i < free_pages_per_order.size(); i++) {
1344 total_free_pages += (free_pages_per_order[i] * std::pow(2, i));
1345 }
1346
1347 printf("Node %s, zone %8s", match_results[1].str().c_str(),
1348 match_results[2].str().c_str());
1349
1350 int usable_free_pages = total_free_pages;
1351 for (size_t i = 0; i < free_pages_per_order.size(); i++) {
1352 auto unusable_index = (total_free_pages - usable_free_pages) /
1353 static_cast<double>(total_free_pages);
1354 printf(" %5.3f", unusable_index);
1355 usable_free_pages -= (free_pages_per_order[i] * std::pow(2, i));
1356 }
1357
1358 printf("\n");
1359 }
1360 }
1361 printf("\n");
1362}
1363
Nandana Dutt5c390032019-03-12 10:52:56 +00001364// Dumps various things. Returns early with status USER_CONSENT_DENIED if user denies consent
1365// via the consent they are shown. Ignores other errors that occur while running various
1366// commands. The consent checking is currently done around long running tasks, which happen to
1367// be distributed fairly evenly throughout the function.
1368static Dumpstate::RunStatus dumpstate() {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001369 DurationReporter duration_reporter("DUMPSTATE");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001370
Nandana Dutt5c390032019-03-12 10:52:56 +00001371 // Dump various things. Note that anything that takes "long" (i.e. several seconds) should
1372 // check intermittently (if it's intrerruptable like a foreach on pids) and/or should be wrapped
1373 // in a consent check (via RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK).
Arve Hjønnevåg2db0f5f2014-10-15 18:08:37 -07001374 dump_dev_files("TRUSTY VERSION", "/sys/bus/platform/drivers/trusty", "trusty_version");
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001375 RunCommand("UPTIME", {"uptime"});
Wei Wang509bb5d2017-06-09 14:42:12 -07001376 DumpBlockStatFiles();
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001377 DumpFile("MEMORY INFO", "/proc/meminfo");
1378 RunCommand("CPU INFO", {"top", "-b", "-n", "1", "-H", "-s", "6", "-o",
Felipe Leme30dbfa12016-09-02 12:43:26 -07001379 "pid,tid,user,pr,ni,%cpu,s,virt,res,pcy,cmd,name"});
Nandana Dutt5c390032019-03-12 10:52:56 +00001380
1381 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(RunCommand, "PROCRANK", {"procrank"}, AS_ROOT_20);
1382
Sunny Goyal35949782019-11-19 15:54:36 -08001383 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(DumpVisibleWindowViews);
1384
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001385 DumpFile("VIRTUAL MEMORY STATS", "/proc/vmstat");
1386 DumpFile("VMALLOC INFO", "/proc/vmallocinfo");
1387 DumpFile("SLAB INFO", "/proc/slabinfo");
1388 DumpFile("ZONEINFO", "/proc/zoneinfo");
1389 DumpFile("PAGETYPEINFO", "/proc/pagetypeinfo");
1390 DumpFile("BUDDYINFO", "/proc/buddyinfo");
Hridya Valsarajuac582cd2019-08-05 15:39:54 -07001391 DumpExternalFragmentationInfo();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001392
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001393 DumpFile("KERNEL WAKE SOURCES", "/d/wakeup_sources");
1394 DumpFile("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001395
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001396 RunCommand("PROCESSES AND THREADS",
Yohei Yukawa591a72d2017-10-05 21:36:35 -07001397 {"ps", "-A", "-T", "-Z", "-O", "pri,nice,rtprio,sched,pcy,time"});
Nandana Dutt5c390032019-03-12 10:52:56 +00001398
1399 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(RunCommand, "LIBRANK", {"librank"},
1400 CommandOptions::AS_ROOT);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001401
Nandana Dutt6ad9a602019-03-11 16:33:24 +00001402 DumpHals();
Steven Moreland81b429e2017-01-31 19:50:46 -08001403
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001404 RunCommand("PRINTENV", {"printenv"});
Elliott Hughes21b7c8d2016-10-28 08:53:02 -07001405 RunCommand("NETSTAT", {"netstat", "-nW"});
Felipe Lemee4eca582016-06-10 17:48:08 -07001406 struct stat s;
1407 if (stat("/proc/modules", &s) != 0) {
1408 MYLOGD("Skipping 'lsmod' because /proc/modules does not exist\n");
1409 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001410 RunCommand("LSMOD", {"lsmod"});
Felipe Lemee4eca582016-06-10 17:48:08 -07001411 }
Michal Karpinski4db754f2015-12-11 18:04:32 +00001412
Siarhei Vishniakou4a0a8772017-12-05 16:22:49 -08001413 if (__android_logger_property_get_bool(
1414 "ro.logd.kernel", BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE)) {
1415 DoKernelLogcat();
1416 } else {
1417 do_dmesg();
1418 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001419
Felipe Lemef0292972016-11-22 13:57:05 -08001420 RunCommand("LIST OF OPEN FILES", {"lsof"}, CommandOptions::AS_ROOT);
Nandana Dutt5c390032019-03-12 10:52:56 +00001421
1422 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(for_each_pid, do_showmap, "SMAPS OF ALL PROCESSES");
1423
Jeff Brown1dc94e32014-09-11 14:15:27 -07001424 for_each_tid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS");
Mark Salyzyna297c322016-02-05 15:33:17 -08001425 for_each_pid(show_showtime, "PROCESS TIMES (pid cmd user system iowait+percentage)");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001426
Ajay Panicker2ff8e872017-04-27 14:04:32 -07001427 /* Dump Bluetooth HCI logs */
1428 ds.AddDir("/data/misc/bluetooth/logs", true);
Ajay Panickerd886ec42016-09-14 12:26:46 -07001429
Paul Chang0d2aad72020-02-13 20:04:03 +08001430 if (ds.options_->do_screenshot && !ds.do_early_screenshot_) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001431 MYLOGI("taking late screenshot\n");
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001432 ds.TakeScreenshot();
Jeff Sharkey5a930032013-03-19 15:05:19 -07001433 }
1434
Felipe Lemee184f662016-10-27 10:04:47 -07001435 AddAnrTraceFiles();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001436
Narayan Kamath8f788292017-05-25 13:20:39 +01001437 // NOTE: tombstones are always added as separate entries in the zip archive
1438 // and are not interspersed with the main report.
Luis Hector Chavez5f6ee4a2018-03-14 15:12:46 -07001439 const bool tombstones_dumped = AddDumps(ds.tombstone_data_.begin(), ds.tombstone_data_.end(),
Narayan Kamathbd863722017-06-01 18:50:12 +01001440 "TOMBSTONE", true /* add_to_zip */);
Narayan Kamath8f788292017-05-25 13:20:39 +01001441 if (!tombstones_dumped) {
1442 printf("*** NO TOMBSTONES to dump in %s\n\n", TOMBSTONE_DIR.c_str());
Christopher Ferris7dc7f322014-07-22 16:08:19 -07001443 }
1444
Jayachandran Ca94c7172017-06-10 15:08:12 -07001445 DumpPacketStats();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001446
Chenbo Feng276a3b62018-08-07 11:44:49 -07001447 RunDumpsys("EBPF MAP STATS", {"netd", "trafficcontroller"});
1448
Felipe Leme6ec6ac42017-01-10 15:29:53 -08001449 DoKmsg();
Mark Salyzyn2262c162014-12-16 09:09:26 -08001450
Jayachandran Ca94c7172017-06-10 15:08:12 -07001451 DumpIpAddrAndRules();
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001452
1453 dump_route_tables();
1454
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001455 RunCommand("ARP CACHE", {"ip", "-4", "neigh", "show"});
1456 RunCommand("IPv6 ND CACHE", {"ip", "-6", "neigh", "show"});
1457 RunCommand("MULTICAST ADDRESSES", {"ip", "maddr"});
Colin Crossf45fa6b2012-03-26 12:38:26 -07001458
Nandana Dutt5c390032019-03-12 10:52:56 +00001459 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(RunDumpsysHigh);
Lorenzo Colitti6afc38c2015-09-09 22:59:25 +09001460
Elliott Hughes23ccc622017-02-28 10:14:22 -08001461 RunCommand("SYSTEM PROPERTIES", {"getprop"});
Colin Crossf45fa6b2012-03-26 12:38:26 -07001462
Jin Qianf334d662017-10-10 14:41:37 -07001463 RunCommand("STORAGED IO INFO", {"storaged", "-u", "-p"});
ynwangf649a6e2016-07-17 21:56:00 -07001464
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001465 RunCommand("FILESYSTEMS & FREE SPACE", {"df"});
Colin Crossf45fa6b2012-03-26 12:38:26 -07001466
Colin Crossf45fa6b2012-03-26 12:38:26 -07001467 /* Binder state is expensive to look at as it uses a lot of memory. */
Hridya Valsaraju920ba712020-02-09 16:27:01 -08001468 std::string binder_logs_dir = access("/dev/binderfs/binder_logs", R_OK) ?
1469 "/sys/kernel/debug/binder" : "/dev/binderfs/binder_logs";
1470
1471 DumpFile("BINDER FAILED TRANSACTION LOG", binder_logs_dir + "/failed_transaction_log");
1472 DumpFile("BINDER TRANSACTION LOG", binder_logs_dir + "/transaction_log");
1473 DumpFile("BINDER TRANSACTIONS", binder_logs_dir + "/transactions");
1474 DumpFile("BINDER STATS", binder_logs_dir + "/stats");
1475 DumpFile("BINDER STATE", binder_logs_dir + "/state");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001476
Vishnu Nair36b4cdb2017-11-17 10:27:05 -08001477 /* Add window and surface trace files. */
1478 if (!PropertiesHelper::IsUserBuild()) {
1479 ds.AddDir(WMTRACE_DATA_DIR, false);
1480 }
1481
Yifan Hongd90cc652020-02-08 16:52:02 -08001482 ds.AddDir(SNAPSHOTCTL_LOG_DIR, false);
1483
Nandana Dutt5c390032019-03-12 10:52:56 +00001484 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(ds.DumpstateBoard);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001485
Steven Moreland7440ddb2016-12-15 16:13:39 -08001486 /* Migrate the ril_dumpstate to a device specific dumpstate? */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001487 int rilDumpstateTimeout = android::base::GetIntProperty("ril.dumpstate.timeout", 0);
1488 if (rilDumpstateTimeout > 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001489 // su does not exist on user builds, so try running without it.
1490 // This way any implementations of vril-dump that do not require
1491 // root can run on user builds.
1492 CommandOptions::CommandOptionsBuilder options =
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001493 CommandOptions::WithTimeout(rilDumpstateTimeout);
Felipe Lemef0292972016-11-22 13:57:05 -08001494 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001495 options.AsRoot();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001496 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001497 RunCommand("DUMP VENDOR RIL LOGS", {"vril-dump"}, options.Build());
Colin Crossf45fa6b2012-03-26 12:38:26 -07001498 }
1499
Felipe Lemed8b94e52016-12-08 10:21:44 -08001500 printf("========================================================\n");
1501 printf("== Android Framework Services\n");
1502 printf("========================================================\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001503
Nandana Dutt5c390032019-03-12 10:52:56 +00001504 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(RunDumpsysNormal);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001505
Felipe Lemed8b94e52016-12-08 10:21:44 -08001506 printf("========================================================\n");
1507 printf("== Checkins\n");
1508 printf("========================================================\n");
Dianne Hackborn02bea972013-06-26 18:59:09 -07001509
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001510 RunDumpsys("CHECKIN BATTERYSTATS", {"batterystats", "-c"});
Nandana Dutt5c390032019-03-12 10:52:56 +00001511
1512 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(RunDumpsys, "CHECKIN MEMINFO", {"meminfo", "--checkin"});
1513
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001514 RunDumpsys("CHECKIN NETSTATS", {"netstats", "--checkin"});
1515 RunDumpsys("CHECKIN PROCSTATS", {"procstats", "-c"});
1516 RunDumpsys("CHECKIN USAGESTATS", {"usagestats", "-c"});
1517 RunDumpsys("CHECKIN PACKAGE", {"package", "--checkin"});
Dianne Hackborn02bea972013-06-26 18:59:09 -07001518
Felipe Lemed8b94e52016-12-08 10:21:44 -08001519 printf("========================================================\n");
1520 printf("== Running Application Activities\n");
1521 printf("========================================================\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001522
Makoto Onuki60780982018-04-16 15:34:00 -07001523 // The following dumpsys internally collects output from running apps, so it can take a long
1524 // time. So let's extend the timeout.
1525
1526 const CommandOptions DUMPSYS_COMPONENTS_OPTIONS = CommandOptions::WithTimeout(60).Build();
1527
1528 RunDumpsys("APP ACTIVITIES", {"activity", "-v", "all"}, DUMPSYS_COMPONENTS_OPTIONS);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001529
Felipe Lemed8b94e52016-12-08 10:21:44 -08001530 printf("========================================================\n");
Makoto Onuki60780982018-04-16 15:34:00 -07001531 printf("== Running Application Services (platform)\n");
Felipe Lemed8b94e52016-12-08 10:21:44 -08001532 printf("========================================================\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001533
Vishnu Nairc6e6ea72018-07-02 14:20:06 -07001534 RunDumpsys("APP SERVICES PLATFORM", {"activity", "service", "all-platform-non-critical"},
Makoto Onuki60780982018-04-16 15:34:00 -07001535 DUMPSYS_COMPONENTS_OPTIONS);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001536
Felipe Lemed8b94e52016-12-08 10:21:44 -08001537 printf("========================================================\n");
Makoto Onuki60780982018-04-16 15:34:00 -07001538 printf("== Running Application Services (non-platform)\n");
Felipe Lemed8b94e52016-12-08 10:21:44 -08001539 printf("========================================================\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001540
Makoto Onuki60780982018-04-16 15:34:00 -07001541 RunDumpsys("APP SERVICES NON-PLATFORM", {"activity", "service", "all-non-platform"},
1542 DUMPSYS_COMPONENTS_OPTIONS);
1543
1544 printf("========================================================\n");
1545 printf("== Running Application Providers (platform)\n");
1546 printf("========================================================\n");
1547
1548 RunDumpsys("APP PROVIDERS PLATFORM", {"activity", "provider", "all-platform"},
1549 DUMPSYS_COMPONENTS_OPTIONS);
1550
1551 printf("========================================================\n");
1552 printf("== Running Application Providers (non-platform)\n");
1553 printf("========================================================\n");
1554
1555 RunDumpsys("APP PROVIDERS NON-PLATFORM", {"activity", "provider", "all-non-platform"},
1556 DUMPSYS_COMPONENTS_OPTIONS);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001557
Adrian Roos8b397ab2017-04-04 16:35:44 -07001558 printf("========================================================\n");
1559 printf("== Dropbox crashes\n");
1560 printf("========================================================\n");
1561
1562 RunDumpsys("DROPBOX SYSTEM SERVER CRASHES", {"dropbox", "-p", "system_server_crash"});
1563 RunDumpsys("DROPBOX SYSTEM APP CRASHES", {"dropbox", "-p", "system_app_crash"});
1564
Felipe Lemed8b94e52016-12-08 10:21:44 -08001565 printf("========================================================\n");
1566 printf("== Final progress (pid %d): %d/%d (estimated %d)\n", ds.pid_, ds.progress_->Get(),
1567 ds.progress_->GetMax(), ds.progress_->GetInitialMax());
1568 printf("========================================================\n");
1569 printf("== dumpstate: done (id %d)\n", ds.id_);
1570 printf("========================================================\n");
Bookatz38472142018-09-28 10:20:24 -07001571
1572 printf("========================================================\n");
1573 printf("== Obtaining statsd metadata\n");
1574 printf("========================================================\n");
1575 // This differs from the usual dumpsys stats, which is the stats report data.
1576 RunDumpsys("STATSDSTATS", {"stats", "--metadata"});
Mike Ma5c267872019-08-21 11:31:34 -07001577
Kiyoung Kimc2d22ac2020-02-04 19:43:36 +09001578 // Add linker configuration directory
1579 ds.AddDir(LINKERCONFIG_DIR, true);
1580
Mike Ma5c267872019-08-21 11:31:34 -07001581 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(DumpIncidentReport);
1582
Nandana Dutt5c390032019-03-12 10:52:56 +00001583 return Dumpstate::RunStatus::OK;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001584}
1585
Nandana Dutt5c390032019-03-12 10:52:56 +00001586/*
1587 * Dumps state for the default case; drops root after it's no longer necessary.
1588 *
1589 * Returns RunStatus::OK if everything went fine.
1590 * Returns RunStatus::ERROR if there was an error.
1591 * Returns RunStatus::USER_DENIED_CONSENT if user explicitly denied consent to sharing the bugreport
1592 * with the caller.
1593 */
Jichao Lie89d9c12019-11-21 19:02:51 -08001594Dumpstate::RunStatus Dumpstate::DumpstateDefaultAfterCritical() {
Nandana Duttdb379fa2019-10-09 16:54:41 +01001595 // Capture first logcat early on; useful to take a snapshot before dumpstate logs take over the
1596 // buffer.
1597 DoLogcat();
1598 // Capture timestamp after first logcat to use in next logcat
1599 time_t logcat_ts = time(nullptr);
1600
Nandana Dutt4be45d12018-09-26 15:04:23 +01001601 /* collect stack traces from Dalvik and native processes (needs root) */
Nandana Duttcf419a72019-03-14 10:40:17 +00001602 RUN_SLOW_FUNCTION_WITH_CONSENT_CHECK(ds.DumpTraces, &dump_traces_path);
Nandana Dutt4be45d12018-09-26 15:04:23 +01001603
1604 /* Run some operations that require root. */
1605 ds.tombstone_data_ = GetDumpFds(TOMBSTONE_DIR, TOMBSTONE_FILE_PREFIX, !ds.IsZipping());
1606 ds.anr_data_ = GetDumpFds(ANR_DIR, ANR_FILE_PREFIX, !ds.IsZipping());
1607
1608 ds.AddDir(RECOVERY_DIR, true);
1609 ds.AddDir(RECOVERY_DATA_DIR, true);
1610 ds.AddDir(UPDATE_ENGINE_LOG_DIR, true);
1611 ds.AddDir(LOGPERSIST_DATA_DIR, false);
1612 if (!PropertiesHelper::IsUserBuild()) {
1613 ds.AddDir(PROFILE_DATA_DIR_CUR, true);
1614 ds.AddDir(PROFILE_DATA_DIR_REF, true);
1615 }
Jerry Changa1df8a92020-01-02 16:03:39 +08001616 ds.AddDir(PREREBOOT_DATA_DIR, false);
Nandana Dutt4be45d12018-09-26 15:04:23 +01001617 add_mountinfo();
1618 DumpIpTablesAsRoot();
David Andersond9ba4752018-12-11 18:26:59 -08001619 DumpDynamicPartitionInfo();
Yifan Hong3945e1b2019-10-29 12:59:23 -07001620 ds.AddDir(OTA_METADATA_DIR, true);
Nandana Dutt4be45d12018-09-26 15:04:23 +01001621
Benedict Wong8f9d8a42019-01-03 16:19:38 -08001622 // Capture any IPSec policies in play. No keys are exposed here.
Nandana Dutt4be45d12018-09-26 15:04:23 +01001623 RunCommand("IP XFRM POLICY", {"ip", "xfrm", "policy"}, CommandOptions::WithTimeout(10).Build());
1624
Benedict Wong8f9d8a42019-01-03 16:19:38 -08001625 // Dump IPsec stats. No keys are exposed here.
1626 DumpFile("XFRM STATS", XFRM_STAT_PROC_FILE);
1627
Nandana Dutt4be45d12018-09-26 15:04:23 +01001628 // Run ss as root so we can see socket marks.
1629 RunCommand("DETAILED SOCKET STATE", {"ss", "-eionptu"}, CommandOptions::WithTimeout(10).Build());
1630
1631 // Run iotop as root to show top 100 IO threads
1632 RunCommand("IOTOP", {"iotop", "-n", "1", "-m", "100"});
1633
Erick Reyese68df822019-02-11 14:46:36 -08001634 // Gather shared memory buffer info if the product implements it
1635 struct stat st;
1636 if (!stat("/product/bin/dmabuf_dump", &st)) {
1637 RunCommand("Dmabuf dump", {"/product/bin/dmabuf_dump"});
1638 }
1639
Minchan Kim22c6a1e2019-09-30 15:58:10 -07001640 DumpFile("PSI cpu", "/proc/pressure/cpu");
1641 DumpFile("PSI memory", "/proc/pressure/memory");
1642 DumpFile("PSI io", "/proc/pressure/io");
1643
Nandana Dutt4be45d12018-09-26 15:04:23 +01001644 if (!DropRootUser()) {
Nandana Dutt5c390032019-03-12 10:52:56 +00001645 return Dumpstate::RunStatus::ERROR;
Nandana Dutt4be45d12018-09-26 15:04:23 +01001646 }
1647
Nandana Dutt5c390032019-03-12 10:52:56 +00001648 RETURN_IF_USER_DENIED_CONSENT();
Nandana Duttdb379fa2019-10-09 16:54:41 +01001649 Dumpstate::RunStatus status = dumpstate();
1650 // Capture logcat since the last time we did it.
1651 DoSystemLogcat(logcat_ts);
1652 return status;
Nandana Dutt4be45d12018-09-26 15:04:23 +01001653}
1654
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001655// This method collects common dumpsys for telephony and wifi. Typically, wifi
1656// reports are fine to include all information, but telephony reports on user
1657// builds need to strip some content (see DumpstateTelephonyOnly).
1658static void DumpstateRadioCommon(bool include_sensitive_info = true) {
Jayachandran Ca94c7172017-06-10 15:08:12 -07001659 DumpIpTablesAsRoot();
1660
Jayachandran Cb4389d92019-07-08 09:46:05 -07001661 ds.AddDir(LOGPERSIST_DATA_DIR, false);
1662
Jayachandran Ca94c7172017-06-10 15:08:12 -07001663 if (!DropRootUser()) {
1664 return;
1665 }
1666
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001667 // We need to be picky about some stuff for telephony reports on user builds.
1668 if (!include_sensitive_info) {
1669 // Only dump the radio log buffer (other buffers and dumps contain too much unrelated info).
1670 DoRadioLogcat();
1671 } else {
1672 // Contains various system properties and process startup info.
1673 do_dmesg();
1674 // Logs other than the radio buffer may contain package/component names and potential PII.
1675 DoLogcat();
1676 // Too broad for connectivity problems.
1677 DoKmsg();
1678 // Contains unrelated hardware info (camera, NFC, biometrics, ...).
1679 DumpHals();
1680 }
1681
Jayachandran Ca94c7172017-06-10 15:08:12 -07001682 DumpPacketStats();
Jayachandran Ca94c7172017-06-10 15:08:12 -07001683 DumpIpAddrAndRules();
1684 dump_route_tables();
Jayachandran Ca94c7172017-06-10 15:08:12 -07001685 RunDumpsys("NETWORK DIAGNOSTICS", {"connectivity", "--diag"},
1686 CommandOptions::WithTimeout(10).Build());
mukesh agrawal253dad42018-01-23 21:59:59 -08001687}
1688
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001689// We use "telephony" here for legacy reasons, though this now really means "connectivity" (cellular
1690// + wifi + networking). This method collects dumpsys for connectivity debugging only. General rules
1691// for what can be included on user builds: all reported information MUST directly relate to
1692// connectivity debugging or customer support and MUST NOT contain unrelated personally identifiable
1693// information. This information MUST NOT identify user-installed packages (UIDs are OK, package
1694// names are not), and MUST NOT contain logs of user application traffic.
1695// TODO(b/148168577) rename this and other related fields/methods to "connectivity" instead.
Hunter Knepshield0cc6c212020-01-07 16:57:10 -08001696static void DumpstateTelephonyOnly(const std::string& calling_package) {
mukesh agrawal253dad42018-01-23 21:59:59 -08001697 DurationReporter duration_reporter("DUMPSTATE");
Jichao Lie89d9c12019-11-21 19:02:51 -08001698
Sooraj Sasindrana0829e72018-05-19 15:52:17 -07001699 const CommandOptions DUMPSYS_COMPONENTS_OPTIONS = CommandOptions::WithTimeout(60).Build();
mukesh agrawal253dad42018-01-23 21:59:59 -08001700
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001701 const bool include_sensitive_info = !PropertiesHelper::IsUserBuild();
Jayachandran Ca94c7172017-06-10 15:08:12 -07001702
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001703 DumpstateRadioCommon(include_sensitive_info);
1704
1705 if (include_sensitive_info) {
1706 // Contains too much unrelated PII, and given the unstructured nature of sysprops, we can't
1707 // really cherrypick all of the connectivity-related ones. Apps generally have no business
1708 // reading these anyway, and there should be APIs to supply the info in a more app-friendly
1709 // way.
1710 RunCommand("SYSTEM PROPERTIES", {"getprop"});
1711 }
Jayachandran Ca94c7172017-06-10 15:08:12 -07001712
1713 printf("========================================================\n");
1714 printf("== Android Framework Services\n");
1715 printf("========================================================\n");
1716
Vishnu Nair652cc802017-11-30 15:18:30 -08001717 RunDumpsys("DUMPSYS", {"connectivity"}, CommandOptions::WithTimeout(90).Build(),
1718 SEC_TO_MSEC(10));
Hunter Knepshield0cc6c212020-01-07 16:57:10 -08001719 if (include_sensitive_info) {
1720 // Carrier apps' services will be dumped below in dumpsys activity service all-non-platform.
1721 RunDumpsys("DUMPSYS", {"carrier_config"}, CommandOptions::WithTimeout(90).Build(),
1722 SEC_TO_MSEC(10));
1723 } else {
1724 // If the caller is a carrier app and has a carrier service, dump it here since we aren't
1725 // running dumpsys activity service all-non-platform below. Due to the increased output, we
1726 // give a higher timeout as well.
1727 RunDumpsys("DUMPSYS", {"carrier_config", "--requesting-package", calling_package},
1728 CommandOptions::WithTimeout(90).Build(), SEC_TO_MSEC(30));
1729 }
1730 RunDumpsys("DUMPSYS", {"wifi"}, CommandOptions::WithTimeout(90).Build(), SEC_TO_MSEC(10));
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001731 RunDumpsys("DUMPSYS", {"netpolicy"}, CommandOptions::WithTimeout(90).Build(), SEC_TO_MSEC(10));
1732 RunDumpsys("DUMPSYS", {"network_management"}, CommandOptions::WithTimeout(90).Build(),
Sooraj Sasindrane8d98912018-04-20 11:31:55 -07001733 SEC_TO_MSEC(10));
Hunter Knepshield0fe51b12020-03-05 16:58:20 -08001734 RunDumpsys("DUMPSYS", {"telephony.registry"}, CommandOptions::WithTimeout(90).Build(),
1735 SEC_TO_MSEC(10));
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001736 if (include_sensitive_info) {
1737 // Contains raw IP addresses, omit from reports on user builds.
1738 RunDumpsys("DUMPSYS", {"netd"}, CommandOptions::WithTimeout(90).Build(), SEC_TO_MSEC(10));
1739 // Contains raw destination IP/MAC addresses, omit from reports on user builds.
1740 RunDumpsys("DUMPSYS", {"connmetrics"}, CommandOptions::WithTimeout(90).Build(),
1741 SEC_TO_MSEC(10));
1742 // Contains package/component names, omit from reports on user builds.
1743 RunDumpsys("BATTERYSTATS", {"batterystats"}, CommandOptions::WithTimeout(90).Build(),
1744 SEC_TO_MSEC(10));
1745 // Contains package names, but should be relatively simple to remove them (also contains
1746 // UIDs already), omit from reports on user builds.
1747 RunDumpsys("BATTERYSTATS", {"deviceidle"}, CommandOptions::WithTimeout(90).Build(),
1748 SEC_TO_MSEC(10));
1749 }
Jayachandran Ca94c7172017-06-10 15:08:12 -07001750
1751 printf("========================================================\n");
1752 printf("== Running Application Services\n");
1753 printf("========================================================\n");
1754
1755 RunDumpsys("TELEPHONY SERVICES", {"activity", "service", "TelephonyDebugService"});
1756
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001757 if (include_sensitive_info) {
1758 printf("========================================================\n");
1759 printf("== Running Application Services (non-platform)\n");
1760 printf("========================================================\n");
Sooraj Sasindrana0829e72018-05-19 15:52:17 -07001761
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001762 // Contains package/component names and potential PII, omit from reports on user builds.
1763 // To get dumps of the active CarrierService(s) on user builds, we supply an argument to the
1764 // carrier_config dumpsys instead.
1765 RunDumpsys("APP SERVICES NON-PLATFORM", {"activity", "service", "all-non-platform"},
1766 DUMPSYS_COMPONENTS_OPTIONS);
Sooraj Sasindrana0829e72018-05-19 15:52:17 -07001767
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001768 printf("========================================================\n");
1769 printf("== Checkins\n");
1770 printf("========================================================\n");
Kelly Rossmoyer769babb2018-08-21 18:06:38 -07001771
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08001772 // Contains package/component names, omit from reports on user builds.
1773 RunDumpsys("CHECKIN BATTERYSTATS", {"batterystats", "-c"});
1774 }
Kelly Rossmoyer769babb2018-08-21 18:06:38 -07001775
1776 printf("========================================================\n");
Jayachandran Ca94c7172017-06-10 15:08:12 -07001777 printf("== dumpstate: done (id %d)\n", ds.id_);
1778 printf("========================================================\n");
1779}
1780
mukesh agrawal253dad42018-01-23 21:59:59 -08001781// This method collects dumpsys for wifi debugging only
1782static void DumpstateWifiOnly() {
1783 DurationReporter duration_reporter("DUMPSTATE");
1784
1785 DumpstateRadioCommon();
1786
1787 printf("========================================================\n");
1788 printf("== Android Framework Services\n");
1789 printf("========================================================\n");
1790
1791 RunDumpsys("DUMPSYS", {"connectivity"}, CommandOptions::WithTimeout(90).Build(),
1792 SEC_TO_MSEC(10));
1793 RunDumpsys("DUMPSYS", {"wifi"}, CommandOptions::WithTimeout(90).Build(),
1794 SEC_TO_MSEC(10));
1795
1796 printf("========================================================\n");
1797 printf("== dumpstate: done (id %d)\n", ds.id_);
1798 printf("========================================================\n");
1799}
1800
Nandana Duttcf419a72019-03-14 10:40:17 +00001801Dumpstate::RunStatus Dumpstate::DumpTraces(const char** path) {
Nandana Duttfaafd522019-03-11 09:23:09 +00001802 DurationReporter duration_reporter("DUMP TRACES");
1803
1804 const std::string temp_file_pattern = "/data/anr/dumptrace_XXXXXX";
1805 const size_t buf_size = temp_file_pattern.length() + 1;
1806 std::unique_ptr<char[]> file_name_buf(new char[buf_size]);
1807 memcpy(file_name_buf.get(), temp_file_pattern.c_str(), buf_size);
1808
1809 // Create a new, empty file to receive all trace dumps.
1810 //
1811 // TODO: This can be simplified once we remove support for the old style
1812 // dumps. We can have a file descriptor passed in to dump_traces instead
1813 // of creating a file, closing it and then reopening it again.
1814 android::base::unique_fd fd(mkostemp(file_name_buf.get(), O_APPEND | O_CLOEXEC));
1815 if (fd < 0) {
1816 MYLOGE("mkostemp on pattern %s: %s\n", file_name_buf.get(), strerror(errno));
Nandana Duttcf419a72019-03-14 10:40:17 +00001817 return RunStatus::OK;
Nandana Duttfaafd522019-03-11 09:23:09 +00001818 }
1819
1820 // Nobody should have access to this temporary file except dumpstate, but we
1821 // temporarily grant 'read' to 'others' here because this file is created
1822 // when tombstoned is still running as root, but dumped after dropping. This
1823 // can go away once support for old style dumping has.
1824 const int chmod_ret = fchmod(fd, 0666);
1825 if (chmod_ret < 0) {
1826 MYLOGE("fchmod on %s failed: %s\n", file_name_buf.get(), strerror(errno));
Nandana Duttcf419a72019-03-14 10:40:17 +00001827 return RunStatus::OK;
Nandana Duttfaafd522019-03-11 09:23:09 +00001828 }
1829
1830 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
1831 if (proc.get() == nullptr) {
1832 MYLOGE("opendir /proc failed: %s\n", strerror(errno));
Nandana Duttcf419a72019-03-14 10:40:17 +00001833 return RunStatus::OK;
Nandana Duttfaafd522019-03-11 09:23:09 +00001834 }
1835
1836 // Number of times process dumping has timed out. If we encounter too many
1837 // failures, we'll give up.
1838 int timeout_failures = 0;
1839 bool dalvik_found = false;
1840
1841 const std::set<int> hal_pids = get_interesting_hal_pids();
1842
1843 struct dirent* d;
1844 while ((d = readdir(proc.get()))) {
Nandana Duttcf419a72019-03-14 10:40:17 +00001845 RETURN_IF_USER_DENIED_CONSENT();
Nandana Duttfaafd522019-03-11 09:23:09 +00001846 int pid = atoi(d->d_name);
1847 if (pid <= 0) {
1848 continue;
1849 }
1850
1851 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
1852 std::string exe;
1853 if (!android::base::Readlink(link_name, &exe)) {
1854 continue;
1855 }
1856
1857 bool is_java_process;
1858 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
1859 // Don't bother dumping backtraces for the zygote.
1860 if (IsZygote(pid)) {
1861 continue;
1862 }
1863
1864 dalvik_found = true;
1865 is_java_process = true;
1866 } else if (should_dump_native_traces(exe.c_str()) || hal_pids.find(pid) != hal_pids.end()) {
1867 is_java_process = false;
1868 } else {
1869 // Probably a native process we don't care about, continue.
1870 continue;
1871 }
1872
1873 // If 3 backtrace dumps fail in a row, consider debuggerd dead.
1874 if (timeout_failures == 3) {
1875 dprintf(fd, "ERROR: Too many stack dump failures, exiting.\n");
1876 break;
1877 }
1878
1879 const uint64_t start = Nanotime();
1880 const int ret = dump_backtrace_to_file_timeout(
1881 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
1882 is_java_process ? 5 : 20, fd);
1883
1884 if (ret == -1) {
1885 // For consistency, the header and footer to this message match those
1886 // dumped by debuggerd in the success case.
1887 dprintf(fd, "\n---- pid %d at [unknown] ----\n", pid);
1888 dprintf(fd, "Dump failed, likely due to a timeout.\n");
1889 dprintf(fd, "---- end %d ----", pid);
1890 timeout_failures++;
1891 continue;
1892 }
1893
1894 // We've successfully dumped stack traces, reset the failure count
1895 // and write a summary of the elapsed time to the file and continue with the
1896 // next process.
1897 timeout_failures = 0;
1898
1899 dprintf(fd, "[dump %s stack %d: %.3fs elapsed]\n", is_java_process ? "dalvik" : "native",
1900 pid, (float)(Nanotime() - start) / NANOS_PER_SEC);
1901 }
1902
1903 if (!dalvik_found) {
1904 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
1905 }
1906
Nandana Duttcf419a72019-03-14 10:40:17 +00001907 *path = file_name_buf.release();
1908 return RunStatus::OK;
Nandana Duttfaafd522019-03-11 09:23:09 +00001909}
1910
Felipe Leme6f674ae2016-11-18 17:10:33 -08001911void Dumpstate::DumpstateBoard() {
1912 DurationReporter duration_reporter("dumpstate_board()");
Felipe Lemed8b94e52016-12-08 10:21:44 -08001913 printf("========================================================\n");
1914 printf("== Board\n");
1915 printf("========================================================\n");
Felipe Leme6f674ae2016-11-18 17:10:33 -08001916
Felipe Leme6f674ae2016-11-18 17:10:33 -08001917 if (!IsZipping()) {
Steven Moreland7440ddb2016-12-15 16:13:39 -08001918 MYLOGD("Not dumping board info because it's not a zipped bugreport\n");
Felipe Leme6f674ae2016-11-18 17:10:33 -08001919 return;
1920 }
1921
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07001922 std::vector<std::string> paths;
1923 std::vector<android::base::ScopeGuard<std::function<void()>>> remover;
Jie Song9fbfad02017-06-20 16:29:42 -07001924 for (int i = 0; i < NUM_OF_DUMPS; i++) {
Nandana Dutt979388e2018-11-30 16:48:55 +00001925 paths.emplace_back(StringPrintf("%s/%s", ds.bugreport_internal_dir_.c_str(),
1926 kDumpstateBoardFiles[i].c_str()));
Nandana Dutt16d1aee2019-02-15 16:13:53 +00001927 remover.emplace_back(android::base::make_scope_guard(
1928 std::bind([](std::string path) { android::os::UnlinkAndLogOnError(path); }, paths[i])));
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07001929 }
Jie Song9fbfad02017-06-20 16:29:42 -07001930
Hunter Knepshield8540faf2020-02-04 19:47:20 -08001931 sp<IDumpstateDevice_1_0> dumpstate_device_1_0(IDumpstateDevice_1_0::getService());
1932 if (dumpstate_device_1_0 == nullptr) {
Wei Wang587eac92018-04-05 12:17:20 -07001933 MYLOGE("No IDumpstateDevice implementation\n");
1934 return;
1935 }
1936
1937 using ScopedNativeHandle =
1938 std::unique_ptr<native_handle_t, std::function<void(native_handle_t*)>>;
1939 ScopedNativeHandle handle(native_handle_create(static_cast<int>(paths.size()), 0),
1940 [](native_handle_t* handle) {
1941 native_handle_close(handle);
1942 native_handle_delete(handle);
1943 });
1944 if (handle == nullptr) {
1945 MYLOGE("Could not create native_handle\n");
1946 return;
1947 }
1948
Nandana Dutt5c390032019-03-12 10:52:56 +00001949 // TODO(128270426): Check for consent in between?
Wei Wang587eac92018-04-05 12:17:20 -07001950 for (size_t i = 0; i < paths.size(); i++) {
1951 MYLOGI("Calling IDumpstateDevice implementation using path %s\n", paths[i].c_str());
1952
1953 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1954 open(paths[i].c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1955 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1956 if (fd < 0) {
1957 MYLOGE("Could not open file %s: %s\n", paths[i].c_str(), strerror(errno));
1958 return;
1959 }
1960 handle.get()->data[i] = fd.release();
1961 }
1962
Hunter Knepshield8540faf2020-02-04 19:47:20 -08001963 // Given that bugreport is required to diagnose failures, it's better to set an arbitrary amount
1964 // of timeout for IDumpstateDevice than to block the rest of bugreport. In the timeout case, we
1965 // will kill the HAL and grab whatever it dumped in time.
1966 constexpr size_t timeout_sec = 30;
1967 // Prefer version 1.1 if available. New devices launching with R are no longer allowed to
1968 // implement just 1.0.
1969 const char* descriptor_to_kill;
1970 using DumpstateBoardTask = std::packaged_task<bool()>;
1971 DumpstateBoardTask dumpstate_board_task;
1972 sp<IDumpstateDevice_1_1> dumpstate_device_1_1(
1973 IDumpstateDevice_1_1::castFrom(dumpstate_device_1_0));
1974 if (dumpstate_device_1_1 != nullptr) {
1975 MYLOGI("Using IDumpstateDevice v1.1");
1976 descriptor_to_kill = IDumpstateDevice_1_1::descriptor;
1977 dumpstate_board_task = DumpstateBoardTask([this, dumpstate_device_1_1, &handle]() -> bool {
1978 ::android::hardware::Return<DumpstateStatus> status =
1979 dumpstate_device_1_1->dumpstateBoard_1_1(handle.get(), options_->dumpstate_hal_mode,
1980 SEC_TO_MSEC(timeout_sec));
1981 if (!status.isOk()) {
1982 MYLOGE("dumpstateBoard failed: %s\n", status.description().c_str());
1983 return false;
1984 } else if (status != DumpstateStatus::OK) {
1985 MYLOGE("dumpstateBoard failed with DumpstateStatus::%s\n", toString(status).c_str());
1986 return false;
1987 }
1988 return true;
1989 });
1990 } else {
1991 MYLOGI("Using IDumpstateDevice v1.0");
1992 descriptor_to_kill = IDumpstateDevice_1_0::descriptor;
1993 dumpstate_board_task = DumpstateBoardTask([dumpstate_device_1_0, &handle]() -> bool {
1994 ::android::hardware::Return<void> status =
1995 dumpstate_device_1_0->dumpstateBoard(handle.get());
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07001996 if (!status.isOk()) {
1997 MYLOGE("dumpstateBoard failed: %s\n", status.description().c_str());
Wei Wang587eac92018-04-05 12:17:20 -07001998 return false;
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07001999 }
Wei Wang587eac92018-04-05 12:17:20 -07002000 return true;
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07002001 });
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002002 }
2003 auto result = dumpstate_board_task.get_future();
2004 std::thread(std::move(dumpstate_board_task)).detach();
Wei Wang587eac92018-04-05 12:17:20 -07002005
Wei Wang587eac92018-04-05 12:17:20 -07002006 if (result.wait_for(std::chrono::seconds(timeout_sec)) != std::future_status::ready) {
2007 MYLOGE("dumpstateBoard timed out after %zus, killing dumpstate vendor HAL\n", timeout_sec);
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002008 if (!android::base::SetProperty(
2009 "ctl.interface_restart",
2010 android::base::StringPrintf("%s/default", descriptor_to_kill))) {
Wei Wang587eac92018-04-05 12:17:20 -07002011 MYLOGE("Couldn't restart dumpstate HAL\n");
2012 }
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07002013 }
Wei Wang587eac92018-04-05 12:17:20 -07002014 // Wait some time for init to kill dumpstate vendor HAL
2015 constexpr size_t killing_timeout_sec = 10;
2016 if (result.wait_for(std::chrono::seconds(killing_timeout_sec)) != std::future_status::ready) {
2017 MYLOGE("killing dumpstateBoard timed out after %zus, continue and "
2018 "there might be racing in content\n", killing_timeout_sec);
2019 }
2020
2021 auto file_sizes = std::make_unique<ssize_t[]>(paths.size());
2022 for (size_t i = 0; i < paths.size(); i++) {
2023 struct stat s;
2024 if (fstat(handle.get()->data[i], &s) == -1) {
2025 MYLOGE("Failed to fstat %s: %s\n", kDumpstateBoardFiles[i].c_str(),
2026 strerror(errno));
2027 file_sizes[i] = -1;
2028 continue;
2029 }
2030 file_sizes[i] = s.st_size;
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07002031 }
2032
2033 for (size_t i = 0; i < paths.size(); i++) {
2034 if (file_sizes[i] == -1) {
2035 continue;
Jie Song9fbfad02017-06-20 16:29:42 -07002036 }
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07002037 if (file_sizes[i] == 0) {
Jie Song9fbfad02017-06-20 16:29:42 -07002038 MYLOGE("Ignoring empty %s\n", kDumpstateBoardFiles[i].c_str());
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07002039 continue;
Jie Song9fbfad02017-06-20 16:29:42 -07002040 }
Luis Hector Chavez7aecd382018-03-19 11:16:59 -07002041 AddZipEntry(kDumpstateBoardFiles[i], paths[i]);
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002042 printf("*** See %s entry ***\n", kDumpstateBoardFiles[i].c_str());
Jie Song9fbfad02017-06-20 16:29:42 -07002043 }
Felipe Leme6f674ae2016-11-18 17:10:33 -08002044}
2045
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002046static void ShowUsage() {
Felipe Leme4a0db9f2016-09-28 09:35:01 -07002047 fprintf(stderr,
Abhijeet Kaurbb55a3b2019-06-13 18:07:25 +01002048 "usage: dumpstate [-h] [-b soundfile] [-e soundfile] [-d] [-p] "
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002049 "[-z] [-s] [-S] [-q] [-P] [-R] [-V version]\n"
Felipe Leme4a0db9f2016-09-28 09:35:01 -07002050 " -h: display this help message\n"
2051 " -b: play sound file instead of vibrate, at beginning of job\n"
2052 " -e: play sound file instead of vibrate, at end of job\n"
Abhijeet Kaurbb55a3b2019-06-13 18:07:25 +01002053 " -d: append date to filename\n"
2054 " -p: capture screenshot to filename.png\n"
2055 " -z: generate zipped file\n"
Felipe Leme4a0db9f2016-09-28 09:35:01 -07002056 " -s: write output to control socket (for init)\n"
Abhijeet Kaurbb55a3b2019-06-13 18:07:25 +01002057 " -S: write file location to control socket (for init; requires -z)\n"
Felipe Leme4a0db9f2016-09-28 09:35:01 -07002058 " -q: disable vibrate\n"
Abhijeet Kaure370d682019-10-01 16:49:30 +01002059 " -P: send broadcast when started and do progress updates\n"
2060 " -R: take bugreport in remote mode (requires -z and -d, shouldn't be used with -P)\n"
Nandana Dutt235864b2019-01-22 12:10:16 +00002061 " -w: start binder service and make it wait for a call to startBugreport\n"
Felipe Lemed071c682016-10-20 16:48:00 -07002062 " -v: prints the dumpstate header and exit\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07002063}
2064
Wei Liuf87959e2016-08-26 14:51:42 -07002065static void register_sig_handler() {
Luis Hector Chavez558e1ef2018-03-22 15:39:17 -07002066 signal(SIGPIPE, SIG_IGN);
Wei Liuf87959e2016-08-26 14:51:42 -07002067}
2068
Felipe Leme1d486fe2016-10-14 18:06:47 -07002069bool Dumpstate::FinishZipFile() {
Felipe Leme9a523ae2016-10-20 15:10:33 -07002070 std::string entry_name = base_name_ + "-" + name_ + ".txt";
Felipe Leme1d486fe2016-10-14 18:06:47 -07002071 MYLOGD("Adding main entry (%s) from %s to .zip bugreport\n", entry_name.c_str(),
Felipe Leme9a523ae2016-10-20 15:10:33 -07002072 tmp_path_.c_str());
Felipe Leme5b9d3bf2016-08-16 17:20:21 -07002073 // Final timestamp
2074 char date[80];
2075 time_t the_real_now_please_stand_up = time(nullptr);
2076 strftime(date, sizeof(date), "%Y/%m/%d %H:%M:%S", localtime(&the_real_now_please_stand_up));
Felipe Leme7447d7c2016-11-03 18:12:22 -07002077 MYLOGD("dumpstate id %d finished around %s (%ld s)\n", ds.id_, date,
Felipe Lemebbaf3c12016-10-11 14:32:25 -07002078 the_real_now_please_stand_up - ds.now_);
Felipe Leme5b9d3bf2016-08-16 17:20:21 -07002079
Felipe Leme9a523ae2016-10-20 15:10:33 -07002080 if (!ds.AddZipEntry(entry_name, tmp_path_)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08002081 MYLOGE("Failed to add text entry to .zip file\n");
Felipe Leme1e9edc62015-12-21 16:02:13 -08002082 return false;
2083 }
Felipe Leme1d486fe2016-10-14 18:06:47 -07002084 if (!AddTextZipEntry("main_entry.txt", entry_name)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08002085 MYLOGE("Failed to add main_entry.txt to .zip file\n");
Felipe Leme111b9d02016-02-03 09:28:24 -08002086 return false;
Felipe Leme809d74e2016-02-02 12:57:00 -08002087 }
Felipe Leme1e9edc62015-12-21 16:02:13 -08002088
Felipe Leme0f3fb202016-06-10 17:10:53 -07002089 // Add log file (which contains stderr output) to zip...
2090 fprintf(stderr, "dumpstate_log.txt entry on zip file logged up to here\n");
Felipe Leme9a523ae2016-10-20 15:10:33 -07002091 if (!ds.AddZipEntry("dumpstate_log.txt", ds.log_path_.c_str())) {
Felipe Leme0f3fb202016-06-10 17:10:53 -07002092 MYLOGE("Failed to add dumpstate log to .zip file\n");
2093 return false;
2094 }
Nandana Dutt979388e2018-11-30 16:48:55 +00002095 // TODO: Should truncate the existing file.
2096 // ... and re-open it for further logging.
Nandana Dutta344cb62019-02-22 15:12:35 +00002097 if (!redirect_to_existing_file(stderr, const_cast<char*>(ds.log_path_.c_str()))) {
2098 return false;
2099 }
Felipe Leme0f3fb202016-06-10 17:10:53 -07002100 fprintf(stderr, "\n");
2101
Felipe Lemec6bc8bc2016-10-27 15:58:27 -07002102 int32_t err = zip_writer_->Finish();
Felipe Leme1d486fe2016-10-14 18:06:47 -07002103 if (err != 0) {
Felipe Lemec6bc8bc2016-10-27 15:58:27 -07002104 MYLOGE("zip_writer_->Finish(): %s\n", ZipWriter::ErrorCodeString(err));
Felipe Leme1e9edc62015-12-21 16:02:13 -08002105 return false;
2106 }
2107
Felipe Leme1d486fe2016-10-14 18:06:47 -07002108 // TODO: remove once FinishZipFile() is automatically handled by Dumpstate's destructor.
2109 ds.zip_file.reset(nullptr);
2110
Felipe Lemee9d2c542016-11-15 11:48:26 -08002111 MYLOGD("Removing temporary file %s\n", tmp_path_.c_str())
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002112 android::os::UnlinkAndLogOnError(tmp_path_);
Felipe Lemec4eee562016-04-21 15:42:55 -07002113
Felipe Leme1e9edc62015-12-21 16:02:13 -08002114 return true;
2115}
Felipe Leme6e01fa62015-11-11 19:35:14 -08002116
Felipe Lemea4ef1f02017-02-15 17:27:40 -08002117static void SendBroadcast(const std::string& action, const std::vector<std::string>& args) {
2118 // clang-format off
2119 std::vector<std::string> am = {"/system/bin/cmd", "activity", "broadcast", "--user", "0",
2120 "--receiver-foreground", "--receiver-include-background", "-a", action};
2121 // clang-format on
Felipe Leme8d2410e2017-02-08 09:46:08 -08002122
2123 am.insert(am.end(), args.begin(), args.end());
2124
Felipe Leme8d2410e2017-02-08 09:46:08 -08002125 RunCommand("", am,
2126 CommandOptions::WithTimeout(20)
2127 .Log("Sending broadcast: '%s'\n")
2128 .Always()
2129 .DropRoot()
2130 .RedirectStderr()
2131 .Build());
2132}
2133
Felipe Leme35b8cf12017-02-10 15:47:29 -08002134static void Vibrate(int duration_ms) {
2135 // clang-format off
Chris Fries0c3de872019-09-14 15:49:41 +00002136 RunCommand("", {"cmd", "vibrator", "vibrate", "-f", std::to_string(duration_ms), "dumpstate"},
Felipe Leme35b8cf12017-02-10 15:47:29 -08002137 CommandOptions::WithTimeout(10)
2138 .Log("Vibrate: '%s'\n")
2139 .Always()
2140 .Build());
2141 // clang-format on
2142}
2143
Nandana Dutt979388e2018-11-30 16:48:55 +00002144static void MaybeResolveSymlink(std::string* path) {
2145 std::string resolved_path;
2146 if (android::base::Readlink(*path, &resolved_path)) {
2147 *path = resolved_path;
2148 }
2149}
2150
Nandana Dutt4be45d12018-09-26 15:04:23 +01002151/*
2152 * Prepares state like filename, screenshot path, etc in Dumpstate. Also initializes ZipWriter
2153 * if we are writing zip files and adds the version file.
2154 */
2155static void PrepareToWriteToFile() {
Nandana Dutt979388e2018-11-30 16:48:55 +00002156 MaybeResolveSymlink(&ds.bugreport_internal_dir_);
2157
Nandana Dutt4be45d12018-09-26 15:04:23 +01002158 std::string build_id = android::base::GetProperty("ro.build.id", "UNKNOWN_BUILD");
2159 std::string device_name = android::base::GetProperty("ro.product.name", "UNKNOWN_DEVICE");
Nandana Dutt9a76d202019-01-21 15:56:48 +00002160 ds.base_name_ = StringPrintf("bugreport-%s-%s", device_name.c_str(), build_id.c_str());
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002161 if (ds.options_->do_add_date) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002162 char date[80];
2163 strftime(date, sizeof(date), "%Y-%m-%d-%H-%M-%S", localtime(&ds.now_));
2164 ds.name_ = date;
2165 } else {
2166 ds.name_ = "undated";
2167 }
2168
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002169 if (ds.options_->telephony_only) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002170 ds.base_name_ += "-telephony";
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002171 } else if (ds.options_->wifi_only) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002172 ds.base_name_ += "-wifi";
2173 }
2174
Paul Chang0d2aad72020-02-13 20:04:03 +08002175 if (ds.options_->do_screenshot) {
Nandana Dutt9d17b942020-03-26 10:02:59 +00002176 ds.screenshot_path_ = ds.GetPath(ds.CalledByApi() ? "-png.tmp" : ".png");
Nandana Dutt4be45d12018-09-26 15:04:23 +01002177 }
2178 ds.tmp_path_ = ds.GetPath(".tmp");
2179 ds.log_path_ = ds.GetPath("-dumpstate_log-" + std::to_string(ds.pid_) + ".txt");
2180
Abhijeet Kaur359b1ff2019-07-26 16:01:36 +01002181 std::string destination = ds.CalledByApi()
Nandana Dutt54dbd672019-01-11 12:58:05 +00002182 ? StringPrintf("[fd:%d]", ds.options_->bugreport_fd.get())
Nandana Dutt9a76d202019-01-21 15:56:48 +00002183 : ds.bugreport_internal_dir_.c_str();
Nandana Dutt4be45d12018-09-26 15:04:23 +01002184 MYLOGD(
Nandana Dutt235c6672019-11-14 15:22:32 +00002185 "Bugreport dir: [%s] "
2186 "Base name: [%s] "
2187 "Suffix: [%s] "
2188 "Log path: [%s] "
2189 "Temporary path: [%s] "
2190 "Screenshot path: [%s]\n",
Nandana Dutt9a76d202019-01-21 15:56:48 +00002191 destination.c_str(), ds.base_name_.c_str(), ds.name_.c_str(), ds.log_path_.c_str(),
2192 ds.tmp_path_.c_str(), ds.screenshot_path_.c_str());
Nandana Dutt4be45d12018-09-26 15:04:23 +01002193
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002194 if (ds.options_->do_zip_file) {
Nandana Dutt9d17b942020-03-26 10:02:59 +00002195 ds.path_ = ds.GetPath(ds.CalledByApi() ? "-zip.tmp" : ".zip");
Nandana Dutt4be45d12018-09-26 15:04:23 +01002196 MYLOGD("Creating initial .zip file (%s)\n", ds.path_.c_str());
2197 create_parent_dirs(ds.path_.c_str());
2198 ds.zip_file.reset(fopen(ds.path_.c_str(), "wb"));
2199 if (ds.zip_file == nullptr) {
2200 MYLOGE("fopen(%s, 'wb'): %s\n", ds.path_.c_str(), strerror(errno));
2201 } else {
2202 ds.zip_writer_.reset(new ZipWriter(ds.zip_file.get()));
2203 }
2204 ds.AddTextZipEntry("version.txt", ds.version_);
2205 }
2206}
2207
2208/*
Abhijeet Kaure370d682019-10-01 16:49:30 +01002209 * Finalizes writing to the file by zipping the tmp file to the final location,
Nandana Dutt4be45d12018-09-26 15:04:23 +01002210 * printing zipped file status, etc.
2211 */
2212static void FinalizeFile() {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002213 bool do_text_file = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002214 if (ds.options_->do_zip_file) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002215 if (!ds.FinishZipFile()) {
2216 MYLOGE("Failed to finish zip file; sending text bugreport instead\n");
2217 do_text_file = true;
2218 } else {
2219 do_text_file = false;
Nandana Dutt4be45d12018-09-26 15:04:23 +01002220 }
2221 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002222 if (ds.options_->use_control_socket) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002223 if (do_text_file) {
2224 dprintf(ds.control_socket_fd_,
2225 "FAIL:could not create zip file, check %s "
2226 "for more details\n",
2227 ds.log_path_.c_str());
2228 } else {
2229 dprintf(ds.control_socket_fd_, "OK:%s\n", ds.path_.c_str());
2230 }
2231 }
2232}
2233
Nandana Dutt4be45d12018-09-26 15:04:23 +01002234
Nandana Dutt58d72e22018-11-16 10:30:48 +00002235static inline const char* ModeToString(Dumpstate::BugreportMode mode) {
2236 switch (mode) {
2237 case Dumpstate::BugreportMode::BUGREPORT_FULL:
2238 return "BUGREPORT_FULL";
2239 case Dumpstate::BugreportMode::BUGREPORT_INTERACTIVE:
2240 return "BUGREPORT_INTERACTIVE";
2241 case Dumpstate::BugreportMode::BUGREPORT_REMOTE:
2242 return "BUGREPORT_REMOTE";
2243 case Dumpstate::BugreportMode::BUGREPORT_WEAR:
2244 return "BUGREPORT_WEAR";
2245 case Dumpstate::BugreportMode::BUGREPORT_TELEPHONY:
2246 return "BUGREPORT_TELEPHONY";
2247 case Dumpstate::BugreportMode::BUGREPORT_WIFI:
2248 return "BUGREPORT_WIFI";
Abhijeet Kaur904e0e02018-12-05 14:03:01 +00002249 case Dumpstate::BugreportMode::BUGREPORT_DEFAULT:
2250 return "BUGREPORT_DEFAULT";
Nandana Dutt58d72e22018-11-16 10:30:48 +00002251 }
2252}
2253
Paul Changf59c2b72020-03-10 02:08:55 +08002254static void SetOptionsFromMode(Dumpstate::BugreportMode mode, Dumpstate::DumpOptions* options,
2255 bool is_screenshot_requested) {
Paul Chang0d2aad72020-02-13 20:04:03 +08002256 // Modify com.android.shell.BugreportProgressService#isDefaultScreenshotRequired as well for
2257 // default system screenshots.
Abhijeet Kaure370d682019-10-01 16:49:30 +01002258 options->bugreport_mode = ModeToString(mode);
Nandana Dutt58d72e22018-11-16 10:30:48 +00002259 switch (mode) {
2260 case Dumpstate::BugreportMode::BUGREPORT_FULL:
Paul Changf59c2b72020-03-10 02:08:55 +08002261 options->do_screenshot = is_screenshot_requested;
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002262 options->dumpstate_hal_mode = DumpstateMode::FULL;
Nandana Dutt58d72e22018-11-16 10:30:48 +00002263 break;
2264 case Dumpstate::BugreportMode::BUGREPORT_INTERACTIVE:
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002265 // Currently, the dumpstate binder is only used by Shell to update progress.
2266 options->do_start_service = true;
2267 options->do_progress_updates = true;
Paul Changf59c2b72020-03-10 02:08:55 +08002268 options->do_screenshot = is_screenshot_requested;
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002269 options->dumpstate_hal_mode = DumpstateMode::INTERACTIVE;
Nandana Dutt58d72e22018-11-16 10:30:48 +00002270 break;
2271 case Dumpstate::BugreportMode::BUGREPORT_REMOTE:
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002272 options->do_vibrate = false;
2273 options->is_remote_mode = true;
Paul Chang0d2aad72020-02-13 20:04:03 +08002274 options->do_screenshot = false;
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002275 options->dumpstate_hal_mode = DumpstateMode::REMOTE;
Nandana Dutt58d72e22018-11-16 10:30:48 +00002276 break;
2277 case Dumpstate::BugreportMode::BUGREPORT_WEAR:
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002278 options->do_start_service = true;
2279 options->do_progress_updates = true;
2280 options->do_zip_file = true;
Paul Changf59c2b72020-03-10 02:08:55 +08002281 options->do_screenshot = is_screenshot_requested;
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002282 options->dumpstate_hal_mode = DumpstateMode::WEAR;
Nandana Dutt58d72e22018-11-16 10:30:48 +00002283 break;
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002284 // TODO(b/148168577) rename TELEPHONY everywhere to CONNECTIVITY.
Nandana Dutt58d72e22018-11-16 10:30:48 +00002285 case Dumpstate::BugreportMode::BUGREPORT_TELEPHONY:
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002286 options->telephony_only = true;
Hunter Knepshield820f9bc2020-02-05 20:10:53 -08002287 options->do_progress_updates = true;
Paul Chang0d2aad72020-02-13 20:04:03 +08002288 options->do_screenshot = false;
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002289 options->dumpstate_hal_mode = DumpstateMode::CONNECTIVITY;
Nandana Dutt58d72e22018-11-16 10:30:48 +00002290 break;
2291 case Dumpstate::BugreportMode::BUGREPORT_WIFI:
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002292 options->wifi_only = true;
2293 options->do_zip_file = true;
Paul Chang0d2aad72020-02-13 20:04:03 +08002294 options->do_screenshot = false;
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002295 options->dumpstate_hal_mode = DumpstateMode::WIFI;
Nandana Dutt58d72e22018-11-16 10:30:48 +00002296 break;
Abhijeet Kaur904e0e02018-12-05 14:03:01 +00002297 case Dumpstate::BugreportMode::BUGREPORT_DEFAULT:
2298 break;
Nandana Dutt58d72e22018-11-16 10:30:48 +00002299 }
2300}
2301
Nandana Dutt58d72e22018-11-16 10:30:48 +00002302static void LogDumpOptions(const Dumpstate::DumpOptions& options) {
Nandana Dutt235c6672019-11-14 15:22:32 +00002303 MYLOGI(
Paul Chang0d2aad72020-02-13 20:04:03 +08002304 "do_zip_file: %d do_vibrate: %d use_socket: %d use_control_socket: %d do_screenshot: %d "
Nandana Dutt235c6672019-11-14 15:22:32 +00002305 "is_remote_mode: %d show_header_only: %d do_start_service: %d telephony_only: %d "
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002306 "wifi_only: %d do_progress_updates: %d fd: %d bugreport_mode: %s dumpstate_hal_mode: %s "
2307 "args: %s\n",
Nandana Dutt235c6672019-11-14 15:22:32 +00002308 options.do_zip_file, options.do_vibrate, options.use_socket, options.use_control_socket,
Paul Chang0d2aad72020-02-13 20:04:03 +08002309 options.do_screenshot, options.is_remote_mode, options.show_header_only,
2310 options.do_start_service,
Nandana Dutt235c6672019-11-14 15:22:32 +00002311 options.telephony_only, options.wifi_only, options.do_progress_updates,
Hunter Knepshield8540faf2020-02-04 19:47:20 -08002312 options.bugreport_fd.get(), options.bugreport_mode.c_str(),
2313 toString(options.dumpstate_hal_mode).c_str(), options.args.c_str());
Nandana Dutt58d72e22018-11-16 10:30:48 +00002314}
2315
Nandana Dutt54dbd672019-01-11 12:58:05 +00002316void Dumpstate::DumpOptions::Initialize(BugreportMode bugreport_mode,
2317 const android::base::unique_fd& bugreport_fd_in,
Paul Changf59c2b72020-03-10 02:08:55 +08002318 const android::base::unique_fd& screenshot_fd_in,
2319 bool is_screenshot_requested) {
Nandana Dutt58d72e22018-11-16 10:30:48 +00002320 // In the new API world, date is always added; output is always a zip file.
2321 // TODO(111441001): remove these options once they are obsolete.
2322 do_add_date = true;
2323 do_zip_file = true;
2324
Nandana Dutt54dbd672019-01-11 12:58:05 +00002325 // Duplicate the fds because the passed in fds don't outlive the binder transaction.
2326 bugreport_fd.reset(dup(bugreport_fd_in.get()));
2327 screenshot_fd.reset(dup(screenshot_fd_in.get()));
Nandana Dutt58d72e22018-11-16 10:30:48 +00002328
Paul Changf59c2b72020-03-10 02:08:55 +08002329 SetOptionsFromMode(bugreport_mode, this, is_screenshot_requested);
Nandana Dutt58d72e22018-11-16 10:30:48 +00002330}
2331
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002332Dumpstate::RunStatus Dumpstate::DumpOptions::Initialize(int argc, char* argv[]) {
2333 RunStatus status = RunStatus::OK;
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002334 int c;
Nandana Dutt235864b2019-01-22 12:10:16 +00002335 while ((c = getopt(argc, argv, "dho:svqzpPBRSV:w")) != -1) {
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002336 switch (c) {
2337 // clang-format off
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002338 case 'd': do_add_date = true; break;
2339 case 'z': do_zip_file = true; break;
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002340 case 's': use_socket = true; break;
2341 case 'S': use_control_socket = true; break;
2342 case 'v': show_header_only = true; break;
2343 case 'q': do_vibrate = false; break;
Paul Chang0d2aad72020-02-13 20:04:03 +08002344 case 'p': do_screenshot = true; break;
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002345 case 'P': do_progress_updates = true; break;
2346 case 'R': is_remote_mode = true; break;
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002347 case 'V': break; // compatibility no-op
Nandana Dutt235864b2019-01-22 12:10:16 +00002348 case 'w':
2349 // This was already processed
2350 break;
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002351 case 'h':
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002352 status = RunStatus::HELP;
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002353 break;
2354 default:
2355 fprintf(stderr, "Invalid option: %c\n", c);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002356 status = RunStatus::INVALID_INPUT;
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002357 break;
2358 // clang-format on
2359 }
2360 }
Felipe Leme8fecfdd2016-02-09 10:40:07 -08002361
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002362 for (int i = 0; i < argc; i++) {
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002363 args += argv[i];
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002364 if (i < argc - 1) {
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002365 args += " ";
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002366 }
2367 }
2368
2369 // Reset next index used by getopt so this can be called multiple times, for eg, in tests.
2370 optind = 1;
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002371
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002372 return status;
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002373}
2374
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002375bool Dumpstate::DumpOptions::ValidateOptions() const {
Nandana Dutt54dbd672019-01-11 12:58:05 +00002376 if (bugreport_fd.get() != -1 && !do_zip_file) {
Nandana Dutt979388e2018-11-30 16:48:55 +00002377 return false;
2378 }
2379
Abhijeet Kaure370d682019-10-01 16:49:30 +01002380 if ((do_zip_file || do_add_date || do_progress_updates) && !OutputToFile()) {
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002381 return false;
2382 }
2383
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002384 if (use_control_socket && !do_zip_file) {
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002385 return false;
2386 }
2387
Abhijeet Kaure370d682019-10-01 16:49:30 +01002388 if (is_remote_mode && (do_progress_updates || !do_zip_file || !do_add_date)) {
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002389 return false;
2390 }
2391 return true;
2392}
2393
Nandana Dutt197661d2018-11-16 16:40:21 +00002394void Dumpstate::SetOptions(std::unique_ptr<DumpOptions> options) {
2395 options_ = std::move(options);
2396}
2397
Abhijeet Kaura407fb82020-03-27 12:51:12 +00002398void Dumpstate::Initialize() {
2399 /* gets the sequential id */
2400 uint32_t last_id = android::base::GetIntProperty(PROPERTY_LAST_ID, 0);
2401 id_ = ++last_id;
2402 android::base::SetProperty(PROPERTY_LAST_ID, std::to_string(last_id));
2403}
2404
Nandana Duttd2f5f082019-01-18 17:13:52 +00002405Dumpstate::RunStatus Dumpstate::Run(int32_t calling_uid, const std::string& calling_package) {
2406 Dumpstate::RunStatus status = RunInternal(calling_uid, calling_package);
Nandana Duttbabf6c72019-01-15 14:11:12 +00002407 if (listener_ != nullptr) {
2408 switch (status) {
2409 case Dumpstate::RunStatus::OK:
Nandana Duttcc4ead82019-01-23 08:29:23 +00002410 listener_->onFinished();
Nandana Duttbabf6c72019-01-15 14:11:12 +00002411 break;
2412 case Dumpstate::RunStatus::HELP:
2413 break;
2414 case Dumpstate::RunStatus::INVALID_INPUT:
Nandana Duttd2f5f082019-01-18 17:13:52 +00002415 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_INVALID_INPUT);
Nandana Duttbabf6c72019-01-15 14:11:12 +00002416 break;
2417 case Dumpstate::RunStatus::ERROR:
Nandana Duttd2f5f082019-01-18 17:13:52 +00002418 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_RUNTIME_ERROR);
2419 break;
2420 case Dumpstate::RunStatus::USER_CONSENT_DENIED:
2421 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_USER_DENIED_CONSENT);
2422 break;
2423 case Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT:
2424 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT);
Nandana Duttbabf6c72019-01-15 14:11:12 +00002425 break;
2426 }
2427 }
2428 return status;
2429}
2430
Nandana Dutt8ae16e62020-03-27 10:20:22 +00002431void Dumpstate::Cancel() {
2432 CleanupTmpFiles();
2433 android::os::UnlinkAndLogOnError(log_path_);
2434 for (int i = 0; i < NUM_OF_DUMPS; i++) {
2435 android::os::UnlinkAndLogOnError(ds.bugreport_internal_dir_ + "/" +
2436 kDumpstateBoardFiles[i]);
2437 }
2438 tombstone_data_.clear();
2439 anr_data_.clear();
2440}
2441
Nandana Dutt979388e2018-11-30 16:48:55 +00002442/*
2443 * Dumps relevant information to a bugreport based on the given options.
2444 *
2445 * The bugreport can be dumped to a file or streamed to a socket.
2446 *
2447 * How dumping to file works:
2448 * stdout is redirected to a temporary file. This will later become the main bugreport entry.
2449 * stderr is redirected a log file.
2450 *
2451 * The temporary bugreport is then populated via printfs, dumping contents of files and
2452 * output of commands to stdout.
2453 *
2454 * If zipping, the temporary bugreport file is added to the zip archive. Else it's renamed to final
2455 * text file.
2456 *
2457 * If zipping, a bunch of other files and dumps also get added to the zip archive. The log file also
2458 * gets added to the archive.
2459 *
Nandana Dutt9a76d202019-01-21 15:56:48 +00002460 * Bugreports are first generated in a local directory and later copied to the caller's fd if
2461 * supplied.
Nandana Dutt979388e2018-11-30 16:48:55 +00002462 */
Nandana Duttd2f5f082019-01-18 17:13:52 +00002463Dumpstate::RunStatus Dumpstate::RunInternal(int32_t calling_uid,
2464 const std::string& calling_package) {
Nandana Dutt979388e2018-11-30 16:48:55 +00002465 LogDumpOptions(*options_);
Nandana Dutt197661d2018-11-16 16:40:21 +00002466 if (!options_->ValidateOptions()) {
Nandana Dutt58d72e22018-11-16 10:30:48 +00002467 MYLOGE("Invalid options specified\n");
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002468 return RunStatus::INVALID_INPUT;
2469 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002470 /* set as high priority, and protect from OOM killer */
2471 setpriority(PRIO_PROCESS, 0, -20);
Wei Wang9c1f9bb2016-06-28 14:32:35 -07002472
Felipe Lemed071c682016-10-20 16:48:00 -07002473 FILE* oom_adj = fopen("/proc/self/oom_score_adj", "we");
Colin Crossf45fa6b2012-03-26 12:38:26 -07002474 if (oom_adj) {
Wei Wang9c1f9bb2016-06-28 14:32:35 -07002475 fputs("-1000", oom_adj);
Colin Crossf45fa6b2012-03-26 12:38:26 -07002476 fclose(oom_adj);
Wei Wang9c1f9bb2016-06-28 14:32:35 -07002477 } else {
2478 /* fallback to kernels <= 2.6.35 */
2479 oom_adj = fopen("/proc/self/oom_adj", "we");
2480 if (oom_adj) {
2481 fputs("-17", oom_adj);
2482 fclose(oom_adj);
2483 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002484 }
2485
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002486 if (version_ == VERSION_DEFAULT) {
2487 version_ = VERSION_CURRENT;
Michal Karpinski4db754f2015-12-11 18:04:32 +00002488 }
2489
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002490 if (version_ != VERSION_CURRENT && version_ != VERSION_SPLIT_ANR) {
Vishnu Nair64afc022018-02-01 15:29:34 -08002491 MYLOGE("invalid version requested ('%s'); suppported values are: ('%s', '%s', '%s')\n",
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002492 version_.c_str(), VERSION_DEFAULT.c_str(), VERSION_CURRENT.c_str(),
Vishnu Nair64afc022018-02-01 15:29:34 -08002493 VERSION_SPLIT_ANR.c_str());
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002494 return RunStatus::INVALID_INPUT;
Felipe Lemed071c682016-10-20 16:48:00 -07002495 }
2496
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002497 if (options_->show_header_only) {
2498 PrintHeader();
2499 return RunStatus::OK;
Felipe Lemed071c682016-10-20 16:48:00 -07002500 }
2501
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002502 MYLOGD("dumpstate calling_uid = %d ; calling package = %s \n",
2503 calling_uid, calling_package.c_str());
Nandana Duttd2f5f082019-01-18 17:13:52 +00002504
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002505 // Redirect output if needed
Nandana Dutt9a76d202019-01-21 15:56:48 +00002506 bool is_redirecting = options_->OutputToFile();
Felipe Leme7447d7c2016-11-03 18:12:22 -07002507
2508 // TODO: temporarily set progress until it's part of the Dumpstate constructor
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002509 std::string stats_path =
Nandana Dutt979388e2018-11-30 16:48:55 +00002510 is_redirecting
2511 ? android::base::StringPrintf("%s/dumpstate-stats.txt", bugreport_internal_dir_.c_str())
2512 : "";
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002513 progress_.reset(new Progress(stats_path));
Felipe Leme7447d7c2016-11-03 18:12:22 -07002514
Sahana Raof35ed432019-07-12 10:47:52 +01002515 if (acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME) < 0) {
2516 MYLOGE("Failed to acquire wake lock: %s\n", strerror(errno));
2517 } else {
2518 // Wake lock will be released automatically on process death
2519 MYLOGD("Wake lock acquired.\n");
2520 }
2521
Felipe Leme6ae5c4f2017-01-10 14:13:22 -08002522 register_sig_handler();
Felipe Lemed071c682016-10-20 16:48:00 -07002523
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002524 // TODO(b/111441001): maybe skip if already started?
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002525 if (options_->do_start_service) {
Felipe Leme75876a22016-10-27 16:31:27 -07002526 MYLOGI("Starting 'dumpstate' service\n");
2527 android::status_t ret;
2528 if ((ret = android::os::DumpstateService::Start()) != android::OK) {
2529 MYLOGE("Unable to start DumpstateService: %d\n", ret);
2530 }
2531 }
2532
Felipe Lemef0292972016-11-22 13:57:05 -08002533 if (PropertiesHelper::IsDryRun()) {
Felipe Lemed071c682016-10-20 16:48:00 -07002534 MYLOGI("Running on dry-run mode (to disable it, call 'setprop dumpstate.dry_run false')\n");
2535 }
2536
Nandana Dutt235c6672019-11-14 15:22:32 +00002537 MYLOGI("dumpstate info: id=%d, args='%s', bugreport_mode= %s bugreport format version: %s\n",
2538 id_, options_->args.c_str(), options_->bugreport_mode.c_str(), version_.c_str());
Felipe Leme809d74e2016-02-02 12:57:00 -08002539
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002540 do_early_screenshot_ = options_->do_progress_updates;
Felipe Lemee338bf62015-12-07 14:03:50 -08002541
Christopher Ferrised9354f2014-10-01 17:35:01 -07002542 // If we are going to use a socket, do it as early as possible
2543 // to avoid timeouts from bugreport.
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002544 if (options_->use_socket) {
Nandana Dutta344cb62019-02-22 15:12:35 +00002545 if (!redirect_to_socket(stdout, "dumpstate")) {
2546 return ERROR;
2547 }
Christopher Ferrised9354f2014-10-01 17:35:01 -07002548 }
2549
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002550 if (options_->use_control_socket) {
Felipe Leme2628e9e2016-04-12 16:36:51 -07002551 MYLOGD("Opening control socket\n");
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002552 control_socket_fd_ = open_socket("dumpstate");
Nandana Dutta344cb62019-02-22 15:12:35 +00002553 if (control_socket_fd_ == -1) {
2554 return ERROR;
2555 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002556 options_->do_progress_updates = 1;
Felipe Leme2628e9e2016-04-12 16:36:51 -07002557 }
2558
Felipe Leme71bbfc52015-11-23 14:14:51 -08002559 if (is_redirecting) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002560 PrepareToWriteToFile();
Felipe Leme1e9edc62015-12-21 16:02:13 -08002561
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002562 if (options_->do_progress_updates) {
Abhijeet Kaure370d682019-10-01 16:49:30 +01002563 // clang-format off
2564 std::vector<std::string> am_args = {
2565 "--receiver-permission", "android.permission.DUMP",
2566 };
2567 // clang-format on
2568 // Send STARTED broadcast for apps that listen to bugreport generation events
2569 SendBroadcast("com.android.internal.intent.action.BUGREPORT_STARTED", am_args);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002570 if (options_->use_control_socket) {
2571 dprintf(control_socket_fd_, "BEGIN:%s\n", path_.c_str());
Felipe Lemeaabfcae2016-07-29 09:49:04 -07002572 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08002573 }
2574 }
2575
Nick Kralevichf3599b32016-01-25 15:05:16 -08002576 /* read /proc/cmdline before dropping root */
2577 FILE *cmdline = fopen("/proc/cmdline", "re");
2578 if (cmdline) {
2579 fgets(cmdline_buf, sizeof(cmdline_buf), cmdline);
2580 fclose(cmdline);
2581 }
2582
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002583 if (options_->do_vibrate) {
Felipe Leme35b8cf12017-02-10 15:47:29 -08002584 Vibrate(150);
John Michelau1f794c42012-09-17 11:20:19 -05002585 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002586
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002587 if (options_->do_zip_file && zip_file != nullptr) {
2588 if (chown(path_.c_str(), AID_SHELL, AID_SHELL)) {
2589 MYLOGE("Unable to change ownership of zip file %s: %s\n", path_.c_str(),
Felipe Leme1d486fe2016-10-14 18:06:47 -07002590 strerror(errno));
Felipe Leme1e9edc62015-12-21 16:02:13 -08002591 }
2592 }
2593
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002594 int dup_stdout_fd;
2595 int dup_stderr_fd;
Felipe Leme71bbfc52015-11-23 14:14:51 -08002596 if (is_redirecting) {
Nandana Dutt979388e2018-11-30 16:48:55 +00002597 // Redirect stderr to log_path_ for debugging.
Vishnu Nair20cf5032018-01-05 13:15:49 -08002598 TEMP_FAILURE_RETRY(dup_stderr_fd = dup(fileno(stderr)));
Nandana Dutta344cb62019-02-22 15:12:35 +00002599 if (!redirect_to_file(stderr, const_cast<char*>(log_path_.c_str()))) {
2600 return ERROR;
2601 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002602 if (chown(log_path_.c_str(), AID_SHELL, AID_SHELL)) {
2603 MYLOGE("Unable to change ownership of dumpstate log file %s: %s\n", log_path_.c_str(),
2604 strerror(errno));
Felipe Leme6fe9db62016-02-12 09:04:16 -08002605 }
Nandana Dutt979388e2018-11-30 16:48:55 +00002606
2607 // Redirect stdout to tmp_path_. This is the main bugreport entry and will be
2608 // moved into zip file later, if zipping.
Vishnu Nair20cf5032018-01-05 13:15:49 -08002609 TEMP_FAILURE_RETRY(dup_stdout_fd = dup(fileno(stdout)));
Nandana Dutt979388e2018-11-30 16:48:55 +00002610 // TODO: why not write to a file instead of stdout to overcome this problem?
Felipe Leme6e01fa62015-11-11 19:35:14 -08002611 /* TODO: rather than generating a text file now and zipping it later,
2612 it would be more efficient to redirect stdout to the zip entry
2613 directly, but the libziparchive doesn't support that option yet. */
Nandana Dutta344cb62019-02-22 15:12:35 +00002614 if (!redirect_to_file(stdout, const_cast<char*>(tmp_path_.c_str()))) {
2615 return ERROR;
2616 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002617 if (chown(tmp_path_.c_str(), AID_SHELL, AID_SHELL)) {
Felipe Leme6fe9db62016-02-12 09:04:16 -08002618 MYLOGE("Unable to change ownership of temporary bugreport file %s: %s\n",
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002619 tmp_path_.c_str(), strerror(errno));
Felipe Leme6fe9db62016-02-12 09:04:16 -08002620 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002621 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08002622
2623 // Don't buffer stdout
2624 setvbuf(stdout, nullptr, _IONBF, 0);
2625
Felipe Leme608385d2016-02-01 10:35:38 -08002626 // NOTE: there should be no stdout output until now, otherwise it would break the header.
2627 // In particular, DurationReport objects should be created passing 'title, NULL', so their
Felipe Lemecbce55d2016-02-08 09:53:18 -08002628 // duration is logged into MYLOG instead.
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002629 PrintHeader();
Colin Crossf45fa6b2012-03-26 12:38:26 -07002630
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002631 if (options_->telephony_only) {
Paul Chang0d2aad72020-02-13 20:04:03 +08002632 MaybeTakeEarlyScreenshot();
Jichao Lie89d9c12019-11-21 19:02:51 -08002633 MaybeCheckUserConsent(calling_uid, calling_package);
Hunter Knepshield0cc6c212020-01-07 16:57:10 -08002634 DumpstateTelephonyOnly(calling_package);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002635 DumpstateBoard();
2636 } else if (options_->wifi_only) {
Paul Chang0d2aad72020-02-13 20:04:03 +08002637 MaybeTakeEarlyScreenshot();
Jichao Lie89d9c12019-11-21 19:02:51 -08002638 MaybeCheckUserConsent(calling_uid, calling_package);
mukesh agrawal253dad42018-01-23 21:59:59 -08002639 DumpstateWifiOnly();
Felipe Leme6ec6ac42017-01-10 15:29:53 -08002640 } else {
Paul Chang0d2aad72020-02-13 20:04:03 +08002641 // Invoke critical dumpsys first to preserve system state, before doing anything else.
Jichao Lie89d9c12019-11-21 19:02:51 -08002642 RunDumpsysCritical();
2643
Paul Chang0d2aad72020-02-13 20:04:03 +08002644 // Take screenshot and get consent only after critical dumpsys has finished.
2645 MaybeTakeEarlyScreenshot();
Jichao Lie89d9c12019-11-21 19:02:51 -08002646 MaybeCheckUserConsent(calling_uid, calling_package);
2647
Nandana Dutt4be45d12018-09-26 15:04:23 +01002648 // Dump state for the default case. This also drops root.
Jichao Lie89d9c12019-11-21 19:02:51 -08002649 RunStatus s = DumpstateDefaultAfterCritical();
Nandana Dutt5c390032019-03-12 10:52:56 +00002650 if (s != RunStatus::OK) {
Nandana Duttaac6f582019-07-26 14:32:47 +01002651 if (s == RunStatus::USER_CONSENT_DENIED) {
Nandana Dutt5c390032019-03-12 10:52:56 +00002652 HandleUserConsentDenied();
2653 }
2654 return s;
Felipe Leme6ec6ac42017-01-10 15:29:53 -08002655 }
Zhengyin Qian068ecc72016-08-10 16:48:14 -07002656 }
Felipe Leme71a74ac2016-03-17 15:43:25 -07002657
Felipe Leme55b42a62015-11-10 17:39:08 -08002658 /* close output if needed */
Felipe Leme71bbfc52015-11-23 14:14:51 -08002659 if (is_redirecting) {
Vishnu Nair20cf5032018-01-05 13:15:49 -08002660 TEMP_FAILURE_RETRY(dup2(dup_stdout_fd, fileno(stdout)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07002661 }
2662
Abhijeet Kaure370d682019-10-01 16:49:30 +01002663 // Zip the (now complete) .tmp file within the internal directory.
Nandana Dutt9a76d202019-01-21 15:56:48 +00002664 if (options_->OutputToFile()) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002665 FinalizeFile();
Colin Crossf45fa6b2012-03-26 12:38:26 -07002666 }
2667
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002668 // Share the final file with the caller if the user has consented or Shell is the caller.
Nandana Duttd2f5f082019-01-18 17:13:52 +00002669 Dumpstate::RunStatus status = Dumpstate::RunStatus::OK;
Abhijeet Kaure370d682019-10-01 16:49:30 +01002670 if (CalledByApi()) {
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002671 status = CopyBugreportIfUserConsented(calling_uid);
Nandana Duttd2f5f082019-01-18 17:13:52 +00002672 if (status != Dumpstate::RunStatus::OK &&
2673 status != Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT) {
2674 // Do an early return if there were errors. We make an exception for consent
2675 // timing out because it's possible the user got distracted. In this case the
2676 // bugreport is not shared but made available for manual retrieval.
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002677 MYLOGI("User denied consent. Returning\n");
Nandana Duttd2f5f082019-01-18 17:13:52 +00002678 return status;
2679 }
Paul Chang0d2aad72020-02-13 20:04:03 +08002680 if (options_->do_screenshot &&
2681 options_->screenshot_fd.get() != -1 &&
2682 !options_->is_screenshot_copied) {
Nandana Dutte78c3d72019-01-29 16:10:45 +00002683 bool copy_succeeded = android::os::CopyFileToFd(screenshot_path_,
2684 options_->screenshot_fd.get());
2685 if (copy_succeeded) {
2686 android::os::UnlinkAndLogOnError(screenshot_path_);
2687 }
2688 }
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002689 if (status == Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT) {
2690 MYLOGI(
2691 "Did not receive user consent yet."
2692 " Will not copy the bugreport artifacts to caller.\n");
Abhijeet Kaur57627412019-04-17 16:00:09 +01002693 const String16 incidentcompanion("incidentcompanion");
2694 sp<android::IBinder> ics(defaultServiceManager()->getService(incidentcompanion));
2695 if (ics != nullptr) {
2696 MYLOGD("Canceling user consent request via incidentcompanion service\n");
2697 android::interface_cast<android::os::IIncidentCompanion>(ics)->cancelAuthorization(
2698 consent_callback_.get());
2699 } else {
2700 MYLOGD("Unable to cancel user consent; incidentcompanion service unavailable\n");
2701 }
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002702 }
Nandana Duttd2f5f082019-01-18 17:13:52 +00002703 }
2704
Felipe Lemecc2a2fa2016-02-25 14:02:44 -08002705 /* vibrate a few but shortly times to let user know it's finished */
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002706 if (options_->do_vibrate) {
Takuya Ogawa47f644e2017-12-20 18:09:09 +09002707 for (int i = 0; i < 3; i++) {
2708 Vibrate(75);
2709 usleep((75 + 50) * 1000);
2710 }
Felipe Lemecc2a2fa2016-02-25 14:02:44 -08002711 }
2712
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002713 MYLOGD("Final progress: %d/%d (estimated %d)\n", progress_->Get(), progress_->GetMax(),
2714 progress_->GetInitialMax());
2715 progress_->Save();
2716 MYLOGI("done (id %d)\n", id_);
Colin Crossf45fa6b2012-03-26 12:38:26 -07002717
Felipe Leme107a05f2016-03-08 15:11:15 -08002718 if (is_redirecting) {
Vishnu Nair20cf5032018-01-05 13:15:49 -08002719 TEMP_FAILURE_RETRY(dup2(dup_stderr_fd, fileno(stderr)));
Felipe Leme107a05f2016-03-08 15:11:15 -08002720 }
2721
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002722 if (options_->use_control_socket && control_socket_fd_ != -1) {
Felipe Lemee844a9d2016-09-21 15:01:39 -07002723 MYLOGD("Closing control socket\n");
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002724 close(control_socket_fd_);
Felipe Leme2628e9e2016-04-12 16:36:51 -07002725 }
2726
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002727 tombstone_data_.clear();
2728 anr_data_.clear();
Narayan Kamath6b9516c2017-10-27 11:15:51 +01002729
Nandana Duttd2f5f082019-01-18 17:13:52 +00002730 return (consent_callback_ != nullptr &&
2731 consent_callback_->getResult() == UserConsentResult::UNAVAILABLE)
2732 ? USER_CONSENT_TIMED_OUT
2733 : RunStatus::OK;
2734}
2735
Paul Chang0d2aad72020-02-13 20:04:03 +08002736void Dumpstate::MaybeTakeEarlyScreenshot() {
2737 if (!options_->do_screenshot || !do_early_screenshot_) {
2738 return;
2739 }
2740
2741 TakeScreenshot();
2742}
2743
Jichao Lie89d9c12019-11-21 19:02:51 -08002744void Dumpstate::MaybeCheckUserConsent(int32_t calling_uid, const std::string& calling_package) {
2745 if (calling_uid == AID_SHELL || !CalledByApi()) {
2746 // No need to get consent for shell triggered dumpstates, or not through
2747 // bugreporting API (i.e. no fd to copy back).
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002748 return;
2749 }
Nandana Duttd2f5f082019-01-18 17:13:52 +00002750 consent_callback_ = new ConsentCallback();
2751 const String16 incidentcompanion("incidentcompanion");
2752 sp<android::IBinder> ics(defaultServiceManager()->getService(incidentcompanion));
Jichao Lie89d9c12019-11-21 19:02:51 -08002753 android::String16 package(calling_package.c_str());
Nandana Duttd2f5f082019-01-18 17:13:52 +00002754 if (ics != nullptr) {
2755 MYLOGD("Checking user consent via incidentcompanion service\n");
2756 android::interface_cast<android::os::IIncidentCompanion>(ics)->authorizeReport(
Jichao Lie89d9c12019-11-21 19:02:51 -08002757 calling_uid, package, String16(), String16(),
Joe Onorato1c36d752019-03-17 18:26:43 -07002758 0x1 /* FLAG_CONFIRMATION_DIALOG */, consent_callback_.get());
Nandana Duttd2f5f082019-01-18 17:13:52 +00002759 } else {
2760 MYLOGD("Unable to check user consent; incidentcompanion service unavailable\n");
2761 }
2762}
2763
Nandana Dutt5c390032019-03-12 10:52:56 +00002764bool Dumpstate::IsUserConsentDenied() const {
2765 return ds.consent_callback_ != nullptr &&
2766 ds.consent_callback_->getResult() == UserConsentResult::DENIED;
2767}
2768
Abhijeet Kaur359b1ff2019-07-26 16:01:36 +01002769bool Dumpstate::CalledByApi() const {
2770 return ds.options_->bugreport_fd.get() != -1 ? true : false;
2771}
2772
Nandana Dutt8ae16e62020-03-27 10:20:22 +00002773void Dumpstate::CleanupTmpFiles() {
Nandana Duttd2f5f082019-01-18 17:13:52 +00002774 android::os::UnlinkAndLogOnError(tmp_path_);
2775 android::os::UnlinkAndLogOnError(screenshot_path_);
2776 android::os::UnlinkAndLogOnError(path_);
2777}
2778
2779Dumpstate::RunStatus Dumpstate::HandleUserConsentDenied() {
2780 MYLOGD("User denied consent; deleting files and returning\n");
Nandana Dutt8ae16e62020-03-27 10:20:22 +00002781 CleanupTmpFiles();
Nandana Duttd2f5f082019-01-18 17:13:52 +00002782 return USER_CONSENT_DENIED;
2783}
2784
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002785Dumpstate::RunStatus Dumpstate::CopyBugreportIfUserConsented(int32_t calling_uid) {
Nandana Duttd2f5f082019-01-18 17:13:52 +00002786 // If the caller has asked to copy the bugreport over to their directory, we need explicit
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002787 // user consent (unless the caller is Shell).
2788 UserConsentResult consent_result;
2789 if (calling_uid == AID_SHELL) {
2790 consent_result = UserConsentResult::APPROVED;
2791 } else {
2792 consent_result = consent_callback_->getResult();
2793 }
Nandana Duttd2f5f082019-01-18 17:13:52 +00002794 if (consent_result == UserConsentResult::UNAVAILABLE) {
2795 // User has not responded yet.
2796 uint64_t elapsed_ms = consent_callback_->getElapsedTimeMs();
Hunter Knepshield70610fa2020-01-03 15:27:33 -08002797 // Telephony is a fast report type, particularly on user builds where information may be
2798 // more aggressively limited. To give the user time to read the consent dialog, increase the
2799 // timeout.
2800 uint64_t timeout_ms = options_->telephony_only ? TELEPHONY_REPORT_USER_CONSENT_TIMEOUT_MS
2801 : USER_CONSENT_TIMEOUT_MS;
2802 if (elapsed_ms < timeout_ms) {
2803 uint delay_seconds = (timeout_ms - elapsed_ms) / 1000;
Nandana Duttd2f5f082019-01-18 17:13:52 +00002804 MYLOGD("Did not receive user consent yet; going to wait for %d seconds", delay_seconds);
2805 sleep(delay_seconds);
2806 }
2807 consent_result = consent_callback_->getResult();
2808 }
2809 if (consent_result == UserConsentResult::DENIED) {
2810 // User has explicitly denied sharing with the app. To be safe delete the
2811 // internal bugreport & tmp files.
2812 return HandleUserConsentDenied();
2813 }
2814 if (consent_result == UserConsentResult::APPROVED) {
Nandana Dutte78c3d72019-01-29 16:10:45 +00002815 bool copy_succeeded = android::os::CopyFileToFd(path_, options_->bugreport_fd.get());
2816 if (copy_succeeded) {
2817 android::os::UnlinkAndLogOnError(path_);
Nandana Duttd2f5f082019-01-18 17:13:52 +00002818 }
2819 return copy_succeeded ? Dumpstate::RunStatus::OK : Dumpstate::RunStatus::ERROR;
2820 } else if (consent_result == UserConsentResult::UNAVAILABLE) {
2821 // consent_result is still UNAVAILABLE. The user has likely not responded yet.
2822 // Since we do not have user consent to share the bugreport it does not get
2823 // copied over to the calling app but remains in the internal directory from
2824 // where the user can manually pull it.
2825 return Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT;
2826 }
2827 // Unknown result; must be a programming error.
2828 MYLOGE("Unknown user consent result:%d\n", consent_result);
2829 return Dumpstate::RunStatus::ERROR;
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002830}
2831
Nandana Duttf02564e2019-02-15 15:24:24 +00002832Dumpstate::RunStatus Dumpstate::ParseCommandlineAndRun(int argc, char* argv[]) {
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002833 std::unique_ptr<Dumpstate::DumpOptions> options = std::make_unique<Dumpstate::DumpOptions>();
2834 Dumpstate::RunStatus status = options->Initialize(argc, argv);
2835 if (status == Dumpstate::RunStatus::OK) {
Nandana Duttf02564e2019-02-15 15:24:24 +00002836 SetOptions(std::move(options));
Nandana Duttd2f5f082019-01-18 17:13:52 +00002837 // When directly running dumpstate binary, the output is not expected to be written
2838 // to any external file descriptor.
Nandana Duttf02564e2019-02-15 15:24:24 +00002839 assert(options_->bugreport_fd.get() == -1);
Nandana Duttd2f5f082019-01-18 17:13:52 +00002840
2841 // calling_uid and calling_package are for user consent to share the bugreport with
Abhijeet Kaura407fb82020-03-27 12:51:12 +00002842 // an app; they are irrelevant here because bugreport is triggered via command line.
2843 // Update Last ID before calling Run().
2844 Initialize();
Nandana Duttf02564e2019-02-15 15:24:24 +00002845 status = Run(-1 /* calling_uid */, "" /* calling_package */);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002846 }
Nandana Duttf02564e2019-02-15 15:24:24 +00002847 return status;
2848}
2849
2850/* Main entry point for dumpstate binary. */
2851int run_main(int argc, char* argv[]) {
2852 Dumpstate::RunStatus status = ds.ParseCommandlineAndRun(argc, argv);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002853
2854 switch (status) {
2855 case Dumpstate::RunStatus::OK:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002856 exit(0);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002857 case Dumpstate::RunStatus::HELP:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002858 ShowUsage();
2859 exit(0);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002860 case Dumpstate::RunStatus::INVALID_INPUT:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002861 fprintf(stderr, "Invalid combination of args\n");
2862 ShowUsage();
2863 exit(1);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002864 case Dumpstate::RunStatus::ERROR:
Nandana Duttd2f5f082019-01-18 17:13:52 +00002865 FALLTHROUGH_INTENDED;
2866 case Dumpstate::RunStatus::USER_CONSENT_DENIED:
2867 FALLTHROUGH_INTENDED;
2868 case Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002869 exit(2);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002870 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002871}
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002872
2873// TODO(111441001): Default DumpOptions to sensible values.
2874Dumpstate::Dumpstate(const std::string& version)
2875 : pid_(getpid()),
2876 options_(new Dumpstate::DumpOptions()),
Nandana Dutt402a8392019-06-14 14:25:13 +01002877 last_reported_percent_progress_(0),
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002878 version_(version),
2879 now_(time(nullptr)) {
2880}
2881
2882Dumpstate& Dumpstate::GetInstance() {
2883 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
2884 return singleton_;
2885}
2886
Nandana Dutt8d945c02019-08-14 13:30:07 +01002887DurationReporter::DurationReporter(const std::string& title, bool logcat_only, bool verbose)
2888 : title_(title), logcat_only_(logcat_only), verbose_(verbose) {
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002889 if (!title_.empty()) {
2890 started_ = Nanotime();
2891 }
2892}
2893
2894DurationReporter::~DurationReporter() {
2895 if (!title_.empty()) {
2896 float elapsed = (float)(Nanotime() - started_) / NANOS_PER_SEC;
chenqiwuaf8b2d92019-12-12 18:53:51 +08002897 if (elapsed >= .5f || verbose_) {
2898 MYLOGD("Duration of '%s': %.2fs\n", title_.c_str(), elapsed);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002899 }
chenqiwuaf8b2d92019-12-12 18:53:51 +08002900 if (!logcat_only_) {
2901 // Use "Yoda grammar" to make it easier to grep|sort sections.
2902 printf("------ %.3fs was the duration of '%s' ------\n", elapsed, title_.c_str());
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002903 }
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002904 }
2905}
2906
2907const int32_t Progress::kDefaultMax = 5000;
2908
2909Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
2910}
2911
2912Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
2913 : Progress(initial_max, growth_factor, "") {
2914 progress_ = progress;
2915}
2916
2917Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
2918 : initial_max_(initial_max),
2919 progress_(0),
2920 max_(initial_max),
2921 growth_factor_(growth_factor),
2922 n_runs_(0),
2923 average_max_(0),
2924 path_(path) {
2925 if (!path_.empty()) {
2926 Load();
2927 }
2928}
2929
2930void Progress::Load() {
2931 MYLOGD("Loading stats from %s\n", path_.c_str());
2932 std::string content;
2933 if (!android::base::ReadFileToString(path_, &content)) {
2934 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
2935 return;
2936 }
2937 if (content.empty()) {
2938 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
2939 return;
2940 }
2941 std::vector<std::string> lines = android::base::Split(content, "\n");
2942
2943 if (lines.size() < 1) {
2944 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
2945 (int)lines.size(), max_);
2946 return;
2947 }
2948 char* ptr;
2949 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
2950 average_max_ = strtol(ptr, nullptr, 10);
2951 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
2952 average_max_ > STATS_MAX_AVERAGE) {
2953 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
2954 initial_max_ = Progress::kDefaultMax;
2955 } else {
2956 initial_max_ = average_max_;
2957 }
2958 max_ = initial_max_;
2959
2960 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
2961}
2962
2963void Progress::Save() {
2964 int32_t total = n_runs_ * average_max_ + progress_;
2965 int32_t runs = n_runs_ + 1;
2966 int32_t average = floor(((float)total) / runs);
2967 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
2968 path_.c_str());
2969 if (path_.empty()) {
2970 return;
2971 }
2972
2973 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
2974 if (!android::base::WriteStringToFile(content, path_)) {
2975 MYLOGE("Could not save stats on %s\n", path_.c_str());
2976 }
2977}
2978
2979int32_t Progress::Get() const {
2980 return progress_;
2981}
2982
2983bool Progress::Inc(int32_t delta_sec) {
2984 bool changed = false;
2985 if (delta_sec >= 0) {
2986 progress_ += delta_sec;
2987 if (progress_ > max_) {
2988 int32_t old_max = max_;
2989 max_ = floor((float)progress_ * growth_factor_);
2990 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
2991 changed = true;
2992 }
2993 }
2994 return changed;
2995}
2996
2997int32_t Progress::GetMax() const {
2998 return max_;
2999}
3000
3001int32_t Progress::GetInitialMax() const {
3002 return initial_max_;
3003}
3004
3005void Progress::Dump(int fd, const std::string& prefix) const {
3006 const char* pr = prefix.c_str();
3007 dprintf(fd, "%sprogress: %d\n", pr, progress_);
3008 dprintf(fd, "%smax: %d\n", pr, max_);
3009 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
3010 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
3011 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
3012 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
3013 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
3014}
3015
3016bool Dumpstate::IsZipping() const {
3017 return zip_writer_ != nullptr;
3018}
3019
3020std::string Dumpstate::GetPath(const std::string& suffix) const {
3021 return GetPath(bugreport_internal_dir_, suffix);
3022}
3023
3024std::string Dumpstate::GetPath(const std::string& directory, const std::string& suffix) const {
3025 return android::base::StringPrintf("%s/%s-%s%s", directory.c_str(), base_name_.c_str(),
3026 name_.c_str(), suffix.c_str());
3027}
3028
3029void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
3030 progress_ = std::move(progress);
3031}
3032
3033void for_each_userid(void (*func)(int), const char *header) {
3034 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
3035 "for_each_userid(%s)", header);
3036 DurationReporter duration_reporter(title);
3037 if (PropertiesHelper::IsDryRun()) return;
3038
3039 DIR *d;
3040 struct dirent *de;
3041
3042 if (header) printf("\n------ %s ------\n", header);
3043 func(0);
3044
3045 if (!(d = opendir("/data/system/users"))) {
3046 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
3047 return;
3048 }
3049
3050 while ((de = readdir(d))) {
3051 int userid;
3052 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
3053 continue;
3054 }
3055 func(userid);
3056 }
3057
3058 closedir(d);
3059}
3060
3061static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
3062 DIR *d;
3063 struct dirent *de;
3064
3065 if (!(d = opendir("/proc"))) {
3066 printf("Failed to open /proc (%s)\n", strerror(errno));
3067 return;
3068 }
3069
3070 if (header) printf("\n------ %s ------\n", header);
3071 while ((de = readdir(d))) {
3072 if (ds.IsUserConsentDenied()) {
3073 MYLOGE(
3074 "Returning early because user denied consent to share bugreport with calling app.");
3075 closedir(d);
3076 return;
3077 }
3078 int pid;
3079 int fd;
3080 char cmdpath[255];
3081 char cmdline[255];
3082
3083 if (!(pid = atoi(de->d_name))) {
3084 continue;
3085 }
3086
3087 memset(cmdline, 0, sizeof(cmdline));
3088
3089 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
3090 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
3091 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
3092 close(fd);
3093 if (cmdline[0]) {
3094 helper(pid, cmdline, arg);
3095 continue;
3096 }
3097 }
3098
3099 // if no cmdline, a kernel thread has comm
3100 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
3101 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
3102 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
3103 close(fd);
3104 if (cmdline[1]) {
3105 cmdline[0] = '[';
3106 size_t len = strcspn(cmdline, "\f\b\r\n");
3107 cmdline[len] = ']';
3108 cmdline[len+1] = '\0';
3109 }
3110 }
3111 if (!cmdline[0]) {
3112 strcpy(cmdline, "N/A");
3113 }
3114 helper(pid, cmdline, arg);
3115 }
3116
3117 closedir(d);
3118}
3119
3120static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
3121 for_each_pid_func *func = (for_each_pid_func*) arg;
3122 func(pid, cmdline);
3123}
3124
3125void for_each_pid(for_each_pid_func func, const char *header) {
3126 std::string title = header == nullptr ? "for_each_pid"
3127 : android::base::StringPrintf("for_each_pid(%s)", header);
3128 DurationReporter duration_reporter(title);
3129 if (PropertiesHelper::IsDryRun()) return;
3130
3131 __for_each_pid(for_each_pid_helper, header, (void *) func);
3132}
3133
3134static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
3135 DIR *d;
3136 struct dirent *de;
3137 char taskpath[255];
3138 for_each_tid_func *func = (for_each_tid_func *) arg;
3139
3140 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
3141
3142 if (!(d = opendir(taskpath))) {
3143 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
3144 return;
3145 }
3146
3147 func(pid, pid, cmdline);
3148
3149 while ((de = readdir(d))) {
3150 if (ds.IsUserConsentDenied()) {
3151 MYLOGE(
3152 "Returning early because user denied consent to share bugreport with calling app.");
3153 closedir(d);
3154 return;
3155 }
3156 int tid;
3157 int fd;
3158 char commpath[255];
3159 char comm[255];
3160
3161 if (!(tid = atoi(de->d_name))) {
3162 continue;
3163 }
3164
3165 if (tid == pid)
3166 continue;
3167
3168 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
3169 memset(comm, 0, sizeof(comm));
3170 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
3171 strcpy(comm, "N/A");
3172 } else {
3173 char *c;
3174 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
3175 close(fd);
3176
3177 c = strrchr(comm, '\n');
3178 if (c) {
3179 *c = '\0';
3180 }
3181 }
3182 func(pid, tid, comm);
3183 }
3184
3185 closedir(d);
3186}
3187
3188void for_each_tid(for_each_tid_func func, const char *header) {
3189 std::string title = header == nullptr ? "for_each_tid"
3190 : android::base::StringPrintf("for_each_tid(%s)", header);
3191 DurationReporter duration_reporter(title);
3192
3193 if (PropertiesHelper::IsDryRun()) return;
3194
3195 __for_each_pid(for_each_tid_helper, header, (void *) func);
3196}
3197
3198void show_wchan(int pid, int tid, const char *name) {
3199 if (PropertiesHelper::IsDryRun()) return;
3200
3201 char path[255];
3202 char buffer[255];
3203 int fd, ret, save_errno;
3204 char name_buffer[255];
3205
3206 memset(buffer, 0, sizeof(buffer));
3207
3208 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
3209 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
3210 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
3211 return;
3212 }
3213
3214 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
3215 save_errno = errno;
3216 close(fd);
3217
3218 if (ret < 0) {
3219 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
3220 return;
3221 }
3222
3223 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
3224 pid == tid ? 0 : 3, "", name);
3225
3226 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
3227
3228 return;
3229}
3230
3231// print time in centiseconds
3232static void snprcent(char *buffer, size_t len, size_t spc,
3233 unsigned long long time) {
3234 static long hz; // cache discovered hz
3235
3236 if (hz <= 0) {
3237 hz = sysconf(_SC_CLK_TCK);
3238 if (hz <= 0) {
3239 hz = 1000;
3240 }
3241 }
3242
3243 // convert to centiseconds
3244 time = (time * 100 + (hz / 2)) / hz;
3245
3246 char str[16];
3247
3248 snprintf(str, sizeof(str), " %llu.%02u",
3249 time / 100, (unsigned)(time % 100));
3250 size_t offset = strlen(buffer);
3251 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
3252 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
3253}
3254
3255// print permille as a percent
3256static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
3257 char str[16];
3258
3259 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
3260 size_t offset = strlen(buffer);
3261 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
3262 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
3263}
3264
3265void show_showtime(int pid, const char *name) {
3266 if (PropertiesHelper::IsDryRun()) return;
3267
3268 char path[255];
3269 char buffer[1023];
3270 int fd, ret, save_errno;
3271
3272 memset(buffer, 0, sizeof(buffer));
3273
3274 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
3275 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
3276 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
3277 return;
3278 }
3279
3280 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
3281 save_errno = errno;
3282 close(fd);
3283
3284 if (ret < 0) {
3285 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
3286 return;
3287 }
3288
3289 // field 14 is utime
3290 // field 15 is stime
3291 // field 42 is iotime
3292 unsigned long long utime = 0, stime = 0, iotime = 0;
3293 if (sscanf(buffer,
3294 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
3295 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
3296 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
3297 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
3298 &utime, &stime, &iotime) != 3) {
3299 return;
3300 }
3301
3302 unsigned long long total = utime + stime;
3303 if (!total) {
3304 return;
3305 }
3306
3307 unsigned permille = (iotime * 1000 + (total / 2)) / total;
3308 if (permille > 1000) {
3309 permille = 1000;
3310 }
3311
3312 // try to beautify and stabilize columns at <80 characters
3313 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
3314 if ((name[0] != '[') || utime) {
3315 snprcent(buffer, sizeof(buffer), 57, utime);
3316 }
3317 snprcent(buffer, sizeof(buffer), 65, stime);
3318 if ((name[0] != '[') || iotime) {
3319 snprcent(buffer, sizeof(buffer), 73, iotime);
3320 }
3321 if (iotime) {
3322 snprdec(buffer, sizeof(buffer), 79, permille);
3323 }
3324 puts(buffer); // adds a trailing newline
3325
3326 return;
3327}
3328
3329void do_dmesg() {
3330 const char *title = "KERNEL LOG (dmesg)";
3331 DurationReporter duration_reporter(title);
3332 printf("------ %s ------\n", title);
3333
3334 if (PropertiesHelper::IsDryRun()) return;
3335
3336 /* Get size of kernel buffer */
3337 int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
3338 if (size <= 0) {
3339 printf("Unexpected klogctl return value: %d\n\n", size);
3340 return;
3341 }
3342 char *buf = (char *) malloc(size + 1);
3343 if (buf == nullptr) {
3344 printf("memory allocation failed\n\n");
3345 return;
3346 }
3347 int retval = klogctl(KLOG_READ_ALL, buf, size);
3348 if (retval < 0) {
3349 printf("klogctl failure\n\n");
3350 free(buf);
3351 return;
3352 }
3353 buf[retval] = '\0';
3354 printf("%s\n\n", buf);
3355 free(buf);
3356 return;
3357}
3358
3359void do_showmap(int pid, const char *name) {
3360 char title[255];
3361 char arg[255];
3362
3363 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
3364 snprintf(arg, sizeof(arg), "%d", pid);
3365 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
3366}
3367
3368int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
3369 DurationReporter duration_reporter(title);
3370
3371 int status = DumpFileToFd(STDOUT_FILENO, title, path);
3372
3373 UpdateProgress(WEIGHT_FILE);
3374
3375 return status;
3376}
3377
3378int read_file_as_long(const char *path, long int *output) {
3379 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
3380 if (fd < 0) {
3381 int err = errno;
3382 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
3383 return -1;
3384 }
3385 char buffer[50];
3386 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
3387 if (bytes_read == -1) {
3388 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
3389 return -2;
3390 }
3391 if (bytes_read == 0) {
3392 MYLOGE("File %s is empty\n", path);
3393 return -3;
3394 }
3395 *output = atoi(buffer);
3396 return 0;
3397}
3398
3399/* calls skip to gate calling dump_from_fd recursively
3400 * in the specified directory. dump_from_fd defaults to
3401 * dump_file_from_fd above when set to NULL. skip defaults
3402 * to false when set to NULL. dump_from_fd will always be
3403 * called with title NULL.
3404 */
3405int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
3406 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
3407 DurationReporter duration_reporter(title);
3408 DIR *dirp;
3409 struct dirent *d;
3410 char *newpath = nullptr;
3411 const char *slash = "/";
3412 int retval = 0;
3413
3414 if (!title.empty()) {
3415 printf("------ %s (%s) ------\n", title.c_str(), dir);
3416 }
3417 if (PropertiesHelper::IsDryRun()) return 0;
3418
3419 if (dir[strlen(dir) - 1] == '/') {
3420 ++slash;
3421 }
3422 dirp = opendir(dir);
3423 if (dirp == nullptr) {
3424 retval = -errno;
3425 MYLOGE("%s: %s\n", dir, strerror(errno));
3426 return retval;
3427 }
3428
3429 if (!dump_from_fd) {
3430 dump_from_fd = dump_file_from_fd;
3431 }
3432 for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
3433 if ((d->d_name[0] == '.')
3434 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
3435 || (d->d_name[1] == '\0'))) {
3436 continue;
3437 }
3438 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
3439 (d->d_type == DT_DIR) ? "/" : "");
3440 if (!newpath) {
3441 retval = -errno;
3442 continue;
3443 }
3444 if (skip && (*skip)(newpath)) {
3445 continue;
3446 }
3447 if (d->d_type == DT_DIR) {
3448 int ret = dump_files("", newpath, skip, dump_from_fd);
3449 if (ret < 0) {
3450 retval = ret;
3451 }
3452 continue;
3453 }
3454 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
3455 if (fd.get() < 0) {
3456 retval = -1;
3457 printf("*** %s: %s\n", newpath, strerror(errno));
3458 continue;
3459 }
3460 (*dump_from_fd)(nullptr, newpath, fd.get());
3461 }
3462 closedir(dirp);
3463 if (!title.empty()) {
3464 printf("\n");
3465 }
3466 return retval;
3467}
3468
3469/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
3470 * it's possible to avoid issues where opening the file itself can get
3471 * stuck.
3472 */
3473int dump_file_from_fd(const char *title, const char *path, int fd) {
3474 if (PropertiesHelper::IsDryRun()) return 0;
3475
3476 int flags = fcntl(fd, F_GETFL);
3477 if (flags == -1) {
3478 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
3479 return -1;
3480 } else if (!(flags & O_NONBLOCK)) {
3481 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
3482 return -1;
3483 }
3484 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
3485}
3486
3487int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Nandana Dutt8d945c02019-08-14 13:30:07 +01003488 const CommandOptions& options, bool verbose_duration) {
3489 DurationReporter duration_reporter(title, false /* logcat_only */, verbose_duration);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003490
3491 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
3492
3493 /* TODO: for now we're simplifying the progress calculation by using the
3494 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
3495 * where its weight should be much higher proportionally to its timeout.
3496 * Ideally, it should use a options.EstimatedDuration() instead...*/
3497 UpdateProgress(options.Timeout());
3498
3499 return status;
3500}
3501
3502void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
3503 const CommandOptions& options, long dumpsysTimeoutMs) {
3504 long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
3505 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
3506 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
3507 RunCommand(title, dumpsys, options);
3508}
3509
3510int open_socket(const char *service) {
3511 int s = android_get_control_socket(service);
3512 if (s < 0) {
3513 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
3514 return -1;
3515 }
3516 fcntl(s, F_SETFD, FD_CLOEXEC);
3517
3518 // Set backlog to 0 to make sure that queue size will be minimum.
3519 // In Linux, because the minimum queue will be 1, connect() will be blocked
3520 // if the other clients already called connect() and the connection request was not accepted.
3521 if (listen(s, 0) < 0) {
3522 MYLOGE("listen(control socket): %s\n", strerror(errno));
3523 return -1;
3524 }
3525
3526 struct sockaddr addr;
3527 socklen_t alen = sizeof(addr);
Abhijeet Kaur2113cae2019-09-13 09:24:15 +01003528 int fd = accept4(s, &addr, &alen, SOCK_CLOEXEC);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003529
3530 // Close socket just after accept(), to make sure that connect() by client will get error
3531 // when the socket is used by the other services.
3532 // There is still a race condition possibility between accept and close, but there is no way
3533 // to close-on-accept atomically.
3534 // See detail; b/123306389#comment25
3535 close(s);
3536
3537 if (fd < 0) {
3538 MYLOGE("accept(control socket): %s\n", strerror(errno));
3539 return -1;
3540 }
3541
3542 return fd;
3543}
3544
3545/* redirect output to a service control socket */
3546bool redirect_to_socket(FILE* redirect, const char* service) {
3547 int fd = open_socket(service);
3548 if (fd == -1) {
3549 return false;
3550 }
3551 fflush(redirect);
3552 // TODO: handle dup2 failure
3553 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
3554 close(fd);
3555 return true;
3556}
3557
3558// TODO: should call is_valid_output_file and/or be merged into it.
3559void create_parent_dirs(const char *path) {
3560 char *chp = const_cast<char *> (path);
3561
3562 /* skip initial slash */
3563 if (chp[0] == '/')
3564 chp++;
3565
3566 /* create leading directories, if necessary */
3567 struct stat dir_stat;
3568 while (chp && chp[0]) {
3569 chp = strchr(chp, '/');
3570 if (chp) {
3571 *chp = 0;
3572 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
3573 MYLOGI("Creating directory %s\n", path);
3574 if (mkdir(path, 0770)) { /* drwxrwx--- */
3575 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
3576 } else if (chown(path, AID_SHELL, AID_SHELL)) {
3577 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
3578 }
3579 }
3580 *chp++ = '/';
3581 }
3582 }
3583}
3584
3585bool _redirect_to_file(FILE* redirect, char* path, int truncate_flag) {
3586 create_parent_dirs(path);
3587
3588 int fd = TEMP_FAILURE_RETRY(open(path,
3589 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
3590 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
3591 if (fd < 0) {
3592 MYLOGE("%s: %s\n", path, strerror(errno));
3593 return false;
3594 }
3595
3596 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
3597 close(fd);
3598 return true;
3599}
3600
3601bool redirect_to_file(FILE* redirect, char* path) {
3602 return _redirect_to_file(redirect, path, O_TRUNC);
3603}
3604
3605bool redirect_to_existing_file(FILE* redirect, char* path) {
3606 return _redirect_to_file(redirect, path, O_APPEND);
3607}
3608
3609void dump_route_tables() {
3610 DurationReporter duration_reporter("DUMP ROUTE TABLES");
3611 if (PropertiesHelper::IsDryRun()) return;
3612 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
3613 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
3614 FILE* fp = fopen(RT_TABLES_PATH, "re");
3615 if (!fp) {
3616 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
3617 return;
3618 }
3619 char table[16];
3620 // Each line has an integer (the table number), a space, and a string (the table name). We only
3621 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
3622 // Add a fixed max limit so this doesn't go awry.
3623 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
3624 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
3625 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
3626 }
3627 fclose(fp);
3628}
3629
3630// TODO: make this function thread safe if sections are generated in parallel.
3631void Dumpstate::UpdateProgress(int32_t delta_sec) {
3632 if (progress_ == nullptr) {
3633 MYLOGE("UpdateProgress: progress_ not set\n");
3634 return;
3635 }
3636
3637 // Always update progess so stats can be tuned...
Nandana Dutt402a8392019-06-14 14:25:13 +01003638 progress_->Inc(delta_sec);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003639
3640 // ...but only notifiy listeners when necessary.
3641 if (!options_->do_progress_updates) return;
3642
3643 int progress = progress_->Get();
3644 int max = progress_->GetMax();
Nandana Dutt402a8392019-06-14 14:25:13 +01003645 int percent = 100 * progress / max;
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003646
Nandana Dutt402a8392019-06-14 14:25:13 +01003647 if (last_reported_percent_progress_ > 0 && percent <= last_reported_percent_progress_) {
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003648 return;
3649 }
Nandana Dutt402a8392019-06-14 14:25:13 +01003650 last_reported_percent_progress_ = percent;
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003651
3652 if (control_socket_fd_ >= 0) {
3653 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
3654 fsync(control_socket_fd_);
3655 }
3656
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003657 if (listener_ != nullptr) {
Nandana Dutt235c6672019-11-14 15:22:32 +00003658 if (percent % 10 == 0) {
3659 // We don't want to spam logcat, so only log multiples of 10.
Abhijeet Kaured5d6a62019-10-07 15:02:05 +01003660 MYLOGD("Setting progress: %d/%d (%d%%)\n", progress, max, percent);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003661 } else {
3662 // stderr is ignored on normal invocations, but useful when calling
3663 // /system/bin/dumpstate directly for debuggging.
Abhijeet Kaured5d6a62019-10-07 15:02:05 +01003664 fprintf(stderr, "Setting progress: %d/%d (%d%%)\n", progress, max, percent);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003665 }
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003666
3667 listener_->onProgress(percent);
3668 }
3669}
3670
3671void Dumpstate::TakeScreenshot(const std::string& path) {
3672 const std::string& real_path = path.empty() ? screenshot_path_ : path;
3673 int status =
3674 RunCommand("", {"/system/bin/screencap", "-p", real_path},
3675 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
3676 if (status == 0) {
3677 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
3678 } else {
3679 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
3680 }
Paul Chang0d2aad72020-02-13 20:04:03 +08003681 if (listener_ != nullptr) {
3682 // Show a visual indication to indicate screenshot is taken via
3683 // IDumpstateListener.onScreenshotTaken()
3684 listener_->onScreenshotTaken(status == 0);
3685 }
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003686}
3687
3688bool is_dir(const char* pathname) {
3689 struct stat info;
3690 if (stat(pathname, &info) == -1) {
3691 return false;
3692 }
3693 return S_ISDIR(info.st_mode);
3694}
3695
3696time_t get_mtime(int fd, time_t default_mtime) {
3697 struct stat info;
3698 if (fstat(fd, &info) == -1) {
3699 return default_mtime;
3700 }
3701 return info.st_mtime;
3702}