blob: 83a34a3af28f86f2790ad1ffb799b9016f99c80d [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) {
Abhijeet Kaur359b1ff2019-07-26 16:01:36 +01002176 ds.screenshot_path_ = ds.GetPath(ds.CalledByApi() ? "-tmp.png" : ".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) {
Abhijeet Kaur359b1ff2019-07-26 16:01:36 +01002195 ds.path_ = ds.GetPath(ds.CalledByApi() ? "-tmp.zip" : ".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
Nandana Duttd2f5f082019-01-18 17:13:52 +00002398Dumpstate::RunStatus Dumpstate::Run(int32_t calling_uid, const std::string& calling_package) {
2399 Dumpstate::RunStatus status = RunInternal(calling_uid, calling_package);
Nandana Duttbabf6c72019-01-15 14:11:12 +00002400 if (listener_ != nullptr) {
2401 switch (status) {
2402 case Dumpstate::RunStatus::OK:
Nandana Duttcc4ead82019-01-23 08:29:23 +00002403 listener_->onFinished();
Nandana Duttbabf6c72019-01-15 14:11:12 +00002404 break;
2405 case Dumpstate::RunStatus::HELP:
2406 break;
2407 case Dumpstate::RunStatus::INVALID_INPUT:
Nandana Duttd2f5f082019-01-18 17:13:52 +00002408 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_INVALID_INPUT);
Nandana Duttbabf6c72019-01-15 14:11:12 +00002409 break;
2410 case Dumpstate::RunStatus::ERROR:
Nandana Duttd2f5f082019-01-18 17:13:52 +00002411 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_RUNTIME_ERROR);
2412 break;
2413 case Dumpstate::RunStatus::USER_CONSENT_DENIED:
2414 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_USER_DENIED_CONSENT);
2415 break;
2416 case Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT:
2417 listener_->onError(IDumpstateListener::BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT);
Nandana Duttbabf6c72019-01-15 14:11:12 +00002418 break;
2419 }
2420 }
2421 return status;
2422}
2423
Nandana Dutt8ae16e62020-03-27 10:20:22 +00002424void Dumpstate::Cancel() {
2425 CleanupTmpFiles();
2426 android::os::UnlinkAndLogOnError(log_path_);
2427 for (int i = 0; i < NUM_OF_DUMPS; i++) {
2428 android::os::UnlinkAndLogOnError(ds.bugreport_internal_dir_ + "/" +
2429 kDumpstateBoardFiles[i]);
2430 }
2431 tombstone_data_.clear();
2432 anr_data_.clear();
2433}
2434
Nandana Dutt979388e2018-11-30 16:48:55 +00002435/*
2436 * Dumps relevant information to a bugreport based on the given options.
2437 *
2438 * The bugreport can be dumped to a file or streamed to a socket.
2439 *
2440 * How dumping to file works:
2441 * stdout is redirected to a temporary file. This will later become the main bugreport entry.
2442 * stderr is redirected a log file.
2443 *
2444 * The temporary bugreport is then populated via printfs, dumping contents of files and
2445 * output of commands to stdout.
2446 *
2447 * If zipping, the temporary bugreport file is added to the zip archive. Else it's renamed to final
2448 * text file.
2449 *
2450 * If zipping, a bunch of other files and dumps also get added to the zip archive. The log file also
2451 * gets added to the archive.
2452 *
Nandana Dutt9a76d202019-01-21 15:56:48 +00002453 * Bugreports are first generated in a local directory and later copied to the caller's fd if
2454 * supplied.
Nandana Dutt979388e2018-11-30 16:48:55 +00002455 */
Nandana Duttd2f5f082019-01-18 17:13:52 +00002456Dumpstate::RunStatus Dumpstate::RunInternal(int32_t calling_uid,
2457 const std::string& calling_package) {
Nandana Dutt979388e2018-11-30 16:48:55 +00002458 LogDumpOptions(*options_);
Nandana Dutt197661d2018-11-16 16:40:21 +00002459 if (!options_->ValidateOptions()) {
Nandana Dutt58d72e22018-11-16 10:30:48 +00002460 MYLOGE("Invalid options specified\n");
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002461 return RunStatus::INVALID_INPUT;
2462 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002463 /* set as high priority, and protect from OOM killer */
2464 setpriority(PRIO_PROCESS, 0, -20);
Wei Wang9c1f9bb2016-06-28 14:32:35 -07002465
Felipe Lemed071c682016-10-20 16:48:00 -07002466 FILE* oom_adj = fopen("/proc/self/oom_score_adj", "we");
Colin Crossf45fa6b2012-03-26 12:38:26 -07002467 if (oom_adj) {
Wei Wang9c1f9bb2016-06-28 14:32:35 -07002468 fputs("-1000", oom_adj);
Colin Crossf45fa6b2012-03-26 12:38:26 -07002469 fclose(oom_adj);
Wei Wang9c1f9bb2016-06-28 14:32:35 -07002470 } else {
2471 /* fallback to kernels <= 2.6.35 */
2472 oom_adj = fopen("/proc/self/oom_adj", "we");
2473 if (oom_adj) {
2474 fputs("-17", oom_adj);
2475 fclose(oom_adj);
2476 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002477 }
2478
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002479 if (version_ == VERSION_DEFAULT) {
2480 version_ = VERSION_CURRENT;
Michal Karpinski4db754f2015-12-11 18:04:32 +00002481 }
2482
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002483 if (version_ != VERSION_CURRENT && version_ != VERSION_SPLIT_ANR) {
Vishnu Nair64afc022018-02-01 15:29:34 -08002484 MYLOGE("invalid version requested ('%s'); suppported values are: ('%s', '%s', '%s')\n",
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002485 version_.c_str(), VERSION_DEFAULT.c_str(), VERSION_CURRENT.c_str(),
Vishnu Nair64afc022018-02-01 15:29:34 -08002486 VERSION_SPLIT_ANR.c_str());
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002487 return RunStatus::INVALID_INPUT;
Felipe Lemed071c682016-10-20 16:48:00 -07002488 }
2489
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002490 if (options_->show_header_only) {
2491 PrintHeader();
2492 return RunStatus::OK;
Felipe Lemed071c682016-10-20 16:48:00 -07002493 }
2494
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002495 MYLOGD("dumpstate calling_uid = %d ; calling package = %s \n",
2496 calling_uid, calling_package.c_str());
Nandana Duttd2f5f082019-01-18 17:13:52 +00002497
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002498 // Redirect output if needed
Nandana Dutt9a76d202019-01-21 15:56:48 +00002499 bool is_redirecting = options_->OutputToFile();
Felipe Leme7447d7c2016-11-03 18:12:22 -07002500
2501 // TODO: temporarily set progress until it's part of the Dumpstate constructor
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002502 std::string stats_path =
Nandana Dutt979388e2018-11-30 16:48:55 +00002503 is_redirecting
2504 ? android::base::StringPrintf("%s/dumpstate-stats.txt", bugreport_internal_dir_.c_str())
2505 : "";
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002506 progress_.reset(new Progress(stats_path));
Felipe Leme7447d7c2016-11-03 18:12:22 -07002507
Felipe Lemed071c682016-10-20 16:48:00 -07002508 /* gets the sequential id */
Felipe Leme7447d7c2016-11-03 18:12:22 -07002509 uint32_t last_id = android::base::GetIntProperty(PROPERTY_LAST_ID, 0);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002510 id_ = ++last_id;
Felipe Lemed071c682016-10-20 16:48:00 -07002511 android::base::SetProperty(PROPERTY_LAST_ID, std::to_string(last_id));
2512
Sahana Raof35ed432019-07-12 10:47:52 +01002513 if (acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME) < 0) {
2514 MYLOGE("Failed to acquire wake lock: %s\n", strerror(errno));
2515 } else {
2516 // Wake lock will be released automatically on process death
2517 MYLOGD("Wake lock acquired.\n");
2518 }
2519
Felipe Leme6ae5c4f2017-01-10 14:13:22 -08002520 register_sig_handler();
Felipe Lemed071c682016-10-20 16:48:00 -07002521
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002522 // TODO(b/111441001): maybe skip if already started?
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002523 if (options_->do_start_service) {
Felipe Leme75876a22016-10-27 16:31:27 -07002524 MYLOGI("Starting 'dumpstate' service\n");
2525 android::status_t ret;
2526 if ((ret = android::os::DumpstateService::Start()) != android::OK) {
2527 MYLOGE("Unable to start DumpstateService: %d\n", ret);
2528 }
2529 }
2530
Felipe Lemef0292972016-11-22 13:57:05 -08002531 if (PropertiesHelper::IsDryRun()) {
Felipe Lemed071c682016-10-20 16:48:00 -07002532 MYLOGI("Running on dry-run mode (to disable it, call 'setprop dumpstate.dry_run false')\n");
2533 }
2534
Nandana Dutt235c6672019-11-14 15:22:32 +00002535 MYLOGI("dumpstate info: id=%d, args='%s', bugreport_mode= %s bugreport format version: %s\n",
2536 id_, options_->args.c_str(), options_->bugreport_mode.c_str(), version_.c_str());
Felipe Leme809d74e2016-02-02 12:57:00 -08002537
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002538 do_early_screenshot_ = options_->do_progress_updates;
Felipe Lemee338bf62015-12-07 14:03:50 -08002539
Christopher Ferrised9354f2014-10-01 17:35:01 -07002540 // If we are going to use a socket, do it as early as possible
2541 // to avoid timeouts from bugreport.
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002542 if (options_->use_socket) {
Nandana Dutta344cb62019-02-22 15:12:35 +00002543 if (!redirect_to_socket(stdout, "dumpstate")) {
2544 return ERROR;
2545 }
Christopher Ferrised9354f2014-10-01 17:35:01 -07002546 }
2547
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002548 if (options_->use_control_socket) {
Felipe Leme2628e9e2016-04-12 16:36:51 -07002549 MYLOGD("Opening control socket\n");
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002550 control_socket_fd_ = open_socket("dumpstate");
Nandana Dutta344cb62019-02-22 15:12:35 +00002551 if (control_socket_fd_ == -1) {
2552 return ERROR;
2553 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002554 options_->do_progress_updates = 1;
Felipe Leme2628e9e2016-04-12 16:36:51 -07002555 }
2556
Felipe Leme71bbfc52015-11-23 14:14:51 -08002557 if (is_redirecting) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002558 PrepareToWriteToFile();
Felipe Leme1e9edc62015-12-21 16:02:13 -08002559
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002560 if (options_->do_progress_updates) {
Abhijeet Kaure370d682019-10-01 16:49:30 +01002561 // clang-format off
2562 std::vector<std::string> am_args = {
2563 "--receiver-permission", "android.permission.DUMP",
2564 };
2565 // clang-format on
2566 // Send STARTED broadcast for apps that listen to bugreport generation events
2567 SendBroadcast("com.android.internal.intent.action.BUGREPORT_STARTED", am_args);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002568 if (options_->use_control_socket) {
2569 dprintf(control_socket_fd_, "BEGIN:%s\n", path_.c_str());
Felipe Lemeaabfcae2016-07-29 09:49:04 -07002570 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08002571 }
2572 }
2573
Nick Kralevichf3599b32016-01-25 15:05:16 -08002574 /* read /proc/cmdline before dropping root */
2575 FILE *cmdline = fopen("/proc/cmdline", "re");
2576 if (cmdline) {
2577 fgets(cmdline_buf, sizeof(cmdline_buf), cmdline);
2578 fclose(cmdline);
2579 }
2580
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002581 if (options_->do_vibrate) {
Felipe Leme35b8cf12017-02-10 15:47:29 -08002582 Vibrate(150);
John Michelau1f794c42012-09-17 11:20:19 -05002583 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002584
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002585 if (options_->do_zip_file && zip_file != nullptr) {
2586 if (chown(path_.c_str(), AID_SHELL, AID_SHELL)) {
2587 MYLOGE("Unable to change ownership of zip file %s: %s\n", path_.c_str(),
Felipe Leme1d486fe2016-10-14 18:06:47 -07002588 strerror(errno));
Felipe Leme1e9edc62015-12-21 16:02:13 -08002589 }
2590 }
2591
Nandana Dutt3f8c7172018-09-25 12:01:54 +01002592 int dup_stdout_fd;
2593 int dup_stderr_fd;
Felipe Leme71bbfc52015-11-23 14:14:51 -08002594 if (is_redirecting) {
Nandana Dutt979388e2018-11-30 16:48:55 +00002595 // Redirect stderr to log_path_ for debugging.
Vishnu Nair20cf5032018-01-05 13:15:49 -08002596 TEMP_FAILURE_RETRY(dup_stderr_fd = dup(fileno(stderr)));
Nandana Dutta344cb62019-02-22 15:12:35 +00002597 if (!redirect_to_file(stderr, const_cast<char*>(log_path_.c_str()))) {
2598 return ERROR;
2599 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002600 if (chown(log_path_.c_str(), AID_SHELL, AID_SHELL)) {
2601 MYLOGE("Unable to change ownership of dumpstate log file %s: %s\n", log_path_.c_str(),
2602 strerror(errno));
Felipe Leme6fe9db62016-02-12 09:04:16 -08002603 }
Nandana Dutt979388e2018-11-30 16:48:55 +00002604
2605 // Redirect stdout to tmp_path_. This is the main bugreport entry and will be
2606 // moved into zip file later, if zipping.
Vishnu Nair20cf5032018-01-05 13:15:49 -08002607 TEMP_FAILURE_RETRY(dup_stdout_fd = dup(fileno(stdout)));
Nandana Dutt979388e2018-11-30 16:48:55 +00002608 // TODO: why not write to a file instead of stdout to overcome this problem?
Felipe Leme6e01fa62015-11-11 19:35:14 -08002609 /* TODO: rather than generating a text file now and zipping it later,
2610 it would be more efficient to redirect stdout to the zip entry
2611 directly, but the libziparchive doesn't support that option yet. */
Nandana Dutta344cb62019-02-22 15:12:35 +00002612 if (!redirect_to_file(stdout, const_cast<char*>(tmp_path_.c_str()))) {
2613 return ERROR;
2614 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002615 if (chown(tmp_path_.c_str(), AID_SHELL, AID_SHELL)) {
Felipe Leme6fe9db62016-02-12 09:04:16 -08002616 MYLOGE("Unable to change ownership of temporary bugreport file %s: %s\n",
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002617 tmp_path_.c_str(), strerror(errno));
Felipe Leme6fe9db62016-02-12 09:04:16 -08002618 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002619 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08002620
2621 // Don't buffer stdout
2622 setvbuf(stdout, nullptr, _IONBF, 0);
2623
Felipe Leme608385d2016-02-01 10:35:38 -08002624 // NOTE: there should be no stdout output until now, otherwise it would break the header.
2625 // In particular, DurationReport objects should be created passing 'title, NULL', so their
Felipe Lemecbce55d2016-02-08 09:53:18 -08002626 // duration is logged into MYLOG instead.
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002627 PrintHeader();
Colin Crossf45fa6b2012-03-26 12:38:26 -07002628
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002629 if (options_->telephony_only) {
Paul Chang0d2aad72020-02-13 20:04:03 +08002630 MaybeTakeEarlyScreenshot();
Jichao Lie89d9c12019-11-21 19:02:51 -08002631 MaybeCheckUserConsent(calling_uid, calling_package);
Hunter Knepshield0cc6c212020-01-07 16:57:10 -08002632 DumpstateTelephonyOnly(calling_package);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002633 DumpstateBoard();
2634 } else if (options_->wifi_only) {
Paul Chang0d2aad72020-02-13 20:04:03 +08002635 MaybeTakeEarlyScreenshot();
Jichao Lie89d9c12019-11-21 19:02:51 -08002636 MaybeCheckUserConsent(calling_uid, calling_package);
mukesh agrawal253dad42018-01-23 21:59:59 -08002637 DumpstateWifiOnly();
Felipe Leme6ec6ac42017-01-10 15:29:53 -08002638 } else {
Paul Chang0d2aad72020-02-13 20:04:03 +08002639 // Invoke critical dumpsys first to preserve system state, before doing anything else.
Jichao Lie89d9c12019-11-21 19:02:51 -08002640 RunDumpsysCritical();
2641
Paul Chang0d2aad72020-02-13 20:04:03 +08002642 // Take screenshot and get consent only after critical dumpsys has finished.
2643 MaybeTakeEarlyScreenshot();
Jichao Lie89d9c12019-11-21 19:02:51 -08002644 MaybeCheckUserConsent(calling_uid, calling_package);
2645
Nandana Dutt4be45d12018-09-26 15:04:23 +01002646 // Dump state for the default case. This also drops root.
Jichao Lie89d9c12019-11-21 19:02:51 -08002647 RunStatus s = DumpstateDefaultAfterCritical();
Nandana Dutt5c390032019-03-12 10:52:56 +00002648 if (s != RunStatus::OK) {
Nandana Duttaac6f582019-07-26 14:32:47 +01002649 if (s == RunStatus::USER_CONSENT_DENIED) {
Nandana Dutt5c390032019-03-12 10:52:56 +00002650 HandleUserConsentDenied();
2651 }
2652 return s;
Felipe Leme6ec6ac42017-01-10 15:29:53 -08002653 }
Zhengyin Qian068ecc72016-08-10 16:48:14 -07002654 }
Felipe Leme71a74ac2016-03-17 15:43:25 -07002655
Felipe Leme55b42a62015-11-10 17:39:08 -08002656 /* close output if needed */
Felipe Leme71bbfc52015-11-23 14:14:51 -08002657 if (is_redirecting) {
Vishnu Nair20cf5032018-01-05 13:15:49 -08002658 TEMP_FAILURE_RETRY(dup2(dup_stdout_fd, fileno(stdout)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07002659 }
2660
Abhijeet Kaure370d682019-10-01 16:49:30 +01002661 // Zip the (now complete) .tmp file within the internal directory.
Nandana Dutt9a76d202019-01-21 15:56:48 +00002662 if (options_->OutputToFile()) {
Nandana Dutt4be45d12018-09-26 15:04:23 +01002663 FinalizeFile();
Colin Crossf45fa6b2012-03-26 12:38:26 -07002664 }
2665
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002666 // Share the final file with the caller if the user has consented or Shell is the caller.
Nandana Duttd2f5f082019-01-18 17:13:52 +00002667 Dumpstate::RunStatus status = Dumpstate::RunStatus::OK;
Abhijeet Kaure370d682019-10-01 16:49:30 +01002668 if (CalledByApi()) {
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002669 status = CopyBugreportIfUserConsented(calling_uid);
Nandana Duttd2f5f082019-01-18 17:13:52 +00002670 if (status != Dumpstate::RunStatus::OK &&
2671 status != Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT) {
2672 // Do an early return if there were errors. We make an exception for consent
2673 // timing out because it's possible the user got distracted. In this case the
2674 // bugreport is not shared but made available for manual retrieval.
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002675 MYLOGI("User denied consent. Returning\n");
Nandana Duttd2f5f082019-01-18 17:13:52 +00002676 return status;
2677 }
Paul Chang0d2aad72020-02-13 20:04:03 +08002678 if (options_->do_screenshot &&
2679 options_->screenshot_fd.get() != -1 &&
2680 !options_->is_screenshot_copied) {
Nandana Dutte78c3d72019-01-29 16:10:45 +00002681 bool copy_succeeded = android::os::CopyFileToFd(screenshot_path_,
2682 options_->screenshot_fd.get());
2683 if (copy_succeeded) {
2684 android::os::UnlinkAndLogOnError(screenshot_path_);
2685 }
2686 }
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002687 if (status == Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT) {
2688 MYLOGI(
2689 "Did not receive user consent yet."
2690 " Will not copy the bugreport artifacts to caller.\n");
Abhijeet Kaur57627412019-04-17 16:00:09 +01002691 const String16 incidentcompanion("incidentcompanion");
2692 sp<android::IBinder> ics(defaultServiceManager()->getService(incidentcompanion));
2693 if (ics != nullptr) {
2694 MYLOGD("Canceling user consent request via incidentcompanion service\n");
2695 android::interface_cast<android::os::IIncidentCompanion>(ics)->cancelAuthorization(
2696 consent_callback_.get());
2697 } else {
2698 MYLOGD("Unable to cancel user consent; incidentcompanion service unavailable\n");
2699 }
Nandana Dutt16d1aee2019-02-15 16:13:53 +00002700 }
Nandana Duttd2f5f082019-01-18 17:13:52 +00002701 }
2702
Felipe Lemecc2a2fa2016-02-25 14:02:44 -08002703 /* vibrate a few but shortly times to let user know it's finished */
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002704 if (options_->do_vibrate) {
Takuya Ogawa47f644e2017-12-20 18:09:09 +09002705 for (int i = 0; i < 3; i++) {
2706 Vibrate(75);
2707 usleep((75 + 50) * 1000);
2708 }
Felipe Lemecc2a2fa2016-02-25 14:02:44 -08002709 }
2710
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002711 MYLOGD("Final progress: %d/%d (estimated %d)\n", progress_->Get(), progress_->GetMax(),
2712 progress_->GetInitialMax());
2713 progress_->Save();
2714 MYLOGI("done (id %d)\n", id_);
Colin Crossf45fa6b2012-03-26 12:38:26 -07002715
Felipe Leme107a05f2016-03-08 15:11:15 -08002716 if (is_redirecting) {
Vishnu Nair20cf5032018-01-05 13:15:49 -08002717 TEMP_FAILURE_RETRY(dup2(dup_stderr_fd, fileno(stderr)));
Felipe Leme107a05f2016-03-08 15:11:15 -08002718 }
2719
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002720 if (options_->use_control_socket && control_socket_fd_ != -1) {
Felipe Lemee844a9d2016-09-21 15:01:39 -07002721 MYLOGD("Closing control socket\n");
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002722 close(control_socket_fd_);
Felipe Leme2628e9e2016-04-12 16:36:51 -07002723 }
2724
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002725 tombstone_data_.clear();
2726 anr_data_.clear();
Narayan Kamath6b9516c2017-10-27 11:15:51 +01002727
Nandana Duttd2f5f082019-01-18 17:13:52 +00002728 return (consent_callback_ != nullptr &&
2729 consent_callback_->getResult() == UserConsentResult::UNAVAILABLE)
2730 ? USER_CONSENT_TIMED_OUT
2731 : RunStatus::OK;
2732}
2733
Paul Chang0d2aad72020-02-13 20:04:03 +08002734void Dumpstate::MaybeTakeEarlyScreenshot() {
2735 if (!options_->do_screenshot || !do_early_screenshot_) {
2736 return;
2737 }
2738
2739 TakeScreenshot();
2740}
2741
Jichao Lie89d9c12019-11-21 19:02:51 -08002742void Dumpstate::MaybeCheckUserConsent(int32_t calling_uid, const std::string& calling_package) {
2743 if (calling_uid == AID_SHELL || !CalledByApi()) {
2744 // No need to get consent for shell triggered dumpstates, or not through
2745 // bugreporting API (i.e. no fd to copy back).
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002746 return;
2747 }
Nandana Duttd2f5f082019-01-18 17:13:52 +00002748 consent_callback_ = new ConsentCallback();
2749 const String16 incidentcompanion("incidentcompanion");
2750 sp<android::IBinder> ics(defaultServiceManager()->getService(incidentcompanion));
Jichao Lie89d9c12019-11-21 19:02:51 -08002751 android::String16 package(calling_package.c_str());
Nandana Duttd2f5f082019-01-18 17:13:52 +00002752 if (ics != nullptr) {
2753 MYLOGD("Checking user consent via incidentcompanion service\n");
2754 android::interface_cast<android::os::IIncidentCompanion>(ics)->authorizeReport(
Jichao Lie89d9c12019-11-21 19:02:51 -08002755 calling_uid, package, String16(), String16(),
Joe Onorato1c36d752019-03-17 18:26:43 -07002756 0x1 /* FLAG_CONFIRMATION_DIALOG */, consent_callback_.get());
Nandana Duttd2f5f082019-01-18 17:13:52 +00002757 } else {
2758 MYLOGD("Unable to check user consent; incidentcompanion service unavailable\n");
2759 }
2760}
2761
Nandana Dutt5c390032019-03-12 10:52:56 +00002762bool Dumpstate::IsUserConsentDenied() const {
2763 return ds.consent_callback_ != nullptr &&
2764 ds.consent_callback_->getResult() == UserConsentResult::DENIED;
2765}
2766
Abhijeet Kaur359b1ff2019-07-26 16:01:36 +01002767bool Dumpstate::CalledByApi() const {
2768 return ds.options_->bugreport_fd.get() != -1 ? true : false;
2769}
2770
Nandana Dutt8ae16e62020-03-27 10:20:22 +00002771void Dumpstate::CleanupTmpFiles() {
Nandana Duttd2f5f082019-01-18 17:13:52 +00002772 android::os::UnlinkAndLogOnError(tmp_path_);
2773 android::os::UnlinkAndLogOnError(screenshot_path_);
2774 android::os::UnlinkAndLogOnError(path_);
2775}
2776
2777Dumpstate::RunStatus Dumpstate::HandleUserConsentDenied() {
2778 MYLOGD("User denied consent; deleting files and returning\n");
Nandana Dutt8ae16e62020-03-27 10:20:22 +00002779 CleanupTmpFiles();
Nandana Duttd2f5f082019-01-18 17:13:52 +00002780 return USER_CONSENT_DENIED;
2781}
2782
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002783Dumpstate::RunStatus Dumpstate::CopyBugreportIfUserConsented(int32_t calling_uid) {
Nandana Duttd2f5f082019-01-18 17:13:52 +00002784 // If the caller has asked to copy the bugreport over to their directory, we need explicit
Abhijeet Kaur3172b532019-10-15 15:07:03 +01002785 // user consent (unless the caller is Shell).
2786 UserConsentResult consent_result;
2787 if (calling_uid == AID_SHELL) {
2788 consent_result = UserConsentResult::APPROVED;
2789 } else {
2790 consent_result = consent_callback_->getResult();
2791 }
Nandana Duttd2f5f082019-01-18 17:13:52 +00002792 if (consent_result == UserConsentResult::UNAVAILABLE) {
2793 // User has not responded yet.
2794 uint64_t elapsed_ms = consent_callback_->getElapsedTimeMs();
Hunter Knepshield70610fa2020-01-03 15:27:33 -08002795 // Telephony is a fast report type, particularly on user builds where information may be
2796 // more aggressively limited. To give the user time to read the consent dialog, increase the
2797 // timeout.
2798 uint64_t timeout_ms = options_->telephony_only ? TELEPHONY_REPORT_USER_CONSENT_TIMEOUT_MS
2799 : USER_CONSENT_TIMEOUT_MS;
2800 if (elapsed_ms < timeout_ms) {
2801 uint delay_seconds = (timeout_ms - elapsed_ms) / 1000;
Nandana Duttd2f5f082019-01-18 17:13:52 +00002802 MYLOGD("Did not receive user consent yet; going to wait for %d seconds", delay_seconds);
2803 sleep(delay_seconds);
2804 }
2805 consent_result = consent_callback_->getResult();
2806 }
2807 if (consent_result == UserConsentResult::DENIED) {
2808 // User has explicitly denied sharing with the app. To be safe delete the
2809 // internal bugreport & tmp files.
2810 return HandleUserConsentDenied();
2811 }
2812 if (consent_result == UserConsentResult::APPROVED) {
Nandana Dutte78c3d72019-01-29 16:10:45 +00002813 bool copy_succeeded = android::os::CopyFileToFd(path_, options_->bugreport_fd.get());
2814 if (copy_succeeded) {
2815 android::os::UnlinkAndLogOnError(path_);
Nandana Duttd2f5f082019-01-18 17:13:52 +00002816 }
2817 return copy_succeeded ? Dumpstate::RunStatus::OK : Dumpstate::RunStatus::ERROR;
2818 } else if (consent_result == UserConsentResult::UNAVAILABLE) {
2819 // consent_result is still UNAVAILABLE. The user has likely not responded yet.
2820 // Since we do not have user consent to share the bugreport it does not get
2821 // copied over to the calling app but remains in the internal directory from
2822 // where the user can manually pull it.
2823 return Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT;
2824 }
2825 // Unknown result; must be a programming error.
2826 MYLOGE("Unknown user consent result:%d\n", consent_result);
2827 return Dumpstate::RunStatus::ERROR;
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002828}
2829
Nandana Duttf02564e2019-02-15 15:24:24 +00002830Dumpstate::RunStatus Dumpstate::ParseCommandlineAndRun(int argc, char* argv[]) {
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002831 std::unique_ptr<Dumpstate::DumpOptions> options = std::make_unique<Dumpstate::DumpOptions>();
2832 Dumpstate::RunStatus status = options->Initialize(argc, argv);
2833 if (status == Dumpstate::RunStatus::OK) {
Nandana Duttf02564e2019-02-15 15:24:24 +00002834 SetOptions(std::move(options));
Nandana Duttd2f5f082019-01-18 17:13:52 +00002835 // When directly running dumpstate binary, the output is not expected to be written
2836 // to any external file descriptor.
Nandana Duttf02564e2019-02-15 15:24:24 +00002837 assert(options_->bugreport_fd.get() == -1);
Nandana Duttd2f5f082019-01-18 17:13:52 +00002838
2839 // calling_uid and calling_package are for user consent to share the bugreport with
2840 // an app; they are irrelvant here because bugreport is only written to a local
2841 // directory, and not shared.
Nandana Duttf02564e2019-02-15 15:24:24 +00002842 status = Run(-1 /* calling_uid */, "" /* calling_package */);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002843 }
Nandana Duttf02564e2019-02-15 15:24:24 +00002844 return status;
2845}
2846
2847/* Main entry point for dumpstate binary. */
2848int run_main(int argc, char* argv[]) {
2849 Dumpstate::RunStatus status = ds.ParseCommandlineAndRun(argc, argv);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002850
2851 switch (status) {
2852 case Dumpstate::RunStatus::OK:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002853 exit(0);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002854 case Dumpstate::RunStatus::HELP:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002855 ShowUsage();
2856 exit(0);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002857 case Dumpstate::RunStatus::INVALID_INPUT:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002858 fprintf(stderr, "Invalid combination of args\n");
2859 ShowUsage();
2860 exit(1);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002861 case Dumpstate::RunStatus::ERROR:
Nandana Duttd2f5f082019-01-18 17:13:52 +00002862 FALLTHROUGH_INTENDED;
2863 case Dumpstate::RunStatus::USER_CONSENT_DENIED:
2864 FALLTHROUGH_INTENDED;
2865 case Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT:
Nandana Dutt12ae14a2019-01-09 10:35:53 +00002866 exit(2);
Nandana Dutt5fb117b2018-09-27 09:23:36 +01002867 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07002868}
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002869
2870// TODO(111441001): Default DumpOptions to sensible values.
2871Dumpstate::Dumpstate(const std::string& version)
2872 : pid_(getpid()),
2873 options_(new Dumpstate::DumpOptions()),
Nandana Dutt402a8392019-06-14 14:25:13 +01002874 last_reported_percent_progress_(0),
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002875 version_(version),
2876 now_(time(nullptr)) {
2877}
2878
2879Dumpstate& Dumpstate::GetInstance() {
2880 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
2881 return singleton_;
2882}
2883
Nandana Dutt8d945c02019-08-14 13:30:07 +01002884DurationReporter::DurationReporter(const std::string& title, bool logcat_only, bool verbose)
2885 : title_(title), logcat_only_(logcat_only), verbose_(verbose) {
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002886 if (!title_.empty()) {
2887 started_ = Nanotime();
2888 }
2889}
2890
2891DurationReporter::~DurationReporter() {
2892 if (!title_.empty()) {
2893 float elapsed = (float)(Nanotime() - started_) / NANOS_PER_SEC;
chenqiwuaf8b2d92019-12-12 18:53:51 +08002894 if (elapsed >= .5f || verbose_) {
2895 MYLOGD("Duration of '%s': %.2fs\n", title_.c_str(), elapsed);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002896 }
chenqiwuaf8b2d92019-12-12 18:53:51 +08002897 if (!logcat_only_) {
2898 // Use "Yoda grammar" to make it easier to grep|sort sections.
2899 printf("------ %.3fs was the duration of '%s' ------\n", elapsed, title_.c_str());
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002900 }
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01002901 }
2902}
2903
2904const int32_t Progress::kDefaultMax = 5000;
2905
2906Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
2907}
2908
2909Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
2910 : Progress(initial_max, growth_factor, "") {
2911 progress_ = progress;
2912}
2913
2914Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
2915 : initial_max_(initial_max),
2916 progress_(0),
2917 max_(initial_max),
2918 growth_factor_(growth_factor),
2919 n_runs_(0),
2920 average_max_(0),
2921 path_(path) {
2922 if (!path_.empty()) {
2923 Load();
2924 }
2925}
2926
2927void Progress::Load() {
2928 MYLOGD("Loading stats from %s\n", path_.c_str());
2929 std::string content;
2930 if (!android::base::ReadFileToString(path_, &content)) {
2931 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
2932 return;
2933 }
2934 if (content.empty()) {
2935 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
2936 return;
2937 }
2938 std::vector<std::string> lines = android::base::Split(content, "\n");
2939
2940 if (lines.size() < 1) {
2941 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
2942 (int)lines.size(), max_);
2943 return;
2944 }
2945 char* ptr;
2946 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
2947 average_max_ = strtol(ptr, nullptr, 10);
2948 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
2949 average_max_ > STATS_MAX_AVERAGE) {
2950 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
2951 initial_max_ = Progress::kDefaultMax;
2952 } else {
2953 initial_max_ = average_max_;
2954 }
2955 max_ = initial_max_;
2956
2957 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
2958}
2959
2960void Progress::Save() {
2961 int32_t total = n_runs_ * average_max_ + progress_;
2962 int32_t runs = n_runs_ + 1;
2963 int32_t average = floor(((float)total) / runs);
2964 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
2965 path_.c_str());
2966 if (path_.empty()) {
2967 return;
2968 }
2969
2970 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
2971 if (!android::base::WriteStringToFile(content, path_)) {
2972 MYLOGE("Could not save stats on %s\n", path_.c_str());
2973 }
2974}
2975
2976int32_t Progress::Get() const {
2977 return progress_;
2978}
2979
2980bool Progress::Inc(int32_t delta_sec) {
2981 bool changed = false;
2982 if (delta_sec >= 0) {
2983 progress_ += delta_sec;
2984 if (progress_ > max_) {
2985 int32_t old_max = max_;
2986 max_ = floor((float)progress_ * growth_factor_);
2987 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
2988 changed = true;
2989 }
2990 }
2991 return changed;
2992}
2993
2994int32_t Progress::GetMax() const {
2995 return max_;
2996}
2997
2998int32_t Progress::GetInitialMax() const {
2999 return initial_max_;
3000}
3001
3002void Progress::Dump(int fd, const std::string& prefix) const {
3003 const char* pr = prefix.c_str();
3004 dprintf(fd, "%sprogress: %d\n", pr, progress_);
3005 dprintf(fd, "%smax: %d\n", pr, max_);
3006 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
3007 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
3008 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
3009 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
3010 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
3011}
3012
3013bool Dumpstate::IsZipping() const {
3014 return zip_writer_ != nullptr;
3015}
3016
3017std::string Dumpstate::GetPath(const std::string& suffix) const {
3018 return GetPath(bugreport_internal_dir_, suffix);
3019}
3020
3021std::string Dumpstate::GetPath(const std::string& directory, const std::string& suffix) const {
3022 return android::base::StringPrintf("%s/%s-%s%s", directory.c_str(), base_name_.c_str(),
3023 name_.c_str(), suffix.c_str());
3024}
3025
3026void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
3027 progress_ = std::move(progress);
3028}
3029
3030void for_each_userid(void (*func)(int), const char *header) {
3031 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
3032 "for_each_userid(%s)", header);
3033 DurationReporter duration_reporter(title);
3034 if (PropertiesHelper::IsDryRun()) return;
3035
3036 DIR *d;
3037 struct dirent *de;
3038
3039 if (header) printf("\n------ %s ------\n", header);
3040 func(0);
3041
3042 if (!(d = opendir("/data/system/users"))) {
3043 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
3044 return;
3045 }
3046
3047 while ((de = readdir(d))) {
3048 int userid;
3049 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
3050 continue;
3051 }
3052 func(userid);
3053 }
3054
3055 closedir(d);
3056}
3057
3058static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
3059 DIR *d;
3060 struct dirent *de;
3061
3062 if (!(d = opendir("/proc"))) {
3063 printf("Failed to open /proc (%s)\n", strerror(errno));
3064 return;
3065 }
3066
3067 if (header) printf("\n------ %s ------\n", header);
3068 while ((de = readdir(d))) {
3069 if (ds.IsUserConsentDenied()) {
3070 MYLOGE(
3071 "Returning early because user denied consent to share bugreport with calling app.");
3072 closedir(d);
3073 return;
3074 }
3075 int pid;
3076 int fd;
3077 char cmdpath[255];
3078 char cmdline[255];
3079
3080 if (!(pid = atoi(de->d_name))) {
3081 continue;
3082 }
3083
3084 memset(cmdline, 0, sizeof(cmdline));
3085
3086 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
3087 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
3088 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
3089 close(fd);
3090 if (cmdline[0]) {
3091 helper(pid, cmdline, arg);
3092 continue;
3093 }
3094 }
3095
3096 // if no cmdline, a kernel thread has comm
3097 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
3098 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
3099 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
3100 close(fd);
3101 if (cmdline[1]) {
3102 cmdline[0] = '[';
3103 size_t len = strcspn(cmdline, "\f\b\r\n");
3104 cmdline[len] = ']';
3105 cmdline[len+1] = '\0';
3106 }
3107 }
3108 if (!cmdline[0]) {
3109 strcpy(cmdline, "N/A");
3110 }
3111 helper(pid, cmdline, arg);
3112 }
3113
3114 closedir(d);
3115}
3116
3117static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
3118 for_each_pid_func *func = (for_each_pid_func*) arg;
3119 func(pid, cmdline);
3120}
3121
3122void for_each_pid(for_each_pid_func func, const char *header) {
3123 std::string title = header == nullptr ? "for_each_pid"
3124 : android::base::StringPrintf("for_each_pid(%s)", header);
3125 DurationReporter duration_reporter(title);
3126 if (PropertiesHelper::IsDryRun()) return;
3127
3128 __for_each_pid(for_each_pid_helper, header, (void *) func);
3129}
3130
3131static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
3132 DIR *d;
3133 struct dirent *de;
3134 char taskpath[255];
3135 for_each_tid_func *func = (for_each_tid_func *) arg;
3136
3137 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
3138
3139 if (!(d = opendir(taskpath))) {
3140 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
3141 return;
3142 }
3143
3144 func(pid, pid, cmdline);
3145
3146 while ((de = readdir(d))) {
3147 if (ds.IsUserConsentDenied()) {
3148 MYLOGE(
3149 "Returning early because user denied consent to share bugreport with calling app.");
3150 closedir(d);
3151 return;
3152 }
3153 int tid;
3154 int fd;
3155 char commpath[255];
3156 char comm[255];
3157
3158 if (!(tid = atoi(de->d_name))) {
3159 continue;
3160 }
3161
3162 if (tid == pid)
3163 continue;
3164
3165 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
3166 memset(comm, 0, sizeof(comm));
3167 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
3168 strcpy(comm, "N/A");
3169 } else {
3170 char *c;
3171 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
3172 close(fd);
3173
3174 c = strrchr(comm, '\n');
3175 if (c) {
3176 *c = '\0';
3177 }
3178 }
3179 func(pid, tid, comm);
3180 }
3181
3182 closedir(d);
3183}
3184
3185void for_each_tid(for_each_tid_func func, const char *header) {
3186 std::string title = header == nullptr ? "for_each_tid"
3187 : android::base::StringPrintf("for_each_tid(%s)", header);
3188 DurationReporter duration_reporter(title);
3189
3190 if (PropertiesHelper::IsDryRun()) return;
3191
3192 __for_each_pid(for_each_tid_helper, header, (void *) func);
3193}
3194
3195void show_wchan(int pid, int tid, const char *name) {
3196 if (PropertiesHelper::IsDryRun()) return;
3197
3198 char path[255];
3199 char buffer[255];
3200 int fd, ret, save_errno;
3201 char name_buffer[255];
3202
3203 memset(buffer, 0, sizeof(buffer));
3204
3205 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
3206 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
3207 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
3208 return;
3209 }
3210
3211 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
3212 save_errno = errno;
3213 close(fd);
3214
3215 if (ret < 0) {
3216 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
3217 return;
3218 }
3219
3220 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
3221 pid == tid ? 0 : 3, "", name);
3222
3223 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
3224
3225 return;
3226}
3227
3228// print time in centiseconds
3229static void snprcent(char *buffer, size_t len, size_t spc,
3230 unsigned long long time) {
3231 static long hz; // cache discovered hz
3232
3233 if (hz <= 0) {
3234 hz = sysconf(_SC_CLK_TCK);
3235 if (hz <= 0) {
3236 hz = 1000;
3237 }
3238 }
3239
3240 // convert to centiseconds
3241 time = (time * 100 + (hz / 2)) / hz;
3242
3243 char str[16];
3244
3245 snprintf(str, sizeof(str), " %llu.%02u",
3246 time / 100, (unsigned)(time % 100));
3247 size_t offset = strlen(buffer);
3248 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
3249 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
3250}
3251
3252// print permille as a percent
3253static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
3254 char str[16];
3255
3256 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
3257 size_t offset = strlen(buffer);
3258 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
3259 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
3260}
3261
3262void show_showtime(int pid, const char *name) {
3263 if (PropertiesHelper::IsDryRun()) return;
3264
3265 char path[255];
3266 char buffer[1023];
3267 int fd, ret, save_errno;
3268
3269 memset(buffer, 0, sizeof(buffer));
3270
3271 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
3272 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
3273 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
3274 return;
3275 }
3276
3277 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
3278 save_errno = errno;
3279 close(fd);
3280
3281 if (ret < 0) {
3282 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
3283 return;
3284 }
3285
3286 // field 14 is utime
3287 // field 15 is stime
3288 // field 42 is iotime
3289 unsigned long long utime = 0, stime = 0, iotime = 0;
3290 if (sscanf(buffer,
3291 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
3292 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
3293 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
3294 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
3295 &utime, &stime, &iotime) != 3) {
3296 return;
3297 }
3298
3299 unsigned long long total = utime + stime;
3300 if (!total) {
3301 return;
3302 }
3303
3304 unsigned permille = (iotime * 1000 + (total / 2)) / total;
3305 if (permille > 1000) {
3306 permille = 1000;
3307 }
3308
3309 // try to beautify and stabilize columns at <80 characters
3310 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
3311 if ((name[0] != '[') || utime) {
3312 snprcent(buffer, sizeof(buffer), 57, utime);
3313 }
3314 snprcent(buffer, sizeof(buffer), 65, stime);
3315 if ((name[0] != '[') || iotime) {
3316 snprcent(buffer, sizeof(buffer), 73, iotime);
3317 }
3318 if (iotime) {
3319 snprdec(buffer, sizeof(buffer), 79, permille);
3320 }
3321 puts(buffer); // adds a trailing newline
3322
3323 return;
3324}
3325
3326void do_dmesg() {
3327 const char *title = "KERNEL LOG (dmesg)";
3328 DurationReporter duration_reporter(title);
3329 printf("------ %s ------\n", title);
3330
3331 if (PropertiesHelper::IsDryRun()) return;
3332
3333 /* Get size of kernel buffer */
3334 int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
3335 if (size <= 0) {
3336 printf("Unexpected klogctl return value: %d\n\n", size);
3337 return;
3338 }
3339 char *buf = (char *) malloc(size + 1);
3340 if (buf == nullptr) {
3341 printf("memory allocation failed\n\n");
3342 return;
3343 }
3344 int retval = klogctl(KLOG_READ_ALL, buf, size);
3345 if (retval < 0) {
3346 printf("klogctl failure\n\n");
3347 free(buf);
3348 return;
3349 }
3350 buf[retval] = '\0';
3351 printf("%s\n\n", buf);
3352 free(buf);
3353 return;
3354}
3355
3356void do_showmap(int pid, const char *name) {
3357 char title[255];
3358 char arg[255];
3359
3360 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
3361 snprintf(arg, sizeof(arg), "%d", pid);
3362 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
3363}
3364
3365int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
3366 DurationReporter duration_reporter(title);
3367
3368 int status = DumpFileToFd(STDOUT_FILENO, title, path);
3369
3370 UpdateProgress(WEIGHT_FILE);
3371
3372 return status;
3373}
3374
3375int read_file_as_long(const char *path, long int *output) {
3376 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
3377 if (fd < 0) {
3378 int err = errno;
3379 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
3380 return -1;
3381 }
3382 char buffer[50];
3383 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
3384 if (bytes_read == -1) {
3385 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
3386 return -2;
3387 }
3388 if (bytes_read == 0) {
3389 MYLOGE("File %s is empty\n", path);
3390 return -3;
3391 }
3392 *output = atoi(buffer);
3393 return 0;
3394}
3395
3396/* calls skip to gate calling dump_from_fd recursively
3397 * in the specified directory. dump_from_fd defaults to
3398 * dump_file_from_fd above when set to NULL. skip defaults
3399 * to false when set to NULL. dump_from_fd will always be
3400 * called with title NULL.
3401 */
3402int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
3403 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
3404 DurationReporter duration_reporter(title);
3405 DIR *dirp;
3406 struct dirent *d;
3407 char *newpath = nullptr;
3408 const char *slash = "/";
3409 int retval = 0;
3410
3411 if (!title.empty()) {
3412 printf("------ %s (%s) ------\n", title.c_str(), dir);
3413 }
3414 if (PropertiesHelper::IsDryRun()) return 0;
3415
3416 if (dir[strlen(dir) - 1] == '/') {
3417 ++slash;
3418 }
3419 dirp = opendir(dir);
3420 if (dirp == nullptr) {
3421 retval = -errno;
3422 MYLOGE("%s: %s\n", dir, strerror(errno));
3423 return retval;
3424 }
3425
3426 if (!dump_from_fd) {
3427 dump_from_fd = dump_file_from_fd;
3428 }
3429 for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
3430 if ((d->d_name[0] == '.')
3431 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
3432 || (d->d_name[1] == '\0'))) {
3433 continue;
3434 }
3435 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
3436 (d->d_type == DT_DIR) ? "/" : "");
3437 if (!newpath) {
3438 retval = -errno;
3439 continue;
3440 }
3441 if (skip && (*skip)(newpath)) {
3442 continue;
3443 }
3444 if (d->d_type == DT_DIR) {
3445 int ret = dump_files("", newpath, skip, dump_from_fd);
3446 if (ret < 0) {
3447 retval = ret;
3448 }
3449 continue;
3450 }
3451 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
3452 if (fd.get() < 0) {
3453 retval = -1;
3454 printf("*** %s: %s\n", newpath, strerror(errno));
3455 continue;
3456 }
3457 (*dump_from_fd)(nullptr, newpath, fd.get());
3458 }
3459 closedir(dirp);
3460 if (!title.empty()) {
3461 printf("\n");
3462 }
3463 return retval;
3464}
3465
3466/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
3467 * it's possible to avoid issues where opening the file itself can get
3468 * stuck.
3469 */
3470int dump_file_from_fd(const char *title, const char *path, int fd) {
3471 if (PropertiesHelper::IsDryRun()) return 0;
3472
3473 int flags = fcntl(fd, F_GETFL);
3474 if (flags == -1) {
3475 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
3476 return -1;
3477 } else if (!(flags & O_NONBLOCK)) {
3478 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
3479 return -1;
3480 }
3481 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
3482}
3483
3484int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Nandana Dutt8d945c02019-08-14 13:30:07 +01003485 const CommandOptions& options, bool verbose_duration) {
3486 DurationReporter duration_reporter(title, false /* logcat_only */, verbose_duration);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003487
3488 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
3489
3490 /* TODO: for now we're simplifying the progress calculation by using the
3491 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
3492 * where its weight should be much higher proportionally to its timeout.
3493 * Ideally, it should use a options.EstimatedDuration() instead...*/
3494 UpdateProgress(options.Timeout());
3495
3496 return status;
3497}
3498
3499void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
3500 const CommandOptions& options, long dumpsysTimeoutMs) {
3501 long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
3502 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
3503 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
3504 RunCommand(title, dumpsys, options);
3505}
3506
3507int open_socket(const char *service) {
3508 int s = android_get_control_socket(service);
3509 if (s < 0) {
3510 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
3511 return -1;
3512 }
3513 fcntl(s, F_SETFD, FD_CLOEXEC);
3514
3515 // Set backlog to 0 to make sure that queue size will be minimum.
3516 // In Linux, because the minimum queue will be 1, connect() will be blocked
3517 // if the other clients already called connect() and the connection request was not accepted.
3518 if (listen(s, 0) < 0) {
3519 MYLOGE("listen(control socket): %s\n", strerror(errno));
3520 return -1;
3521 }
3522
3523 struct sockaddr addr;
3524 socklen_t alen = sizeof(addr);
Abhijeet Kaur2113cae2019-09-13 09:24:15 +01003525 int fd = accept4(s, &addr, &alen, SOCK_CLOEXEC);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003526
3527 // Close socket just after accept(), to make sure that connect() by client will get error
3528 // when the socket is used by the other services.
3529 // There is still a race condition possibility between accept and close, but there is no way
3530 // to close-on-accept atomically.
3531 // See detail; b/123306389#comment25
3532 close(s);
3533
3534 if (fd < 0) {
3535 MYLOGE("accept(control socket): %s\n", strerror(errno));
3536 return -1;
3537 }
3538
3539 return fd;
3540}
3541
3542/* redirect output to a service control socket */
3543bool redirect_to_socket(FILE* redirect, const char* service) {
3544 int fd = open_socket(service);
3545 if (fd == -1) {
3546 return false;
3547 }
3548 fflush(redirect);
3549 // TODO: handle dup2 failure
3550 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
3551 close(fd);
3552 return true;
3553}
3554
3555// TODO: should call is_valid_output_file and/or be merged into it.
3556void create_parent_dirs(const char *path) {
3557 char *chp = const_cast<char *> (path);
3558
3559 /* skip initial slash */
3560 if (chp[0] == '/')
3561 chp++;
3562
3563 /* create leading directories, if necessary */
3564 struct stat dir_stat;
3565 while (chp && chp[0]) {
3566 chp = strchr(chp, '/');
3567 if (chp) {
3568 *chp = 0;
3569 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
3570 MYLOGI("Creating directory %s\n", path);
3571 if (mkdir(path, 0770)) { /* drwxrwx--- */
3572 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
3573 } else if (chown(path, AID_SHELL, AID_SHELL)) {
3574 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
3575 }
3576 }
3577 *chp++ = '/';
3578 }
3579 }
3580}
3581
3582bool _redirect_to_file(FILE* redirect, char* path, int truncate_flag) {
3583 create_parent_dirs(path);
3584
3585 int fd = TEMP_FAILURE_RETRY(open(path,
3586 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
3587 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
3588 if (fd < 0) {
3589 MYLOGE("%s: %s\n", path, strerror(errno));
3590 return false;
3591 }
3592
3593 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
3594 close(fd);
3595 return true;
3596}
3597
3598bool redirect_to_file(FILE* redirect, char* path) {
3599 return _redirect_to_file(redirect, path, O_TRUNC);
3600}
3601
3602bool redirect_to_existing_file(FILE* redirect, char* path) {
3603 return _redirect_to_file(redirect, path, O_APPEND);
3604}
3605
3606void dump_route_tables() {
3607 DurationReporter duration_reporter("DUMP ROUTE TABLES");
3608 if (PropertiesHelper::IsDryRun()) return;
3609 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
3610 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
3611 FILE* fp = fopen(RT_TABLES_PATH, "re");
3612 if (!fp) {
3613 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
3614 return;
3615 }
3616 char table[16];
3617 // Each line has an integer (the table number), a space, and a string (the table name). We only
3618 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
3619 // Add a fixed max limit so this doesn't go awry.
3620 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
3621 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
3622 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
3623 }
3624 fclose(fp);
3625}
3626
3627// TODO: make this function thread safe if sections are generated in parallel.
3628void Dumpstate::UpdateProgress(int32_t delta_sec) {
3629 if (progress_ == nullptr) {
3630 MYLOGE("UpdateProgress: progress_ not set\n");
3631 return;
3632 }
3633
3634 // Always update progess so stats can be tuned...
Nandana Dutt402a8392019-06-14 14:25:13 +01003635 progress_->Inc(delta_sec);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003636
3637 // ...but only notifiy listeners when necessary.
3638 if (!options_->do_progress_updates) return;
3639
3640 int progress = progress_->Get();
3641 int max = progress_->GetMax();
Nandana Dutt402a8392019-06-14 14:25:13 +01003642 int percent = 100 * progress / max;
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003643
Nandana Dutt402a8392019-06-14 14:25:13 +01003644 if (last_reported_percent_progress_ > 0 && percent <= last_reported_percent_progress_) {
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003645 return;
3646 }
Nandana Dutt402a8392019-06-14 14:25:13 +01003647 last_reported_percent_progress_ = percent;
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003648
3649 if (control_socket_fd_ >= 0) {
3650 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
3651 fsync(control_socket_fd_);
3652 }
3653
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003654 if (listener_ != nullptr) {
Nandana Dutt235c6672019-11-14 15:22:32 +00003655 if (percent % 10 == 0) {
3656 // We don't want to spam logcat, so only log multiples of 10.
Abhijeet Kaured5d6a62019-10-07 15:02:05 +01003657 MYLOGD("Setting progress: %d/%d (%d%%)\n", progress, max, percent);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003658 } else {
3659 // stderr is ignored on normal invocations, but useful when calling
3660 // /system/bin/dumpstate directly for debuggging.
Abhijeet Kaured5d6a62019-10-07 15:02:05 +01003661 fprintf(stderr, "Setting progress: %d/%d (%d%%)\n", progress, max, percent);
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003662 }
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003663
3664 listener_->onProgress(percent);
3665 }
3666}
3667
3668void Dumpstate::TakeScreenshot(const std::string& path) {
3669 const std::string& real_path = path.empty() ? screenshot_path_ : path;
3670 int status =
3671 RunCommand("", {"/system/bin/screencap", "-p", real_path},
3672 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
3673 if (status == 0) {
3674 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
3675 } else {
3676 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
3677 }
Paul Chang0d2aad72020-02-13 20:04:03 +08003678 if (listener_ != nullptr) {
3679 // Show a visual indication to indicate screenshot is taken via
3680 // IDumpstateListener.onScreenshotTaken()
3681 listener_->onScreenshotTaken(status == 0);
3682 }
Abhijeet Kaurcf234e82019-07-01 14:53:55 +01003683}
3684
3685bool is_dir(const char* pathname) {
3686 struct stat info;
3687 if (stat(pathname, &info) == -1) {
3688 return false;
3689 }
3690 return S_ISDIR(info.st_mode);
3691}
3692
3693time_t get_mtime(int fd, time_t default_mtime) {
3694 struct stat info;
3695 if (fstat(fd, &info) == -1) {
3696 return default_mtime;
3697 }
3698 return info.st_mtime;
3699}