1f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross/*
2f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * Copyright (C) 2008 The Android Open Source Project
3f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross *
4f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * Licensed under the Apache License, Version 2.0 (the "License");
5f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * you may not use this file except in compliance with the License.
6f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * You may obtain a copy of the License at
7f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross *
8f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross *      http://www.apache.org/licenses/LICENSE-2.0
9f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross *
10f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * Unless required by applicable law or agreed to in writing, software
11f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * distributed under the License is distributed on an "AS IS" BASIS,
12f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * See the License for the specific language governing permissions and
14f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * limitations under the License.
15f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross */
16f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme
176c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzyn#define LOG_TAG "dumpstate"
18f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
192db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg#include <dirent.h>
20f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <errno.h>
21f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <fcntl.h>
22ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme#include <libgen.h>
23f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <limits.h>
248f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn#include <stdbool.h>
25f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <stdio.h>
26f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <stdlib.h>
27f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <string.h>
28e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair#include <sys/poll.h>
297dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris#include <sys/prctl.h>
30f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <sys/resource.h>
31f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <sys/stat.h>
32f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <sys/time.h>
33f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <sys/wait.h>
34f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <unistd.h>
357aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez
367aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez#include <chrono>
377aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez#include <functional>
387aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez#include <future>
398f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath#include <memory>
408f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath#include <regex>
418f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath#include <set>
428f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath#include <string>
437aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez#include <utility>
448f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath#include <vector>
45f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
4696c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme#include <android-base/file.h>
4796c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme#include <android-base/properties.h>
487aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez#include <android-base/scopeguard.h>
499dc117c415d0df0a3acd900709d05deabe975704Elliott Hughes#include <android-base/stringprintf.h>
50058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla#include <android-base/strings.h>
51aff684300a3b7d6984d3b3c1efddb810cd0205e7Andreas Gampe#include <android-base/unique_fd.h>
526f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme#include <android/hardware/dumpstate/1.0/IDumpstateDevice.h>
5344cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland#include <android/hidl/manager/1.0/IServiceManager.h>
546f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme#include <cutils/native_handle.h>
55f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include <cutils/properties.h>
56e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair#include <dumpsys.h>
5744cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland#include <hidl/ServiceManagement.h>
5875876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme#include <openssl/sha.h>
596c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzyn#include <private/android_filesystem_config.h>
606c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzyn#include <private/android_logger.h>
61e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair#include <serviceutils/PriorityDumper.h>
627aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez#include <utils/StrongPointer.h>
63f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme#include "DumpstateInternal.h"
64e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair#include "DumpstateSectionReporter.h"
6575876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme#include "DumpstateService.h"
66f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross#include "dumpstate.h"
676e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme
68cb7ef82aef52e766c45f65f446d02fd9356afea4Steven Morelandusing ::android::hardware::dumpstate::V1_0::IDumpstateDevice;
69e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing ::std::literals::chrono_literals::operator""ms;
70e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing ::std::literals::chrono_literals::operator""s;
71cb7ef82aef52e766c45f65f446d02fd9356afea4Steven Moreland
7247e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Leme// TODO: remove once moved to namespace
73e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::defaultServiceManager;
74e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::Dumpsys;
75e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::INVALID_OPERATION;
76e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::IServiceManager;
77e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::OK;
78e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::sp;
79e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::status_t;
80e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::String16;
81e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::String8;
82e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::TIMED_OUT;
83e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::UNKNOWN_ERROR;
84e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::Vector;
8547e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeusing android::os::dumpstate::CommandOptions;
8647e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeusing android::os::dumpstate::DumpFileToFd;
87e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::os::dumpstate::DumpstateSectionReporter;
8847e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeusing android::os::dumpstate::GetPidByName;
89e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairusing android::os::dumpstate::PropertiesHelper;
9047e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Leme
91f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross/* read before root is shed */
92f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossstatic char cmdline_buf[16384] = "(unknown)";
93f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossstatic const char *dump_traces_path = NULL;
94f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
951d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme// TODO: variables and functions below should be part of dumpstate object
961d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme
97635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemestatic std::set<std::string> mount_points;
98635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemevoid add_mountinfo();
9978f2c86235d5882a8dc84c85a1c1864062e5f3afFelipe Leme
1002a83daa8a3e1eab292dc1464bbe78f025f4bc0e9Todd Poynor#define PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops"
1017d0a762ecaf9f4d005f0f6db913034c2e084d362Mark Salyzyn#define ALT_PSTORE_LAST_KMSG "/sys/fs/pstore/console-ramoops-0"
102509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang#define BLK_DEV_SYS_DIR "/sys/block"
1032a83daa8a3e1eab292dc1464bbe78f025f4bc0e9Todd Poynor
104341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu#define RAFT_DIR "/data/misc/raft"
105e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme#define RECOVERY_DIR "/cache/recovery"
106d6ab01105bbd80dfa2fc2debc8e31d6422c378eeMark Salyzyn#define RECOVERY_DATA_DIR "/data/misc/recovery"
1071b34605e92179f2b1c37cc9f101d985750838d9dTianjie Xu#define UPDATE_ENGINE_LOG_DIR "/data/misc/update_engine_log"
1084d42dea08915ccbb61ca05903af5330d02d66755Mark Salyzyn#define LOGPERSIST_DATA_DIR "/data/misc/logd"
109d2991962b7120319a4fa63f1a93b100adaad5dbeDavid Brazdil#define PROFILE_DATA_DIR_CUR "/data/misc/profiles/cur"
110d2991962b7120319a4fa63f1a93b100adaad5dbeDavid Brazdil#define PROFILE_DATA_DIR_REF "/data/misc/profiles/ref"
1110816520c5cd60519d8e221ed92497aa5464e3039Erik Kline#define WLUTIL "/vendor/xbin/wlutil"
11236b4cdb2ddec610e52ab60ae1f6497ae3739f496Vishnu Nair#define WMTRACE_DATA_DIR "/data/misc/wmtrace"
1137dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris
1148f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath// TODO(narayan): Since this information has to be kept in sync
1158f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath// with tombstoned, we should just put it in a common header.
1168f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath//
1178f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath// File: system/core/debuggerd/tombstoned/tombstoned.cpp
118bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamathstatic const std::string TOMBSTONE_DIR = "/data/tombstones/";
119bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamathstatic const std::string TOMBSTONE_FILE_PREFIX = "tombstone_";
120bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamathstatic const std::string ANR_DIR = "/data/anr/";
121bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamathstatic const std::string ANR_FILE_PREFIX = "anr_";
1228f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
123e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme// TODO: temporary variables and functions used during C++ refactoring
124e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Lemestatic Dumpstate& ds = Dumpstate::GetInstance();
125678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemestatic int RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
126678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme                      const CommandOptions& options = CommandOptions::DEFAULT) {
127678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme    return ds.RunCommand(title, fullCommand, options);
128678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme}
129678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemestatic void RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
130bda15a00929b836a53bf03473b1ec36285e5944bFelipe Leme                       const CommandOptions& options = Dumpstate::DEFAULT_DUMPSYS,
1316921f80f26cb779d2982d2e37e14aeadbc8230b7Vishnu Nair                       long dumpsysTimeoutMs = 0) {
1326921f80f26cb779d2982d2e37e14aeadbc8230b7Vishnu Nair    return ds.RunDumpsys(title, dumpsysArgs, options, dumpsysTimeoutMs);
133678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme}
134678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemestatic int DumpFile(const std::string& title, const std::string& path) {
135678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme    return ds.DumpFile(title, path);
136678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme}
137e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
138e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme// Relative directory (inside the zip) for all files copied as-is into the bugreport.
139e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Lemestatic const std::string ZIP_ROOT_DIR = "FS";
140e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme
1417440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland// Must be hardcoded because dumpstate HAL implementation need SELinux access to it
1429fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Songstatic const std::string kDumpstateBoardPath = "/bugreports/";
143e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairstatic const std::string kProtoPath = "proto/";
144e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairstatic const std::string kProtoExt = ".proto";
1459fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Songstatic const std::string kDumpstateBoardFiles[] = {
1469fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song    "dumpstate_board.txt",
14795d6ca5df402889c4a9819e1422867b61283c0c8Felipe Leme    "dumpstate_board.bin"
1489fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song};
1499fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Songstatic const int NUM_OF_DUMPS = arraysize(kDumpstateBoardFiles);
1509fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song
1519ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Lemestatic constexpr char PROPERTY_EXTRA_OPTIONS[] = "dumpstate.options";
15296c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Lemestatic constexpr char PROPERTY_LAST_ID[] = "dumpstate.last_id";
153d071c6802a03031b26de7b92a76d03849681149bFelipe Lemestatic constexpr char PROPERTY_VERSION[] = "dumpstate.version";
154b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kallastatic constexpr char PROPERTY_EXTRA_TITLE[] = "dumpstate.options.title";
155b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kallastatic constexpr char PROPERTY_EXTRA_DESCRIPTION[] = "dumpstate.options.description";
1569ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme
157f029297f673ae06d219bd727a318a48b885db6fdFelipe Lemestatic const CommandOptions AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
158f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme
1598f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath/*
160bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath * Returns a vector of dump fds under |dir_path| with a given |file_prefix|.
161bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath * The returned vector is sorted by the mtimes of the dumps. If |limit_by_mtime|
162bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath * is set, the vector only contains files that were written in the last 30 minutes.
163d0d7695ecbfd12aaecc8aec66aacb487b116ac0bAndreas Gampe * If |limit_by_count| is set, the vector only contains the ten latest files.
1648f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath */
1655f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavezstatic std::vector<DumpData> GetDumpFds(const std::string& dir_path,
1665f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez                                        const std::string& file_prefix,
1675f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez                                        bool limit_by_mtime,
1685f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez                                        bool limit_by_count = true) {
1698f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    const time_t thirty_minutes_ago = ds.now_ - 60 * 30;
1708f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
171bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath    std::unique_ptr<DIR, decltype(&closedir)> dump_dir(opendir(dir_path.c_str()), closedir);
1728f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
173d05127172ce1f113230b1774119b6d54475dc158Luis Hector Chavez    if (dump_dir == nullptr) {
174d05127172ce1f113230b1774119b6d54475dc158Luis Hector Chavez        MYLOGW("Unable to open directory %s: %s\n", dir_path.c_str(), strerror(errno));
1755f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez        return std::vector<DumpData>();
176d05127172ce1f113230b1774119b6d54475dc158Luis Hector Chavez    }
177d05127172ce1f113230b1774119b6d54475dc158Luis Hector Chavez
1785f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    std::vector<DumpData> dump_data;
179bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath    struct dirent* entry = nullptr;
180bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath    while ((entry = readdir(dump_dir.get()))) {
181bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        if (entry->d_type != DT_REG) {
182bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath            continue;
1838f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        }
1848f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
185bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        const std::string base_name(entry->d_name);
186bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        if (base_name.find(file_prefix) != 0) {
1878f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            continue;
1888f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        }
1898f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
190bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        const std::string abs_path = dir_path + base_name;
191bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        android::base::unique_fd fd(
192bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath            TEMP_FAILURE_RETRY(open(abs_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)));
193bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        if (fd == -1) {
194d05127172ce1f113230b1774119b6d54475dc158Luis Hector Chavez            MYLOGW("Unable to open dump file %s: %s\n", abs_path.c_str(), strerror(errno));
195bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath            break;
196bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        }
197bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath
198bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        struct stat st = {};
199bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        if (fstat(fd, &st) == -1) {
200d05127172ce1f113230b1774119b6d54475dc158Luis Hector Chavez            MYLOGW("Unable to stat dump file %s: %s\n", abs_path.c_str(), strerror(errno));
2018f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            continue;
2028f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        }
2038f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
2043f31b6319f88ba81470c21711dacfb0b8bf11beeNarayan Kamath        if (limit_by_mtime && st.st_mtime < thirty_minutes_ago) {
205bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath            MYLOGI("Excluding stale dump file: %s\n", abs_path.c_str());
2068f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            continue;
2078f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        }
2088f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
2095f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez        dump_data.emplace_back(DumpData{abs_path, std::move(fd), st.st_mtime});
2108f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    }
2118f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
2125f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    // Sort in descending modification time so that we only keep the newest
2135f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    // reports if |limit_by_count| is true.
2145f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    std::sort(dump_data.begin(), dump_data.end(),
2155f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez              [](const DumpData& d1, const DumpData& d2) { return d1.mtime > d2.mtime; });
2168f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
2175f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    if (limit_by_count && dump_data.size() > 10) {
2185f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez        dump_data.erase(dump_data.begin() + 10, dump_data.end());
219d0d7695ecbfd12aaecc8aec66aacb487b116ac0bAndreas Gampe    }
220d0d7695ecbfd12aaecc8aec66aacb487b116ac0bAndreas Gampe
2215f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    return dump_data;
2228f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath}
2238f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
224bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamathstatic bool AddDumps(const std::vector<DumpData>::const_iterator start,
225bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath                     const std::vector<DumpData>::const_iterator end,
226bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath                     const char* type_name, const bool add_to_zip) {
2278f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    bool dumped = false;
228bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath    for (auto it = start; it != end; ++it) {
229bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        const std::string& name = it->name;
230bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        const int fd = it->fd;
2318f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        dumped = true;
2326b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath
2336b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // Seek to the beginning of the file before dumping any data. A given
2346b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // DumpData entry might be dumped multiple times in the report.
2356b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        //
2366b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // For example, the most recent ANR entry is dumped to the body of the
2376b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // main entry and it also shows up as a separate entry in the bugreport
2386b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // ZIP file.
2396b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        if (lseek(fd, 0, SEEK_SET) != static_cast<off_t>(0)) {
2406b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath            MYLOGE("Unable to add %s to zip file, lseek failed: %s\n", name.c_str(),
2416b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath                   strerror(errno));
2426b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        }
2436b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath
2448f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        if (ds.IsZipping() && add_to_zip) {
245e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            if (ds.AddZipEntryFromFd(ZIP_ROOT_DIR + name, fd, /* timeout = */ 0ms) != OK) {
2466b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath                MYLOGE("Unable to add %s to zip file, addZipEntryFromFd failed\n", name.c_str());
2478f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            }
2487dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris        } else {
2498f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            dump_file_from_fd(type_name, name.c_str(), fd);
2507dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris        }
2517dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris    }
2528f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
2538f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    return dumped;
2547dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris}
2557dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris
256635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme// for_each_pid() callback to get mount info about a process.
2574c2d66379753e2b7680811726424026b9e54b18aFelipe Lemevoid do_mountinfo(int pid, const char* name __attribute__((unused))) {
258635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    char path[PATH_MAX];
259635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme
260635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    // Gets the the content of the /proc/PID/ns/mnt link, so only unique mount points
261635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    // are added.
262f0922cc1786c0c2fbf44c10b0005243ecbb4227dNick Kralevich    snprintf(path, sizeof(path), "/proc/%d/ns/mnt", pid);
263635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    char linkname[PATH_MAX];
264635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    ssize_t r = readlink(path, linkname, PATH_MAX);
265635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    if (r == -1) {
266cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme        MYLOGE("Unable to read link for %s: %s\n", path, strerror(errno));
267635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme        return;
268635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    }
269635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    linkname[r] = '\0';
270635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme
271635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    if (mount_points.find(linkname) == mount_points.end()) {
272635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme        // First time this mount point was found: add it
273f0922cc1786c0c2fbf44c10b0005243ecbb4227dNick Kralevich        snprintf(path, sizeof(path), "/proc/%d/mountinfo", pid);
2741d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        if (ds.AddZipEntry(ZIP_ROOT_DIR + path, path)) {
275635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme            mount_points.insert(linkname);
276635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme        } else {
277cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme            MYLOGE("Unable to add mountinfo %s to zip file\n", path);
278635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme        }
279635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    }
280635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme}
281635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme
282635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemevoid add_mountinfo() {
2831d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!ds.IsZipping()) return;
284678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme    std::string title = "MOUNT INFO";
285635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme    mount_points.clear();
28646b85da716a32f285fe1222e9978beacc8697d09Felipe Leme    DurationReporter duration_reporter(title, true);
287678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme    for_each_pid(do_mountinfo, nullptr);
288678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme    MYLOGD("%s: %d entries added to zip file\n", title.c_str(), (int)mount_points.size());
289635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme}
290635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme
2912db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågstatic void dump_dev_files(const char *title, const char *driverpath, const char *filename)
2922db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg{
2932db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    DIR *d;
2942db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    struct dirent *de;
2952db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    char path[PATH_MAX];
2962db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg
2972db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    d = opendir(driverpath);
2982db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    if (d == NULL) {
2992db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg        return;
3002db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    }
3012db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg
3022db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    while ((de = readdir(d))) {
3032db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg        if (de->d_type != DT_LNK) {
3042db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg            continue;
3052db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg        }
3062db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg        snprintf(path, sizeof(path), "%s/%s/%s", driverpath, de->d_name, filename);
307b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme        DumpFile(title, path);
3082db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    }
3092db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg
3102db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    closedir(d);
3112db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg}
3122db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg
313068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
314068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
315068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian// dump anrd's trace and add to the zip file.
316068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian// 1. check if anrd is running on this device.
317068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian// 2. send a SIGUSR1 to its pid which will dump anrd's trace.
318068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian// 3. wait until the trace generation completes and add to the zip file.
319068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianstatic bool dump_anrd_trace() {
320068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    unsigned int pid;
321068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    char buf[50], path[PATH_MAX];
322068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    struct dirent *trace;
323068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    struct stat st;
324068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    DIR *trace_dir;
325afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian    int retry = 5;
326afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian    long max_ctime = 0, old_mtime;
327068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    long long cur_size = 0;
328068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    const char *trace_path = "/data/misc/anrd/";
329068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
3301d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!ds.IsZipping()) {
3311d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        MYLOGE("Not dumping anrd trace because it's not a zipped bugreport\n");
332068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        return false;
333068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    }
334068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
335068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    // find anrd's pid if it is running.
33661ffcf73d50dbed5b52265e79bb73abf1849324dEcco Park    pid = GetPidByName("/system/xbin/anrd");
337068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
338068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    if (pid > 0) {
339afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian        if (stat(trace_path, &st) == 0) {
340afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian            old_mtime = st.st_mtime;
341afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian        } else {
342afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian            MYLOGE("Failed to find: %s\n", trace_path);
343afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian            return false;
344afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian        }
345afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian
346068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        // send SIGUSR1 to the anrd to generate a trace.
347068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        sprintf(buf, "%u", pid);
348b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme        if (RunCommand("ANRD_DUMP", {"kill", "-SIGUSR1", buf},
34930dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme                       CommandOptions::WithTimeout(1).Build())) {
350068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            MYLOGE("anrd signal timed out. Please manually collect trace\n");
351068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            return false;
352068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        }
353068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
354afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian        while (retry-- > 0 && old_mtime == st.st_mtime) {
355afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian            sleep(1);
356afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian            stat(trace_path, &st);
357afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian        }
358afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian
359afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian        if (retry < 0 && old_mtime == st.st_mtime) {
360afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian            MYLOGE("Failed to stat %s or trace creation timeout\n", trace_path);
361afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian            return false;
362afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian        }
363afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian
364068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        // identify the trace file by its creation time.
365068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        if (!(trace_dir = opendir(trace_path))) {
366068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            MYLOGE("Can't open trace file under %s\n", trace_path);
367068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        }
368068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        while ((trace = readdir(trace_dir))) {
369068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            if (strcmp(trace->d_name, ".") == 0
370068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    || strcmp(trace->d_name, "..") == 0) {
371068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                continue;
372068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            }
373068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            sprintf(path, "%s%s", trace_path, trace->d_name);
374068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            if (stat(path, &st) == 0) {
375068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                if (st.st_ctime > max_ctime) {
376068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    max_ctime = st.st_ctime;
377068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    sprintf(buf, "%s", trace->d_name);
378068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                }
379068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            }
380068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        }
381068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        closedir(trace_dir);
382068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
383068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        // Wait until the dump completes by checking the size of the trace.
384068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        if (max_ctime > 0) {
385068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            sprintf(path, "%s%s", trace_path, buf);
386068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            while(true) {
387068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                sleep(1);
388068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                if (stat(path, &st) == 0) {
389068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    if (st.st_size == cur_size) {
390068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                        break;
391068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    } else if (st.st_size > cur_size) {
392068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                        cur_size = st.st_size;
393068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    } else {
394068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                        return false;
395068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    }
396068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                } else {
397068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    MYLOGE("Cant stat() %s anymore\n", path);
398068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    return false;
399068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                }
400068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            }
401068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            // Add to the zip file.
4021d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme            if (!ds.AddZipEntry("anrd_trace.txt", path)) {
403068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                MYLOGE("Unable to add anrd_trace file %s to zip file\n", path);
404068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            } else {
405068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                if (remove(path)) {
406068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                    MYLOGE("Error removing anrd_trace file %s: %s", path, strerror(errno));
407068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                }
408068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian                return true;
409068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            }
410068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        } else {
411068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian            MYLOGE("Can't stats any trace file under %s\n", trace_path);
412068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian        }
413068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    }
414068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian    return false;
415068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian}
416068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian
417efd7e27569b69ed854ed75fca40fc638e3c0268bFelipe Lemestatic void dump_systrace() {
4181d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!ds.IsZipping()) {
4191d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        MYLOGD("Not dumping systrace because it's not a zipped bugreport\n");
42071a74ac75c8687195d27642fa0db31a796102c59Felipe Leme        return;
42171a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    }
422bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme    std::string systrace_path = ds.GetPath("-systrace.txt");
42314e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme    if (systrace_path.empty()) {
42414e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme        MYLOGE("Not dumping systrace because path is empty\n");
42514e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme        return;
42614e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme    }
42771a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    const char* path = "/sys/kernel/debug/tracing/tracing_on";
42871a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    long int is_tracing;
42971a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    if (read_file_as_long(path, &is_tracing)) {
43071a74ac75c8687195d27642fa0db31a796102c59Felipe Leme        return; // error already logged
43171a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    }
43271a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    if (is_tracing <= 0) {
43371a74ac75c8687195d27642fa0db31a796102c59Felipe Leme        MYLOGD("Skipping systrace because '%s' content is '%ld'\n", path, is_tracing);
43471a74ac75c8687195d27642fa0db31a796102c59Felipe Leme        return;
43571a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    }
43671a74ac75c8687195d27642fa0db31a796102c59Felipe Leme
43714e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme    MYLOGD("Running '/system/bin/atrace --async_dump -o %s', which can take several minutes",
43814e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme            systrace_path.c_str());
439b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    if (RunCommand("SYSTRACE", {"/system/bin/atrace", "--async_dump", "-o", systrace_path},
44030dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme                   CommandOptions::WithTimeout(120).Build())) {
44114e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme        MYLOGE("systrace timed out, its zip entry will be incomplete\n");
442c7fe8fe5b525a1a071af92f3ebbeef2f6d4b06afFelipe Leme        // TODO: RunCommand tries to kill the process, but atrace doesn't die
44330dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        // peacefully; ideally, we should call strace to stop itself, but there is no such option
44430dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        // yet (just a --async_stop, which stops and dump
445b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme        // if (RunCommand("SYSTRACE", {"/system/bin/atrace", "--kill"})) {
44630dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        //   MYLOGE("could not stop systrace ");
44730dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        // }
44814e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme    }
4491d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!ds.AddZipEntry("systrace.txt", systrace_path)) {
45014e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme        MYLOGE("Unable to add systrace file %s to zip file\n", systrace_path.c_str());
45171a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    } else {
45214e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme        if (remove(systrace_path.c_str())) {
45314e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme            MYLOGE("Error removing systrace file %s: %s", systrace_path.c_str(), strerror(errno));
45414e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme        }
45571a74ac75c8687195d27642fa0db31a796102c59Felipe Leme    }
45671a74ac75c8687195d27642fa0db31a796102c59Felipe Leme}
45771a74ac75c8687195d27642fa0db31a796102c59Felipe Leme
458efd7e27569b69ed854ed75fca40fc638e3c0268bFelipe Lemestatic void dump_raft() {
459f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme    if (PropertiesHelper::IsUserBuild()) {
460341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu        return;
461341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu    }
462341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu
4631d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    std::string raft_path = ds.GetPath("-raft_log.txt");
4641d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (raft_path.empty()) {
4651d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        MYLOGD("raft_path is empty\n");
466341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu        return;
467341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu    }
468f0e78d4391fd5cea487af116106a7887720b950eWei Liu
469f0e78d4391fd5cea487af116106a7887720b950eWei Liu    struct stat s;
470f0e78d4391fd5cea487af116106a7887720b950eWei Liu    if (stat(RAFT_DIR, &s) != 0 || !S_ISDIR(s.st_mode)) {
471f0e78d4391fd5cea487af116106a7887720b950eWei Liu        MYLOGD("%s does not exist or is not a directory\n", RAFT_DIR);
472f0e78d4391fd5cea487af116106a7887720b950eWei Liu        return;
473f0e78d4391fd5cea487af116106a7887720b950eWei Liu    }
474f0e78d4391fd5cea487af116106a7887720b950eWei Liu
47530dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme    CommandOptions options = CommandOptions::WithTimeout(600).Build();
4761d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!ds.IsZipping()) {
4771d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        // Write compressed and encoded raft logs to stdout if it's not a zipped bugreport.
478b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme        RunCommand("RAFT LOGS", {"logcompressor", "-r", RAFT_DIR}, options);
479341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu        return;
480341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu    }
481341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu
4821d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    RunCommand("RAFT LOGS", {"logcompressor", "-n", "-r", RAFT_DIR, "-o", raft_path}, options);
4831d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!ds.AddZipEntry("raft_log.txt", raft_path)) {
4841d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        MYLOGE("Unable to add raft log %s to zip file\n", raft_path.c_str());
485341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu    } else {
4861d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        if (remove(raft_path.c_str())) {
4871d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme            MYLOGE("Error removing raft file %s: %s\n", raft_path.c_str(), strerror(errno));
488341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu        }
489341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu    }
490341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu}
491341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu
492326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzynstatic bool skip_not_stat(const char *path) {
493326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    static const char stat[] = "/stat";
494326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    size_t len = strlen(path);
495326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    if (path[len - 1] == '/') { /* Directory? */
496326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        return false;
497326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    }
498326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    return strcmp(path + len - sizeof(stat) + 1, stat); /* .../stat? */
499326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn}
500326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn
5014c2d66379753e2b7680811726424026b9e54b18aFelipe Lemestatic bool skip_none(const char* path __attribute__((unused))) {
502e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme    return false;
503e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme}
504e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
5058f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzynunsigned long worst_write_perf = 20000; /* in KB/s */
506326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn
50701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
50801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//  stat offsets
50901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// Name            units         description
51001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// ----            -----         -----------
51101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read I/Os       requests      number of read I/Os processed
51201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_READ_IOS      0
51301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read merges     requests      number of read I/Os merged with in-queue I/O
51401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_READ_MERGES   1
51501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read sectors    sectors       number of sectors read
51601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_READ_SECTORS  2
51701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read ticks      milliseconds  total wait time for read requests
51801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_READ_TICKS    3
51901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// write I/Os      requests      number of write I/Os processed
52001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_WRITE_IOS     4
52101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// write merges    requests      number of write I/Os merged with in-queue I/O
52201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_WRITE_MERGES  5
52301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// write sectors   sectors       number of sectors written
52401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_WRITE_SECTORS 6
52501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// write ticks     milliseconds  total wait time for write requests
52601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_WRITE_TICKS   7
52701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// in_flight       requests      number of I/Os currently in flight
52801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_IN_FLIGHT     8
52901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// io_ticks        milliseconds  total time this block device has been active
53001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_IO_TICKS      9
53101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// time_in_queue   milliseconds  total wait time for all requests
53201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_IN_QUEUE     10
53301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define __STAT_NUMBER_FIELD 11
53401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
53501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read I/Os, write I/Os
53601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// =====================
53701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
53801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// These values increment when an I/O request completes.
53901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
54001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read merges, write merges
54101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// =========================
54201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
54301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// These values increment when an I/O request is merged with an
54401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// already-queued I/O request.
54501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
54601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read sectors, write sectors
54701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// ===========================
54801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
54901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// These values count the number of sectors read from or written to this
55001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// block device.  The "sectors" in question are the standard UNIX 512-byte
55101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// sectors, not any device- or filesystem-specific block size.  The
55201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// counters are incremented when the I/O completes.
55301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define SECTOR_SIZE 512
55401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
55501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// read ticks, write ticks
55601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// =======================
55701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
55801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// These values count the number of milliseconds that I/O requests have
55901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// waited on this block device.  If there are multiple I/O requests waiting,
56001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// these values will increase at a rate greater than 1000/second; for
56101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// example, if 60 read requests wait for an average of 30 ms, the read_ticks
56201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// field will increase by 60*30 = 1800.
56301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
56401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// in_flight
56501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// =========
56601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
56701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// This value counts the number of I/O requests that have been issued to
56801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// the device driver but have not yet completed.  It does not include I/O
56901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// requests that are in the queue but not yet issued to the device driver.
57001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
57101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// io_ticks
57201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// ========
57301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
57401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// This value counts the number of milliseconds during which the device has
57501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// had I/O requests queued.
57601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
57701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// time_in_queue
57801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// =============
57901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
58001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// This value counts the number of milliseconds that I/O requests have waited
58101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// on this block device.  If there are multiple I/O requests waiting, this
58201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// value will increase as the product of the number of milliseconds times the
58301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn// number of requests waiting (see "read ticks" above for an example).
58401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn#define S_TO_MS 1000
58501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn//
58601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn
587326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzynstatic int dump_stat_from_fd(const char *title __unused, const char *path, int fd) {
58801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn    unsigned long long fields[__STAT_NUMBER_FIELD];
589326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    bool z;
590326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    char *cp, *buffer = NULL;
591326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    size_t i = 0;
592326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    FILE *fp = fdopen(fd, "rb");
593326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    getline(&buffer, &i, fp);
594326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    fclose(fp);
595326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    if (!buffer) {
596326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        return -errno;
597326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    }
598326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    i = strlen(buffer);
599326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    while ((i > 0) && (buffer[i - 1] == '\n')) {
600326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        buffer[--i] = '\0';
601326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    }
602326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    if (!*buffer) {
603326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        free(buffer);
604326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        return 0;
605326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    }
606326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    z = true;
607326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    for (cp = buffer, i = 0; i < (sizeof(fields) / sizeof(fields[0])); ++i) {
60801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        fields[i] = strtoull(cp, &cp, 10);
609326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        if (fields[i] != 0) {
610326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn            z = false;
611326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        }
612326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    }
613326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    if (z) { /* never accessed */
614326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        free(buffer);
615326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn        return 0;
616326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    }
617326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn
618509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang    if (!strncmp(path, BLK_DEV_SYS_DIR, sizeof(BLK_DEV_SYS_DIR) - 1)) {
619509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        path += sizeof(BLK_DEV_SYS_DIR) - 1;
620326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    }
6211dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang
6221dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang    printf("%-30s:%9s%9s%9s%9s%9s%9s%9s%9s%9s%9s%9s\n%-30s:\t%s\n", "Block-Dev",
6231dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang           "R-IOs", "R-merg", "R-sect", "R-wait", "W-IOs", "W-merg", "W-sect",
6241dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang           "W-wait", "in-fli", "activ", "T-wait", path, buffer);
625326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    free(buffer);
626326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn
62701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn    if (fields[__STAT_IO_TICKS]) {
62801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        unsigned long read_perf = 0;
62901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        unsigned long read_ios = 0;
63001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        if (fields[__STAT_READ_TICKS]) {
63101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn            unsigned long long divisor = fields[__STAT_READ_TICKS]
63201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                                       * fields[__STAT_IO_TICKS];
63301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn            read_perf = ((unsigned long long)SECTOR_SIZE
63401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                           * fields[__STAT_READ_SECTORS]
63501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
63601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                                        / divisor;
63701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn            read_ios = ((unsigned long long)S_TO_MS * fields[__STAT_READ_IOS]
63801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
63901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                                        / divisor;
64001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        }
64101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn
64201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        unsigned long write_perf = 0;
64301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        unsigned long write_ios = 0;
64401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        if (fields[__STAT_WRITE_TICKS]) {
64501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn            unsigned long long divisor = fields[__STAT_WRITE_TICKS]
64601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                                       * fields[__STAT_IO_TICKS];
64701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn            write_perf = ((unsigned long long)SECTOR_SIZE
64801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                           * fields[__STAT_WRITE_SECTORS]
64901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
65001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                                        / divisor;
65101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn            write_ios = ((unsigned long long)S_TO_MS * fields[__STAT_WRITE_IOS]
65201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                           * fields[__STAT_IN_QUEUE] + (divisor >> 1))
65301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                                        / divisor;
65401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        }
65501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn
65601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        unsigned queue = (fields[__STAT_IN_QUEUE]
65701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                             + (fields[__STAT_IO_TICKS] >> 1))
65801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn                                 / fields[__STAT_IO_TICKS];
65901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn
66001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        if (!write_perf && !write_ios) {
6611dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang            printf("%-30s: perf(ios) rd: %luKB/s(%lu/s) q: %u\n", path, read_perf, read_ios, queue);
66201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        } else {
6631dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang            printf("%-30s: perf(ios) rd: %luKB/s(%lu/s) wr: %luKB/s(%lu/s) q: %u\n", path, read_perf,
664d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme                   read_ios, write_perf, write_ios, queue);
66501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        }
66601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn
66701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        /* bugreport timeout factor adjustment */
66801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        if ((write_perf > 1) && (write_perf < worst_write_perf)) {
66901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn            worst_write_perf = write_perf;
67001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn        }
6718f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn    }
672326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn    return 0;
673326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn}
674326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn
675be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chenstatic const long MINIMUM_LOGCAT_TIMEOUT_MS = 50000;
676be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen
677be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen/* timeout in ms to read a list of buffers */
678be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chenstatic unsigned long logcat_timeout(const std::vector<std::string>& buffers) {
679be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    unsigned long timeout_ms = 0;
680be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    for (const auto& buffer : buffers) {
681be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen        log_id_t id = android_name_to_log_id(buffer.c_str());
682be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen        unsigned long property_size = __android_logger_get_buffer_size(id);
683be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen        /* Engineering margin is ten-fold our guess */
684be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen        timeout_ms += 10 * (property_size + worst_write_perf) / worst_write_perf;
685be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    }
686be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    return timeout_ms > MINIMUM_LOGCAT_TIMEOUT_MS ? timeout_ms : MINIMUM_LOGCAT_TIMEOUT_MS;
6878f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn}
6888f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn
6892b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Lemevoid Dumpstate::PrintHeader() const {
69096c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    std::string build, fingerprint, radio, bootloader, network;
69196c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    char date[80];
69296c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme
69396c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    build = android::base::GetProperty("ro.build.display.id", "(unknown)");
69496c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    fingerprint = android::base::GetProperty("ro.build.fingerprint", "(unknown)");
69596c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    radio = android::base::GetProperty("gsm.version.baseband", "(unknown)");
69696c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    bootloader = android::base::GetProperty("ro.bootloader", "(unknown)");
69796c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    network = android::base::GetProperty("gsm.operator.alpha", "(unknown)");
698bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme    strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now_));
699f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
700d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
701d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("== dumpstate: %s\n", date);
702d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
703f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
704d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("\n");
705d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Build: %s\n", build.c_str());
70696c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    // NOTE: fingerprint entry format is important for other tools.
707d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Build fingerprint: '%s'\n", fingerprint.c_str());
708d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Bootloader: %s\n", bootloader.c_str());
709d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Radio: %s\n", radio.c_str());
710d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Network: %s\n", network.c_str());
711f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
712d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Kernel: ");
713f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme    DumpFileToFd(STDOUT_FILENO, "", "/proc/version");
714d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Command line: %s\n", strtok(cmdline_buf, "\n"));
7157709f8a5e62a67c6df06f68bddcc2a1036bd62bbFelipe Leme    printf("Uptime: ");
7167709f8a5e62a67c6df06f68bddcc2a1036bd62bbFelipe Leme    RunCommandToFd(STDOUT_FILENO, "", {"uptime", "-p"},
7177709f8a5e62a67c6df06f68bddcc2a1036bd62bbFelipe Leme                   CommandOptions::WithTimeout(1).Always().Build());
718d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Bugreport format version: %s\n", version_.c_str());
719d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("Dumpstate info: id=%d pid=%d dry_run=%d args=%s extra_options=%s\n", id_, pid_,
720d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme           PropertiesHelper::IsDryRun(), args_.c_str(), extra_options_.c_str());
721d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("\n");
72278f2c86235d5882a8dc84c85a1c1864062e5f3afFelipe Leme}
72378f2c86235d5882a8dc84c85a1c1864062e5f3afFelipe Leme
72424b66eed1acd08a975546b57198940f4de9250ebFelipe Leme// List of file extensions that can cause a zip file attachment to be rejected by some email
72524b66eed1acd08a975546b57198940f4de9250ebFelipe Leme// service providers.
72624b66eed1acd08a975546b57198940f4de9250ebFelipe Lemestatic const std::set<std::string> PROBLEMATIC_FILE_EXTENSIONS = {
72724b66eed1acd08a975546b57198940f4de9250ebFelipe Leme      ".ade", ".adp", ".bat", ".chm", ".cmd", ".com", ".cpl", ".exe", ".hta", ".ins", ".isp",
72824b66eed1acd08a975546b57198940f4de9250ebFelipe Leme      ".jar", ".jse", ".lib", ".lnk", ".mde", ".msc", ".msp", ".mst", ".pif", ".scr", ".sct",
72924b66eed1acd08a975546b57198940f4de9250ebFelipe Leme      ".shb", ".sys", ".vb",  ".vbe", ".vbs", ".vxd", ".wsc", ".wsf", ".wsh"
73024b66eed1acd08a975546b57198940f4de9250ebFelipe Leme};
73124b66eed1acd08a975546b57198940f4de9250ebFelipe Leme
732e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nairstatus_t Dumpstate::AddZipEntryFromFd(const std::string& entry_name, int fd,
733e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                                      std::chrono::milliseconds timeout = 0ms) {
7341d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!IsZipping()) {
7351d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        MYLOGD("Not adding zip entry %s from fd because it's not a zipped bugreport\n",
7361d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme               entry_name.c_str());
737e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        return INVALID_OPERATION;
738111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme    }
73924b66eed1acd08a975546b57198940f4de9250ebFelipe Leme    std::string valid_name = entry_name;
74024b66eed1acd08a975546b57198940f4de9250ebFelipe Leme
74124b66eed1acd08a975546b57198940f4de9250ebFelipe Leme    // Rename extension if necessary.
742cb057c2e6bf23b43df49282c0db26b663e4535f7Chih-Hung Hsieh    size_t idx = entry_name.rfind('.');
74324b66eed1acd08a975546b57198940f4de9250ebFelipe Leme    if (idx != std::string::npos) {
74424b66eed1acd08a975546b57198940f4de9250ebFelipe Leme        std::string extension = entry_name.substr(idx);
74524b66eed1acd08a975546b57198940f4de9250ebFelipe Leme        std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
74624b66eed1acd08a975546b57198940f4de9250ebFelipe Leme        if (PROBLEMATIC_FILE_EXTENSIONS.count(extension) != 0) {
74724b66eed1acd08a975546b57198940f4de9250ebFelipe Leme            valid_name = entry_name + ".renamed";
74824b66eed1acd08a975546b57198940f4de9250ebFelipe Leme            MYLOGI("Renaming entry %s to %s\n", entry_name.c_str(), valid_name.c_str());
74924b66eed1acd08a975546b57198940f4de9250ebFelipe Leme        }
75024b66eed1acd08a975546b57198940f4de9250ebFelipe Leme    }
75124b66eed1acd08a975546b57198940f4de9250ebFelipe Leme
7526fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme    // Logging statement  below is useful to time how long each entry takes, but it's too verbose.
7536fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme    // MYLOGD("Adding zip entry %s\n", entry_name.c_str());
754c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme    int32_t err = zip_writer_->StartEntryWithTime(valid_name.c_str(), ZipWriter::kCompress,
755c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme                                                  get_mtime(fd, ds.now_));
7561d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (err != 0) {
757c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme        MYLOGE("zip_writer_->StartEntryWithTime(%s): %s\n", valid_name.c_str(),
7581d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme               ZipWriter::ErrorCodeString(err));
759e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        return UNKNOWN_ERROR;
760e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme    }
761e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    auto start = std::chrono::steady_clock::now();
762e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    auto end = start + timeout;
763e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    struct pollfd pfd = {fd, POLLIN};
764e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
765770410dcf2f72cf4e806442263e63719a0be0f5aFelipe Leme    std::vector<uint8_t> buffer(65536);
766e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme    while (1) {
767e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        if (timeout.count() > 0) {
768e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            // lambda to recalculate the timeout.
769e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            auto time_left_ms = [end]() {
770e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                auto now = std::chrono::steady_clock::now();
771e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - now);
772e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                return std::max(diff.count(), 0LL);
773e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            };
774e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair
775e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            int rc = TEMP_FAILURE_RETRY(poll(&pfd, 1, time_left_ms()));
776e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            if (rc < 0) {
777e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                MYLOGE("Error in poll while adding from fd to zip entry %s:%s", entry_name.c_str(),
778e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                       strerror(errno));
779e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                return -errno;
780e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            } else if (rc == 0) {
781e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                MYLOGE("Timed out adding from fd to zip entry %s:%s Timeout:%lldms",
782e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                       entry_name.c_str(), strerror(errno), timeout.count());
783e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                return TIMED_OUT;
784e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            }
785e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        }
786e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair
78722200401c000c556ff7ed6d100d4f57e18ebb24fZach Riggle        ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
788e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme        if (bytes_read == 0) {
789e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme            break;
790e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme        } else if (bytes_read == -1) {
791cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme            MYLOGE("read(%s): %s\n", entry_name.c_str(), strerror(errno));
792e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            return -errno;
793e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme        }
794c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme        err = zip_writer_->WriteBytes(buffer.data(), bytes_read);
795e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme        if (err) {
796c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme            MYLOGE("zip_writer_->WriteBytes(): %s\n", ZipWriter::ErrorCodeString(err));
797e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            return UNKNOWN_ERROR;
798e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme        }
799e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme    }
800e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
801c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme    err = zip_writer_->FinishEntry();
8021d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (err != 0) {
803c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme        MYLOGE("zip_writer_->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err));
804e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        return UNKNOWN_ERROR;
805e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme    }
806e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
807e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    return OK;
808e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme}
809e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
8101d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemebool Dumpstate::AddZipEntry(const std::string& entry_name, const std::string& entry_path) {
8111d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    android::base::unique_fd fd(
8121d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        TEMP_FAILURE_RETRY(open(entry_path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
813aff684300a3b7d6984d3b3c1efddb810cd0205e7Andreas Gampe    if (fd == -1) {
814cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme        MYLOGE("open(%s): %s\n", entry_path.c_str(), strerror(errno));
815e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme        return false;
816e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme    }
817e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
818e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    return (AddZipEntryFromFd(entry_name, fd.get()) == OK);
819e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme}
820e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
821e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme/* adds a file to the existing zipped bugreport */
8224c2d66379753e2b7680811726424026b9e54b18aFelipe Lemestatic int _add_file_from_fd(const char* title __attribute__((unused)), const char* path, int fd) {
823e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    return (ds.AddZipEntryFromFd(ZIP_ROOT_DIR + path, fd) == OK) ? 0 : 1;
824e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme}
825e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
8261d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemevoid Dumpstate::AddDir(const std::string& dir, bool recursive) {
8271d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!IsZipping()) {
8281d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        MYLOGD("Not adding dir %s because it's not a zipped bugreport\n", dir.c_str());
829111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme        return;
830111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme    }
831678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme    MYLOGD("Adding dir %s (recursive: %d)\n", dir.c_str(), recursive);
83246b85da716a32f285fe1222e9978beacc8697d09Felipe Leme    DurationReporter duration_reporter(dir, true);
833678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme    dump_files("", dir.c_str(), recursive ? skip_none : is_dir, _add_file_from_fd);
834e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme}
835e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme
8361d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemebool Dumpstate::AddTextZipEntry(const std::string& entry_name, const std::string& content) {
8371d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!IsZipping()) {
8381d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme        MYLOGD("Not adding text zip entry %s because it's not a zipped bugreport\n",
8391d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme               entry_name.c_str());
840111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme        return false;
841111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme    }
842cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme    MYLOGD("Adding zip text entry %s\n", entry_name.c_str());
843c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme    int32_t err = zip_writer_->StartEntryWithTime(entry_name.c_str(), ZipWriter::kCompress, ds.now_);
8441d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (err != 0) {
845c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme        MYLOGE("zip_writer_->StartEntryWithTime(%s): %s\n", entry_name.c_str(),
8461d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme               ZipWriter::ErrorCodeString(err));
847809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme        return false;
848809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme    }
849809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme
850c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme    err = zip_writer_->WriteBytes(content.c_str(), content.length());
8511d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (err != 0) {
852c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme        MYLOGE("zip_writer_->WriteBytes(%s): %s\n", entry_name.c_str(),
8531d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme               ZipWriter::ErrorCodeString(err));
854809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme        return false;
855809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme    }
856809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme
857c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme    err = zip_writer_->FinishEntry();
8581d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (err != 0) {
859c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme        MYLOGE("zip_writer_->FinishEntry(): %s\n", ZipWriter::ErrorCodeString(err));
860809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme        return false;
861809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme    }
862809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme
863809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme    return true;
864809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme}
865809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme
8666ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Lemestatic void DoKmsg() {
8676ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    struct stat st;
8686ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    if (!stat(PSTORE_LAST_KMSG, &st)) {
8696ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        /* Also TODO: Make console-ramoops CAP_SYSLOG protected. */
8706ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        DumpFile("LAST KMSG", PSTORE_LAST_KMSG);
8716ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    } else if (!stat(ALT_PSTORE_LAST_KMSG, &st)) {
8726ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        DumpFile("LAST KMSG", ALT_PSTORE_LAST_KMSG);
8736ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    } else {
8746ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        /* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */
8756ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        DumpFile("LAST KMSG", "/proc/last_kmsg");
8766ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    }
8776ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme}
8786ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme
8794a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakoustatic void DoKernelLogcat() {
880be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    unsigned long timeout_ms = logcat_timeout({"kernel"});
8814a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou    RunCommand(
8824a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        "KERNEL LOG",
8834a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        {"logcat", "-b", "kernel", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
8844a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        CommandOptions::WithTimeoutInMs(timeout_ms).Build());
8854a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou}
8864a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou
8876ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Lemestatic void DoLogcat() {
8886921f80f26cb779d2982d2e37e14aeadbc8230b7Vishnu Nair    unsigned long timeout_ms;
8896ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    // DumpFile("EVENT LOG TAGS", "/etc/event-log-tags");
8906ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    // calculate timeout
891be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    timeout_ms = logcat_timeout({"main", "system", "crash"});
892ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak    RunCommand("SYSTEM LOG",
8936921f80f26cb779d2982d2e37e14aeadbc8230b7Vishnu Nair               {"logcat", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
8946921f80f26cb779d2982d2e37e14aeadbc8230b7Vishnu Nair               CommandOptions::WithTimeoutInMs(timeout_ms).Build());
895be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    timeout_ms = logcat_timeout({"events"});
8964a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou    RunCommand(
8974a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        "EVENT LOG",
8984a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        {"logcat", "-b", "events", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
8994a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        CommandOptions::WithTimeoutInMs(timeout_ms).Build());
900be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    timeout_ms = logcat_timeout({"stats"});
901be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    RunCommand(
902be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen        "STATS LOG",
903be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen        {"logcat", "-b", "stats", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
904be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen        CommandOptions::WithTimeoutInMs(timeout_ms).Build());
905be3bbc17db0fd09de2b2134a2a9c32ea7357db0eYao Chen    timeout_ms = logcat_timeout({"radio"});
9064a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou    RunCommand(
9074a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        "RADIO LOG",
9084a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        {"logcat", "-b", "radio", "-v", "threadtime", "-v", "printable", "-v", "uid", "-d", "*:v"},
9094a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        CommandOptions::WithTimeoutInMs(timeout_ms).Build());
9106ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme
9116ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    RunCommand("LOG STATISTICS", {"logcat", "-b", "all", "-S"});
9126ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme
9136ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    /* kernels must set CONFIG_PSTORE_PMSG, slice up pstore with device tree */
9144a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou    RunCommand("LAST LOGCAT", {"logcat", "-L", "-b", "all", "-v", "threadtime", "-v", "printable",
9154a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou                               "-v", "uid", "-d", "*:v"});
9166ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme}
9176ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme
918a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran Cstatic void DumpIpTablesAsRoot() {
919b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("IPTABLES", {"iptables", "-L", "-nvx"});
920b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("IP6TABLES", {"ip6tables", "-L", "-nvx"});
92132af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline    RunCommand("IPTABLES NAT", {"iptables", "-t", "nat", "-L", "-nvx"});
922c0808155fd10d2d5c49bb4c8d4cafed8da28c182Felipe Leme    /* no ip6 nat */
92332af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline    RunCommand("IPTABLES MANGLE", {"iptables", "-t", "mangle", "-L", "-nvx"});
92432af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline    RunCommand("IP6TABLES MANGLE", {"ip6tables", "-t", "mangle", "-L", "-nvx"});
92532af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline    RunCommand("IPTABLES RAW", {"iptables", "-t", "raw", "-L", "-nvx"});
92632af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline    RunCommand("IP6TABLES RAW", {"ip6tables", "-t", "raw", "-L", "-nvx"});
927c0808155fd10d2d5c49bb4c8d4cafed8da28c182Felipe Leme}
928c0808155fd10d2d5c49bb4c8d4cafed8da28c182Felipe Leme
9298f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamathstatic void AddGlobalAnrTraceFile(const bool add_to_zip, const std::string& anr_traces_file,
9308f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                                  const std::string& anr_traces_dir) {
931e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    std::string dump_traces_dir;
932e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
933e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    if (dump_traces_path != nullptr) {
934e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme        if (add_to_zip) {
935e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            dump_traces_dir = dirname(dump_traces_path);
936e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            MYLOGD("Adding ANR traces (directory %s) to the zip file\n", dump_traces_dir.c_str());
937e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            ds.AddDir(dump_traces_dir, true);
938e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme        } else {
939e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            MYLOGD("Dumping current ANR traces (%s) to the main bugreport entry\n",
940e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme                   dump_traces_path);
941e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            ds.DumpFile("VM TRACES JUST NOW", dump_traces_path);
942e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme        }
943e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    }
944e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
945e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
946e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    // Make sure directory is not added twice.
947e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    // TODO: this is an overzealous check because it's relying on dump_traces_path - which is
948e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    // generated by dump_traces() -  and anr_traces_path - which is retrieved from a system
949e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    // property - but in reality they're the same path (although the former could be nullptr).
950e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    // Anyways, once dump_traces() is refactored as a private Dumpstate function, this logic should
951e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    // be revisited.
952e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    bool already_dumped = anr_traces_dir == dump_traces_dir;
953e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
9548f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    MYLOGD("AddGlobalAnrTraceFile(): dump_traces_dir=%s, anr_traces_dir=%s, already_dumped=%d\n",
955e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme           dump_traces_dir.c_str(), anr_traces_dir.c_str(), already_dumped);
956e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
9576b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath    android::base::unique_fd fd(TEMP_FAILURE_RETRY(
9586b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        open(anr_traces_file.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)));
9596b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath    if (fd.get() < 0) {
9608f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_file.c_str(), strerror(errno));
961e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    } else {
9628f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        if (add_to_zip) {
9638f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            if (!already_dumped) {
9648f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                MYLOGD("Adding dalvik ANR traces (directory %s) to the zip file\n",
9658f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                       anr_traces_dir.c_str());
9668f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                ds.AddDir(anr_traces_dir, true);
967e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            }
9688f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        } else {
9698f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            MYLOGD("Dumping last ANR traces (%s) to the main bugreport entry\n",
9708f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                   anr_traces_file.c_str());
9716b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath            dump_file_from_fd("VM TRACES AT LAST ANR", anr_traces_file.c_str(), fd.get());
9728f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        }
9738f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    }
9748f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath}
9758f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
9768f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamathstatic void AddAnrTraceDir(const bool add_to_zip, const std::string& anr_traces_dir) {
9778f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    MYLOGD("AddAnrTraceDir(): dump_traces_file=%s, anr_traces_dir=%s\n", dump_traces_path,
9788f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath           anr_traces_dir.c_str());
9798f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
9808f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // If we're here, dump_traces_path will always be a temporary file
9818f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // (created with mkostemp or similar) that contains dumps taken earlier
9828f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // on in the process.
9838f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    if (dump_traces_path != nullptr) {
9848f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        if (add_to_zip) {
9858f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            ds.AddZipEntry(ZIP_ROOT_DIR + anr_traces_dir + "/traces-just-now.txt", dump_traces_path);
9868f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        } else {
9878f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            MYLOGD("Dumping current ANR traces (%s) to the main bugreport entry\n",
9888f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                   dump_traces_path);
9898f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            ds.DumpFile("VM TRACES JUST NOW", dump_traces_path);
9908f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        }
9918f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
9928f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        const int ret = unlink(dump_traces_path);
9938f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        if (ret == -1) {
9948f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            MYLOGW("Error unlinking temporary trace path %s: %s\n", dump_traces_path,
9958f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                   strerror(errno));
9968f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        }
9978f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    }
9988f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
999bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath    // Add a specific message for the first ANR Dump.
10005f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    if (ds.anr_data_.size() > 0) {
10015f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez        AddDumps(ds.anr_data_.begin(), ds.anr_data_.begin() + 1,
1002bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath                 "VM TRACES AT LAST ANR", add_to_zip);
1003bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath
10046b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // The "last" ANR will always be included as separate entry in the zip file. In addition,
10056b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // it will be present in the body of the main entry if |add_to_zip| == false.
10066b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        //
10076b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath        // Historical ANRs are always included as separate entries in the bugreport zip file.
10085f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez        AddDumps(ds.anr_data_.begin() + ((add_to_zip) ? 1 : 0), ds.anr_data_.end(),
10096b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath                 "HISTORICAL ANR", true /* add_to_zip */);
1010bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath    } else {
10118f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        printf("*** NO ANRs to dump in %s\n\n", ANR_DIR.c_str());
10128f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    }
10138f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath}
10148f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
10158f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamathstatic void AddAnrTraceFiles() {
10168f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    const bool add_to_zip = ds.IsZipping() && ds.version_ == VERSION_SPLIT_ANR;
10178f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
10188f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    std::string anr_traces_file;
10198f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    std::string anr_traces_dir;
10208f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    bool is_global_trace_file = true;
10218f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
10228f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // First check whether the stack-trace-dir property is set. When it's set,
10238f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // each ANR trace will be written to a separate file and not to a global
10248f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // stack trace file.
10258f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    anr_traces_dir = android::base::GetProperty("dalvik.vm.stack-trace-dir", "");
10268f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    if (anr_traces_dir.empty()) {
10278f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        anr_traces_file = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
10288f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        if (!anr_traces_file.empty()) {
10298f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            anr_traces_dir = dirname(anr_traces_file.c_str());
1030e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme        }
1031bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath    } else {
1032bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath        is_global_trace_file = false;
1033e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    }
1034e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
10358f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // We have neither configured a global trace file nor a trace directory,
10368f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // there will be nothing to dump.
10378f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    if (anr_traces_file.empty() && anr_traces_dir.empty()) {
10388f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n");
1039e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme        return;
1040e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    }
1041e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
10428f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    if (is_global_trace_file) {
10438f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        AddGlobalAnrTraceFile(add_to_zip, anr_traces_file, anr_traces_dir);
10448f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    } else {
10458f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        AddAnrTraceDir(add_to_zip, anr_traces_dir);
10468f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    }
10478f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
1048e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    /* slow traces for slow operations */
1049e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    struct stat st;
10508f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    if (!anr_traces_dir.empty()) {
1051e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme        int i = 0;
10528f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        while (true) {
10538f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            const std::string slow_trace_path =
10548f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath                anr_traces_dir + android::base::StringPrintf("slow%02d.txt", i);
10558f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            if (stat(slow_trace_path.c_str(), &st)) {
1056e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme                // No traces file at this index, done with the files.
1057e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme                break;
1058e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            }
10598f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath            ds.DumpFile("VM TRACES WHEN SLOW", slow_trace_path.c_str());
1060e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme            i++;
1061e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme        }
1062e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    }
1063e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme}
1064e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme
1065509bb5d1764cdc44eef5166436dac3130a239d6dWei Wangstatic void DumpBlockStatFiles() {
1066509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang    DurationReporter duration_reporter("DUMP BLOCK STAT");
1067509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang
10681dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang    std::unique_ptr<DIR, std::function<int(DIR*)>> dirptr(opendir(BLK_DEV_SYS_DIR), closedir);
10691dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang
10701dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang    if (dirptr == nullptr) {
1071509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        MYLOGE("Failed to open %s: %s\n", BLK_DEV_SYS_DIR, strerror(errno));
1072509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        return;
1073509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang    }
1074509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang
1075509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang    printf("------ DUMP BLOCK STAT ------\n\n");
10761dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang    while (struct dirent *d = readdir(dirptr.get())) {
1077509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        if ((d->d_name[0] == '.')
1078509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang         && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
1079509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang          || (d->d_name[1] == '\0'))) {
1080509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang            continue;
1081509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        }
1082509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        const std::string new_path =
1083509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang            android::base::StringPrintf("%s/%s", BLK_DEV_SYS_DIR, d->d_name);
1084509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        printf("------ BLOCK STAT (%s) ------\n", new_path.c_str());
1085509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        dump_files("", new_path.c_str(), skip_not_stat, dump_stat_from_fd);
1086509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang        printf("\n");
1087509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang    }
10881dc1ef5af577d0cacc7b86a83d243d9750b0dd6dWei Wang     return;
1089509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang}
1090a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1091a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran Cstatic void DumpPacketStats() {
1092a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpFile("NETWORK DEV INFO", "/proc/net/dev");
1093a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpFile("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all");
1094a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpFile("QTAGUID NETWORK INTERFACES INFO (xt)", "/proc/net/xt_qtaguid/iface_stat_fmt");
1095a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpFile("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl");
1096a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpFile("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats");
1097a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C}
1098a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1099a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran Cstatic void DumpIpAddrAndRules() {
1100a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */
1101a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunCommand("NETWORK INTERFACES", {"ip", "link"});
1102a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunCommand("IPv4 ADDRESSES", {"ip", "-4", "addr", "show"});
1103a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunCommand("IPv6 ADDRESSES", {"ip", "-6", "addr", "show"});
1104a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunCommand("IP RULES", {"ip", "rule", "show"});
1105a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunCommand("IP RULES v6", {"ip", "-6", "rule", "show"});
1106a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C}
1107a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
110864afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nairstatic void RunDumpsysTextByPriority(const std::string& title, int priority,
110964afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                                     std::chrono::milliseconds timeout,
111064afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                                     std::chrono::milliseconds service_timeout) {
111164afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    auto start = std::chrono::steady_clock::now();
1112e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    sp<android::IServiceManager> sm = defaultServiceManager();
1113e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Dumpsys dumpsys(sm.get());
1114e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Vector<String16> args;
1115e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Dumpsys::setServiceArgs(args, /* asProto = */ false, priority);
1116e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Vector<String16> services = dumpsys.listServices(priority, /* supports_proto = */ false);
1117e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    for (const String16& service : services) {
1118e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        std::string path(title);
1119e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        path.append(" - ").append(String8(service).c_str());
1120e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        DumpstateSectionReporter section_reporter(path, ds.listener_, ds.report_section_);
1121e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        size_t bytes_written = 0;
1122e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        status_t status = dumpsys.startDumpThread(service, args);
1123e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        if (status == OK) {
1124e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            dumpsys.writeDumpHeader(STDOUT_FILENO, service, priority);
1125e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            std::chrono::duration<double> elapsed_seconds;
1126e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            status = dumpsys.writeDump(STDOUT_FILENO, service, service_timeout,
1127e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                                       /* as_proto = */ false, elapsed_seconds, bytes_written);
1128e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            section_reporter.setSize(bytes_written);
1129e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            dumpsys.writeDumpFooter(STDOUT_FILENO, service, elapsed_seconds);
1130e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            bool dump_complete = (status == OK);
1131e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            dumpsys.stopDumpThread(dump_complete);
1132e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        }
1133e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        section_reporter.setStatus(status);
1134e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair
1135e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        auto elapsed_duration = std::chrono::duration_cast<std::chrono::milliseconds>(
1136e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            std::chrono::steady_clock::now() - start);
1137e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        if (elapsed_duration > timeout) {
1138e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            MYLOGE("*** command '%s' timed out after %llums\n", title.c_str(),
1139e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                   elapsed_duration.count());
1140e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            break;
1141e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        }
1142e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    }
1143e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair}
1144e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair
114564afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nairstatic void RunDumpsysText(const std::string& title, int priority,
114664afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                           std::chrono::milliseconds timeout,
114764afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                           std::chrono::milliseconds service_timeout) {
114864afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    DurationReporter duration_reporter(title);
114964afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    dprintf(STDOUT_FILENO, "------ %s (/system/bin/dumpsys) ------\n", title.c_str());
115064afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    fsync(STDOUT_FILENO);
115164afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysTextByPriority(title, priority, timeout, service_timeout);
115264afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair}
115364afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair
115464afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair/* Dump all services registered with Normal or Default priority. */
115564afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nairstatic void RunDumpsysTextNormalPriority(const std::string& title,
115664afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                                         std::chrono::milliseconds timeout,
115764afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                                         std::chrono::milliseconds service_timeout) {
115864afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    DurationReporter duration_reporter(title);
115964afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    dprintf(STDOUT_FILENO, "------ %s (/system/bin/dumpsys) ------\n", title.c_str());
116064afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    fsync(STDOUT_FILENO);
116164afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysTextByPriority(title, IServiceManager::DUMP_FLAG_PRIORITY_NORMAL, timeout,
116264afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                             service_timeout);
116364afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysTextByPriority(title, IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT, timeout,
116464afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                             service_timeout);
116564afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair}
116664afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair
116764afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nairstatic void RunDumpsysProto(const std::string& title, int priority,
116864afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                            std::chrono::milliseconds timeout,
116964afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                            std::chrono::milliseconds service_timeout) {
11701e27b08c1c96926f88c782b047214e09f29d57d2Luis Hector Chavez    if (!ds.IsZipping()) {
11711e27b08c1c96926f88c782b047214e09f29d57d2Luis Hector Chavez        MYLOGD("Not dumping %s because it's not a zipped bugreport\n", title.c_str());
11721e27b08c1c96926f88c782b047214e09f29d57d2Luis Hector Chavez        return;
11731e27b08c1c96926f88c782b047214e09f29d57d2Luis Hector Chavez    }
1174e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    sp<android::IServiceManager> sm = defaultServiceManager();
1175e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Dumpsys dumpsys(sm.get());
1176e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Vector<String16> args;
1177e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Dumpsys::setServiceArgs(args, /* asProto = */ true, priority);
1178e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    DurationReporter duration_reporter(title);
1179e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair
1180e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    auto start = std::chrono::steady_clock::now();
1181e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    Vector<String16> services = dumpsys.listServices(priority, /* supports_proto = */ true);
1182e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    for (const String16& service : services) {
1183e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        std::string path(kProtoPath);
1184e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        path.append(String8(service).c_str());
1185e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        if (priority == IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL) {
1186e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            path.append("_CRITICAL");
1187e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        } else if (priority == IServiceManager::DUMP_FLAG_PRIORITY_HIGH) {
1188e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            path.append("_HIGH");
1189e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        }
1190e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        path.append(kProtoExt);
1191e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        DumpstateSectionReporter section_reporter(path, ds.listener_, ds.report_section_);
1192e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        status_t status = dumpsys.startDumpThread(service, args);
1193e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        if (status == OK) {
1194e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            status = ds.AddZipEntryFromFd(path, dumpsys.getDumpFd(), service_timeout);
1195e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            bool dumpTerminated = (status == OK);
1196e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            dumpsys.stopDumpThread(dumpTerminated);
1197e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        }
1198e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        ZipWriter::FileEntry file_entry;
1199e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        ds.zip_writer_->GetLastEntry(&file_entry);
1200e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        section_reporter.setSize(file_entry.compressed_size);
1201e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        section_reporter.setStatus(status);
1202e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair
1203e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        auto elapsed_duration = std::chrono::duration_cast<std::chrono::milliseconds>(
1204e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            std::chrono::steady_clock::now() - start);
1205e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        if (elapsed_duration > timeout) {
1206e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            MYLOGE("*** command '%s' timed out after %llums\n", title.c_str(),
1207e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair                   elapsed_duration.count());
1208e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair            break;
1209e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair        }
1210e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair    }
1211e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair}
1212e97d6127dd73f8c9f4a60e33dd9a701ece47716dVishnu Nair
1213780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair// Runs dumpsys on services that must dump first and and will take less than 100ms to dump.
1214780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nairstatic void RunDumpsysCritical() {
121564afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysText("DUMPSYS CRITICAL", IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL,
121664afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                   /* timeout= */ 5s, /* service_timeout= */ 500ms);
121764afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysProto("DUMPSYS CRITICAL PROTO", IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL,
121864afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                    /* timeout= */ 5s, /* service_timeout= */ 500ms);
1219780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair}
1220780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair
1221780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair// Runs dumpsys on services that must dump first but can take up to 250ms to dump.
1222780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nairstatic void RunDumpsysHigh() {
122364afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    // TODO meminfo takes ~10s, connectivity takes ~5sec to dump. They are both
122464afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    // high priority. Reduce timeout once they are able to dump in a shorter time or
122564afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    // moved to a parallel task.
122664afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysText("DUMPSYS HIGH", IServiceManager::DUMP_FLAG_PRIORITY_HIGH,
122764afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                   /* timeout= */ 90s, /* service_timeout= */ 30s);
122864afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysProto("DUMPSYS HIGH PROTO", IServiceManager::DUMP_FLAG_PRIORITY_HIGH,
122964afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                    /* timeout= */ 5s, /* service_timeout= */ 1s);
1230780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair}
1231780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair
1232780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair// Runs dumpsys on services that must dump but can take up to 10s to dump.
1233780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nairstatic void RunDumpsysNormal() {
123464afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysTextNormalPriority("DUMPSYS", /* timeout= */ 90s, /* service_timeout= */ 10s);
123564afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    RunDumpsysProto("DUMPSYS PROTO", IServiceManager::DUMP_FLAG_PRIORITY_NORMAL,
123664afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair                    /* timeout= */ 90s, /* service_timeout= */ 10s);
1237780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair}
1238780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair
123944cd9480005ed5a5b1b3530f44335ba400055de3Steven Morelandstatic void DumpHals() {
124044cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    using android::hidl::manager::V1_0::IServiceManager;
124144cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    using android::hardware::defaultServiceManager;
124244cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland
124344cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    sp<IServiceManager> sm = defaultServiceManager();
124444cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    if (sm == nullptr) {
124544cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        MYLOGE("Could not retrieve hwservicemanager to dump hals.\n");
124644cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        return;
124744cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    }
124844cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland
124944cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    auto ret = sm->list([&](const auto& interfaces) {
125044cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        for (const std::string& interface : interfaces) {
125144cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland            std::string cleanName = interface;
125244cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland            std::replace_if(cleanName.begin(),
125344cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                            cleanName.end(),
125444cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                            [](char c) {
125544cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                                return !isalnum(c) &&
125644cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                                    std::string("@-_:.").find(c) == std::string::npos;
125744cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                            }, '_');
125844cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland            const std::string path = kDumpstateBoardPath + "lshal_debug_" + cleanName;
125944cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland
126044cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland            {
126144cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                auto fd = android::base::unique_fd(
126244cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                    TEMP_FAILURE_RETRY(open(path.c_str(),
126344cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                    O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
126444cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
126544cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                if (fd < 0) {
126644cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                    MYLOGE("Could not open %s to dump additional hal information.\n", path.c_str());
126744cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                    continue;
126844cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                }
126944cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                RunCommandToFd(fd,
127044cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                        "",
1271c81cd3c115443fdd162446992e040ca45e7e4c51Steven Moreland                        {"lshal", "debug", "-E", interface},
127244cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                        CommandOptions::WithTimeout(2).AsRootIfAvailable().Build());
127344cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland
127444cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                bool empty = 0 == lseek(fd, 0, SEEK_END);
127544cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                if (!empty) {
127644cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                    ds.AddZipEntry("lshal-debug/" + cleanName + ".txt", path);
127744cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland                }
127844cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland            }
127944cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland
128044cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland            unlink(path.c_str());
128144cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        }
128244cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    });
128344cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland
128444cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    if (!ret.isOk()) {
128544cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        MYLOGE("Could not list hals from hwservicemanager.\n");
128644cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland    }
128744cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland}
128844cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland
1289bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Lemestatic void dumpstate() {
12909a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    DurationReporter duration_reporter("DUMPSTATE");
1291f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
12922db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg    dump_dev_files("TRUSTY VERSION", "/sys/bus/platform/drivers/trusty", "trusty_version");
1293b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("UPTIME", {"uptime"});
1294509bb5d1764cdc44eef5166436dac3130a239d6dWei Wang    DumpBlockStatFiles();
12958c8130eb68c89987a94db084608a4229bad06c18Mark Salyzyn    dump_emmc_ecsd("/d/mmc0/mmc0:0001/ext_csd");
1296b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("MEMORY INFO", "/proc/meminfo");
1297b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("CPU INFO", {"top", "-b", "-n", "1", "-H", "-s", "6", "-o",
129830dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme                            "pid,tid,user,pr,ni,%cpu,s,virt,res,pcy,cmd,name"});
1299f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme    RunCommand("PROCRANK", {"procrank"}, AS_ROOT_20);
1300b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("VIRTUAL MEMORY STATS", "/proc/vmstat");
1301b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("VMALLOC INFO", "/proc/vmallocinfo");
1302b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("SLAB INFO", "/proc/slabinfo");
1303b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("ZONEINFO", "/proc/zoneinfo");
1304b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("PAGETYPEINFO", "/proc/pagetypeinfo");
1305b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("BUDDYINFO", "/proc/buddyinfo");
1306b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("FRAGMENTATION INFO", "/d/extfrag/unusable_index");
1307b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme
1308b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("KERNEL WAKE SOURCES", "/d/wakeup_sources");
1309b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
1310b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("KERNEL SYNC", "/d/sync");
1311b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme
1312b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("PROCESSES AND THREADS",
1313591a72da3ec97e986f9149d0b0d851bf27f6665dYohei Yukawa               {"ps", "-A", "-T", "-Z", "-O", "pri,nice,rtprio,sched,pcy,time"});
1314f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme    RunCommand("LIBRANK", {"librank"}, CommandOptions::AS_ROOT);
1315f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
131669ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber    if (ds.IsZipping()) {
131744cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        RunCommand("HARDWARE HALS", {"lshal"}, CommandOptions::WithTimeout(2).AsRootIfAvailable().Build());
131844cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        DumpHals();
131969ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber    } else {
132044cd9480005ed5a5b1b3530f44335ba400055de3Steven Moreland        RunCommand("HARDWARE HALS", {"lshal", "--debug"}, CommandOptions::WithTimeout(10).AsRootIfAvailable().Build());
132169ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber    }
132281b429eba542f95877459bf6b860c55f35fea222Steven Moreland
1323b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("PRINTENV", {"printenv"});
132421b7c8d618777d6bf684e52b082c23f7e04b0688Elliott Hughes    RunCommand("NETSTAT", {"netstat", "-nW"});
1325e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme    struct stat s;
1326e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme    if (stat("/proc/modules", &s) != 0) {
1327e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme        MYLOGD("Skipping 'lsmod' because /proc/modules does not exist\n");
1328e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme    } else {
1329b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme        RunCommand("LSMOD", {"lsmod"});
1330e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme    }
13314db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski
13324a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou    if (__android_logger_property_get_bool(
13334a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou            "ro.logd.kernel", BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE)) {
13344a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        DoKernelLogcat();
13354a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou    } else {
13364a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou        do_dmesg();
13374a0a877c6d9b8aa2225a791329c2da0f7e8bdbe9Siarhei Vishniakou    }
1338f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1339f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme    RunCommand("LIST OF OPEN FILES", {"lsof"}, CommandOptions::AS_ROOT);
13401dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown    for_each_pid(do_showmap, "SMAPS OF ALL PROCESSES");
13411dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown    for_each_tid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS");
1342a297c3258f6f7ea52cc2dcc42d62f85fda12a163Mark Salyzyn    for_each_pid(show_showtime, "PROCESS TIMES (pid cmd user system iowait+percentage)");
1343f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
13442ff8e87d906365a9b786ac6829b901ca2798bb68Ajay Panicker    /* Dump Bluetooth HCI logs */
13452ff8e87d906365a9b786ac6829b901ca2798bb68Ajay Panicker    ds.AddDir("/data/misc/bluetooth/logs", true);
1346d886ec496952a19bee202bc3d6f670009c3a0689Ajay Panicker
13479a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (!ds.do_early_screenshot_) {
1348cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme        MYLOGI("taking late screenshot\n");
1349bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme        ds.TakeScreenshot();
13505a93003d3f0d1808b6dcd9928041ec62ea7f67adJeff Sharkey    }
13515a93003d3f0d1808b6dcd9928041ec62ea7f67adJeff Sharkey
13526ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    DoLogcat();
1353ecc0763e6c96c418ea4ee6c993d58d16a58407b3Mark Salyzyn
1354e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme    AddAnrTraceFiles();
1355f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
13568f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // NOTE: tombstones are always added as separate entries in the zip archive
13578f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    // and are not interspersed with the main report.
13585f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    const bool tombstones_dumped = AddDumps(ds.tombstone_data_.begin(), ds.tombstone_data_.end(),
1359bd86372f09748b258f959cb7a1a04613038e59b0Narayan Kamath                                            "TOMBSTONE", true /* add_to_zip */);
13608f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath    if (!tombstones_dumped) {
13618f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath        printf("*** NO TOMBSTONES to dump in %s\n\n", TOMBSTONE_DIR.c_str());
13627dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris    }
13637dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris
1364a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpPacketStats();
1365f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
13666ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    DoKmsg();
13672262c16372570f57d3107d574abe2c80825d286eMark Salyzyn
1368a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpIpAddrAndRules();
13692b3bba34aec65b612be8d1f52cd124d9c30955f9Sreeram Ramachandran
13702b3bba34aec65b612be8d1f52cd124d9c30955f9Sreeram Ramachandran    dump_route_tables();
13712b3bba34aec65b612be8d1f52cd124d9c30955f9Sreeram Ramachandran
1372b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("ARP CACHE", {"ip", "-4", "neigh", "show"});
1373b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("IPv6 ND CACHE", {"ip", "-6", "neigh", "show"});
1374b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("MULTICAST ADDRESSES", {"ip", "maddr"});
1375f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1376780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair    RunDumpsysHigh();
13776afc38c45af45eb8f64793bca2903b3f4c55579bLorenzo Colitti
137823ccc625fd60891d20977abc5f2c35cbe46142acElliott Hughes    RunCommand("SYSTEM PROPERTIES", {"getprop"});
1379f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1380f334d669dcd9ce322dd5a997c3b5a392b9152d3bJin Qian    RunCommand("STORAGED IO INFO", {"storaged", "-u", "-p"});
1381f649a6ef3ca6358f605aea100c77a3f20f4af937ynwang
1382b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("FILESYSTEMS & FREE SPACE", {"df"});
1383f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1384b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunCommand("LAST RADIO LOG", {"parse_radio_log", "/proc/last_radio_log"});
1385f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1386f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    /* Binder state is expensive to look at as it uses a lot of memory. */
1387b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log");
1388b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log");
1389b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("BINDER TRANSACTIONS", "/sys/kernel/debug/binder/transactions");
1390b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("BINDER STATS", "/sys/kernel/debug/binder/stats");
1391b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    DumpFile("BINDER STATE", "/sys/kernel/debug/binder/state");
1392f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
139336b4cdb2ddec610e52ab60ae1f6497ae3739f496Vishnu Nair    /* Add window and surface trace files. */
139436b4cdb2ddec610e52ab60ae1f6497ae3739f496Vishnu Nair    if (!PropertiesHelper::IsUserBuild()) {
139536b4cdb2ddec610e52ab60ae1f6497ae3739f496Vishnu Nair        ds.AddDir(WMTRACE_DATA_DIR, false);
139636b4cdb2ddec610e52ab60ae1f6497ae3739f496Vishnu Nair    }
139736b4cdb2ddec610e52ab60ae1f6497ae3739f496Vishnu Nair
13986f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme    ds.DumpstateBoard();
1399f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
14007440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland    /* Migrate the ril_dumpstate to a device specific dumpstate? */
140196c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    int rilDumpstateTimeout = android::base::GetIntProperty("ril.dumpstate.timeout", 0);
140296c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme    if (rilDumpstateTimeout > 0) {
140330dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        // su does not exist on user builds, so try running without it.
140430dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        // This way any implementations of vril-dump that do not require
140530dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        // root can run on user builds.
140630dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme        CommandOptions::CommandOptionsBuilder options =
140796c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme            CommandOptions::WithTimeout(rilDumpstateTimeout);
1408f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme        if (!PropertiesHelper::IsUserBuild()) {
140930dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme            options.AsRoot();
1410f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross        }
1411b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme        RunCommand("DUMP VENDOR RIL LOGS", {"vril-dump"}, options.Build());
1412f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    }
1413f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1414d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1415d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("== Android Framework Services\n");
1416d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1417f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1418780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair    RunDumpsysNormal();
1419f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1420d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1421d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("== Checkins\n");
1422d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
142302bea9786d2ecc4c04f35fd7d9b73d4dd2b73735Dianne Hackborn
1424b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunDumpsys("CHECKIN BATTERYSTATS", {"batterystats", "-c"});
1425b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunDumpsys("CHECKIN MEMINFO", {"meminfo", "--checkin"});
1426b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunDumpsys("CHECKIN NETSTATS", {"netstats", "--checkin"});
1427b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunDumpsys("CHECKIN PROCSTATS", {"procstats", "-c"});
1428b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunDumpsys("CHECKIN USAGESTATS", {"usagestats", "-c"});
1429b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme    RunDumpsys("CHECKIN PACKAGE", {"package", "--checkin"});
143002bea9786d2ecc4c04f35fd7d9b73d4dd2b73735Dianne Hackborn
1431d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1432d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("== Running Application Activities\n");
1433d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1434f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
14356078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    // The following dumpsys internally collects output from running apps, so it can take a long
14366078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    // time. So let's extend the timeout.
14376078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki
14386078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    const CommandOptions DUMPSYS_COMPONENTS_OPTIONS = CommandOptions::WithTimeout(60).Build();
14396078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki
14406078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    RunDumpsys("APP ACTIVITIES", {"activity", "-v", "all"}, DUMPSYS_COMPONENTS_OPTIONS);
14416078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki
14426078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("========================================================\n");
14436078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("== Running Application Services (platform)\n");
14446078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("========================================================\n");
14456078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki
14466078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    RunDumpsys("APP SERVICES PLATFORM", {"activity", "service", "all-platform"},
14476078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki            DUMPSYS_COMPONENTS_OPTIONS);
14486078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki
14496078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("========================================================\n");
14506078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("== Running Application Services (non-platform)\n");
14516078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("========================================================\n");
14526078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki
14536078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    RunDumpsys("APP SERVICES NON-PLATFORM", {"activity", "service", "all-non-platform"},
14546078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki            DUMPSYS_COMPONENTS_OPTIONS);
1455f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1456d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
14576078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("== Running Application Providers (platform)\n");
1458d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1459f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
14606078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    RunDumpsys("APP PROVIDERS PLATFORM", {"activity", "provider", "all-platform"},
14616078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki            DUMPSYS_COMPONENTS_OPTIONS);
1462f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1463d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
14646078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    printf("== Running Application Providers (non-platform)\n");
1465d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1466f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
14676078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki    RunDumpsys("APP PROVIDERS NON-PLATFORM", {"activity", "provider", "all-non-platform"},
14686078098adadbdacd21f247fef0f88d9c02e26bacMakoto Onuki            DUMPSYS_COMPONENTS_OPTIONS);
1469f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
14708b397ab3d6ad2ff23897b3743fe51325e15ffaf6Adrian Roos    printf("========================================================\n");
14718b397ab3d6ad2ff23897b3743fe51325e15ffaf6Adrian Roos    printf("== Dropbox crashes\n");
14728b397ab3d6ad2ff23897b3743fe51325e15ffaf6Adrian Roos    printf("========================================================\n");
14738b397ab3d6ad2ff23897b3743fe51325e15ffaf6Adrian Roos
14748b397ab3d6ad2ff23897b3743fe51325e15ffaf6Adrian Roos    RunDumpsys("DROPBOX SYSTEM SERVER CRASHES", {"dropbox", "-p", "system_server_crash"});
14758b397ab3d6ad2ff23897b3743fe51325e15ffaf6Adrian Roos    RunDumpsys("DROPBOX SYSTEM APP CRASHES", {"dropbox", "-p", "system_app_crash"});
14768b397ab3d6ad2ff23897b3743fe51325e15ffaf6Adrian Roos
1477d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1478d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("== Final progress (pid %d): %d/%d (estimated %d)\n", ds.pid_, ds.progress_->Get(),
1479d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme           ds.progress_->GetMax(), ds.progress_->GetInitialMax());
1480d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1481d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("== dumpstate: done (id %d)\n", ds.id_);
1482d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1483f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross}
1484f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1485253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal// This method collects common dumpsys for telephony and wifi
1486253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawalstatic void DumpstateRadioCommon() {
1487a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpIpTablesAsRoot();
1488a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1489a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    if (!DropRootUser()) {
1490a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C        return;
1491a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    }
1492a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1493a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    do_dmesg();
1494a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DoLogcat();
1495a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpPacketStats();
1496a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DoKmsg();
1497a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    DumpIpAddrAndRules();
1498a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    dump_route_tables();
1499a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1500a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunDumpsys("NETWORK DIAGNOSTICS", {"connectivity", "--diag"},
1501a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C               CommandOptions::WithTimeout(10).Build());
1502253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal}
1503253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal
1504253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal// This method collects dumpsys for telephony debugging only
1505253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawalstatic void DumpstateTelephonyOnly() {
1506253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    DurationReporter duration_reporter("DUMPSTATE");
1507a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran    const CommandOptions DUMPSYS_COMPONENTS_OPTIONS = CommandOptions::WithTimeout(60).Build();
1508253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal
1509253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    DumpstateRadioCommon();
1510a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1511a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunCommand("SYSTEM PROPERTIES", {"getprop"});
1512a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1513a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("========================================================\n");
1514a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("== Android Framework Services\n");
1515a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("========================================================\n");
1516a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1517652cc80fcffda5a80b468b822cdddd69b28696a3Vishnu Nair    RunDumpsys("DUMPSYS", {"connectivity"}, CommandOptions::WithTimeout(90).Build(),
1518652cc80fcffda5a80b468b822cdddd69b28696a3Vishnu Nair               SEC_TO_MSEC(10));
1519652cc80fcffda5a80b468b822cdddd69b28696a3Vishnu Nair    RunDumpsys("DUMPSYS", {"carrier_config"}, CommandOptions::WithTimeout(90).Build(),
1520652cc80fcffda5a80b468b822cdddd69b28696a3Vishnu Nair               SEC_TO_MSEC(10));
1521d25a914cd3d54dfa8760a928cf2b19d53bee27f4Amruth Ramachandran    RunDumpsys("DUMPSYS", {"wifi"}, CommandOptions::WithTimeout(90).Build(),
1522d25a914cd3d54dfa8760a928cf2b19d53bee27f4Amruth Ramachandran               SEC_TO_MSEC(10));
1523e8d9891b85c5e65888157d60b1d166d124e14b31Sooraj Sasindran    RunDumpsys("BATTERYSTATS", {"batterystats"}, CommandOptions::WithTimeout(90).Build(),
1524e8d9891b85c5e65888157d60b1d166d124e14b31Sooraj Sasindran               SEC_TO_MSEC(10));
1525a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1526a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("========================================================\n");
1527a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("== Running Application Services\n");
1528a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("========================================================\n");
1529a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1530a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    RunDumpsys("TELEPHONY SERVICES", {"activity", "service", "TelephonyDebugService"});
1531a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1532a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("========================================================\n");
1533a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran    printf("== Running Application Services (non-platform)\n");
1534a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran    printf("========================================================\n");
1535a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran
1536a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran    RunDumpsys("APP SERVICES NON-PLATFORM", {"activity", "service", "all-non-platform"},
1537a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran            DUMPSYS_COMPONENTS_OPTIONS);
1538a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran
1539a0829e7e1427d101046b33f8fb2ac752b94927f3Sooraj Sasindran    printf("========================================================\n");
1540a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("== dumpstate: done (id %d)\n", ds.id_);
1541a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C    printf("========================================================\n");
1542a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C}
1543a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C
1544253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal// This method collects dumpsys for wifi debugging only
1545253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawalstatic void DumpstateWifiOnly() {
1546253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    DurationReporter duration_reporter("DUMPSTATE");
1547253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal
1548253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    DumpstateRadioCommon();
1549253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal
1550253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    printf("========================================================\n");
1551253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    printf("== Android Framework Services\n");
1552253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    printf("========================================================\n");
1553253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal
1554253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    RunDumpsys("DUMPSYS", {"connectivity"}, CommandOptions::WithTimeout(90).Build(),
1555253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal               SEC_TO_MSEC(10));
1556253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    RunDumpsys("DUMPSYS", {"wifi"}, CommandOptions::WithTimeout(90).Build(),
1557253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal               SEC_TO_MSEC(10));
1558253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal
1559253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    printf("========================================================\n");
1560253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    printf("== dumpstate: done (id %d)\n", ds.id_);
1561253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    printf("========================================================\n");
1562253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal}
1563253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal
15646f674aefab201fbf9141aabbb603bbfc84771927Felipe Lemevoid Dumpstate::DumpstateBoard() {
15656f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme    DurationReporter duration_reporter("dumpstate_board()");
1566d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
1567d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("== Board\n");
1568d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("========================================================\n");
15696f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme
15706f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme    if (!IsZipping()) {
15717440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland        MYLOGD("Not dumping board info because it's not a zipped bugreport\n");
15726f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme        return;
15736f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme    }
15746f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme
15757aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez    std::vector<std::string> paths;
15767aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez    std::vector<android::base::ScopeGuard<std::function<void()>>> remover;
15779fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song    for (int i = 0; i < NUM_OF_DUMPS; i++) {
15787aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez        paths.emplace_back(kDumpstateBoardPath + kDumpstateBoardFiles[i]);
15797aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez        remover.emplace_back(android::base::make_scope_guard(std::bind(
15807aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            [](std::string path) {
15817aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez                if (remove(path.c_str()) != 0 && errno != ENOENT) {
15827aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez                    MYLOGE("Could not remove(%s): %s\n", path.c_str(), strerror(errno));
15837aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez                }
15847aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            },
15857aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            paths[i])));
15867aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez    }
15877aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez
1588587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    sp<IDumpstateDevice> dumpstate_device(IDumpstateDevice::getService());
1589587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    if (dumpstate_device == nullptr) {
1590587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        MYLOGE("No IDumpstateDevice implementation\n");
1591587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        return;
1592587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    }
15936f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme
1594587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    using ScopedNativeHandle =
1595587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            std::unique_ptr<native_handle_t, std::function<void(native_handle_t*)>>;
1596587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    ScopedNativeHandle handle(native_handle_create(static_cast<int>(paths.size()), 0),
1597587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                              [](native_handle_t* handle) {
1598587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                                  native_handle_close(handle);
1599587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                                  native_handle_delete(handle);
1600587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                              });
1601587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    if (handle == nullptr) {
1602587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        MYLOGE("Could not create native_handle\n");
1603587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        return;
1604587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    }
16059fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song
1606587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    for (size_t i = 0; i < paths.size(); i++) {
1607587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        MYLOGI("Calling IDumpstateDevice implementation using path %s\n", paths[i].c_str());
16087aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez
1609587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        android::base::unique_fd fd(TEMP_FAILURE_RETRY(
1610587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            open(paths[i].c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1611587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1612587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        if (fd < 0) {
1613587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            MYLOGE("Could not open file %s: %s\n", paths[i].c_str(), strerror(errno));
1614587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            return;
1615587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        }
1616587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        handle.get()->data[i] = fd.release();
1617587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    }
16186f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme
1619587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    // Given that bugreport is required to diagnose failures, it's better to
1620587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    // set an arbitrary amount of timeout for IDumpstateDevice than to block the
1621587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    // rest of bugreport. In the timeout case, we will kill dumpstate board HAL
1622587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    // and grab whatever dumped
1623587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    std::packaged_task<bool()>
1624587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            dumpstate_task([paths, dumpstate_device, &handle]() -> bool {
16257aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            android::hardware::Return<void> status = dumpstate_device->dumpstateBoard(handle.get());
16267aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            if (!status.isOk()) {
16277aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez                MYLOGE("dumpstateBoard failed: %s\n", status.description().c_str());
1628587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                return false;
16297aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            }
1630587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            return true;
16317aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez        });
1632587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang
16337aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez    auto result = dumpstate_task.get_future();
16347aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez    std::thread(std::move(dumpstate_task)).detach();
1635587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang
1636587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    constexpr size_t timeout_sec = 30;
1637587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    if (result.wait_for(std::chrono::seconds(timeout_sec)) != std::future_status::ready) {
1638587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        MYLOGE("dumpstateBoard timed out after %zus, killing dumpstate vendor HAL\n", timeout_sec);
1639587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        if (!android::base::SetProperty("ctl.interface_restart",
1640587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                                        android::base::StringPrintf("%s/default",
1641587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                                                                    IDumpstateDevice::descriptor))) {
1642587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            MYLOGE("Couldn't restart dumpstate HAL\n");
1643587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        }
16447aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez    }
1645587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    // Wait some time for init to kill dumpstate vendor HAL
1646587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    constexpr size_t killing_timeout_sec = 10;
1647587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    if (result.wait_for(std::chrono::seconds(killing_timeout_sec)) != std::future_status::ready) {
1648587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        MYLOGE("killing dumpstateBoard timed out after %zus, continue and "
1649587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang               "there might be racing in content\n", killing_timeout_sec);
1650587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    }
1651587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang
1652587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    auto file_sizes = std::make_unique<ssize_t[]>(paths.size());
1653587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang    for (size_t i = 0; i < paths.size(); i++) {
1654587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        struct stat s;
1655587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        if (fstat(handle.get()->data[i], &s) == -1) {
1656587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            MYLOGE("Failed to fstat %s: %s\n", kDumpstateBoardFiles[i].c_str(),
1657587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang                   strerror(errno));
1658587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            file_sizes[i] = -1;
1659587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang            continue;
1660587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        }
1661587eac9815d8994f0d9f0b7584402aae353bcb2cWei Wang        file_sizes[i] = s.st_size;
16627440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland    }
16636f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme
16647aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez    for (size_t i = 0; i < paths.size(); i++) {
16657aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez        if (file_sizes[i] == -1) {
16667aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            continue;
16677aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez        }
16687aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez        if (file_sizes[i] == 0) {
16699fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song            MYLOGE("Ignoring empty %s\n", kDumpstateBoardFiles[i].c_str());
16707aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez            continue;
16719fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song        }
16727aecd381d74c4acfecdcd8fa03fda4debf5adfffLuis Hector Chavez        AddZipEntry(kDumpstateBoardFiles[i], paths[i]);
16739fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song    }
16749fbfad0b6dcda9a2b2c3913597aa24e4db7b3544Jie Song
1675d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    printf("*** See dumpstate-board.txt entry ***\n");
16766f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme}
16776f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme
16784a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Lemestatic void ShowUsageAndExit(int exitCode = 1) {
16794a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme    fprintf(stderr,
1680bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme            "usage: dumpstate [-h] [-b soundfile] [-e soundfile] [-o file] [-d] [-p] "
16814a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "[-z]] [-s] [-S] [-q] [-B] [-P] [-R] [-V version]\n"
16824a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -h: display this help message\n"
16834a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -b: play sound file instead of vibrate, at beginning of job\n"
16844a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -e: play sound file instead of vibrate, at end of job\n"
16854a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -o: write to file (instead of stdout)\n"
16864a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -d: append date to filename (requires -o)\n"
16874a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -p: capture screenshot to filename.png (requires -o)\n"
16884a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -z: generate zipped file (requires -o)\n"
16894a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -s: write output to control socket (for init)\n"
169047f644e774a13c81bf8bda5166e65cd5c5171ef3Takuya Ogawa            "  -S: write file location to control socket (for init; requires -o and -z)\n"
16914a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -q: disable vibrate\n"
16924a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -B: send broadcast when finished (requires -o)\n"
16934a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -P: send broadcast when started and update system properties on "
16944a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "progress (requires -o and -B)\n"
16954a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "  -R: take bugreport in remote mode (requires -o, -z, -d and -B, "
16964a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            "shouldn't be used with -P)\n"
1697d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            "  -v: prints the dumpstate header and exit\n");
16984a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme    exit(exitCode);
16994a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme}
17004a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme
17014a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Lemestatic void ExitOnInvalidArgs() {
17024a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme    fprintf(stderr, "invalid combination of args\n");
17034a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme    ShowUsageAndExit();
1704f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross}
1705f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1706f87959e00732d7d737527f1248a71adea99ae29dWei Liustatic void register_sig_handler() {
1707558e1ef07fb6169a1501a9b8637387abef611f34Luis Hector Chavez    signal(SIGPIPE, SIG_IGN);
1708f87959e00732d7d737527f1248a71adea99ae29dWei Liu}
1709f87959e00732d7d737527f1248a71adea99ae29dWei Liu
17101d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemebool Dumpstate::FinishZipFile() {
17119a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    std::string entry_name = base_name_ + "-" + name_ + ".txt";
17121d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    MYLOGD("Adding main entry (%s) from %s to .zip bugreport\n", entry_name.c_str(),
17139a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme           tmp_path_.c_str());
17145b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme    // Final timestamp
17155b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme    char date[80];
17165b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme    time_t the_real_now_please_stand_up = time(nullptr);
17175b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme    strftime(date, sizeof(date), "%Y/%m/%d %H:%M:%S", localtime(&the_real_now_please_stand_up));
17187447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    MYLOGD("dumpstate id %d finished around %s (%ld s)\n", ds.id_, date,
1719bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme           the_real_now_please_stand_up - ds.now_);
17205b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme
17219a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (!ds.AddZipEntry(entry_name, tmp_path_)) {
1722cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme        MYLOGE("Failed to add text entry to .zip file\n");
17236e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        return false;
17246e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme    }
17251d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (!AddTextZipEntry("main_entry.txt", entry_name)) {
1726cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme        MYLOGE("Failed to add main_entry.txt to .zip file\n");
1727111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme        return false;
1728809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme    }
17296e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme
17300f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme    // Add log file (which contains stderr output) to zip...
17310f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme    fprintf(stderr, "dumpstate_log.txt entry on zip file logged up to here\n");
17329a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (!ds.AddZipEntry("dumpstate_log.txt", ds.log_path_.c_str())) {
17330f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme        MYLOGE("Failed to add dumpstate log to .zip file\n");
17340f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme        return false;
17350f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme    }
17360f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme    // ... and re-opens it for further logging.
17379a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    redirect_to_existing_file(stderr, const_cast<char*>(ds.log_path_.c_str()));
17380f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme    fprintf(stderr, "\n");
17390f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme
1740c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme    int32_t err = zip_writer_->Finish();
17411d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    if (err != 0) {
1742c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme        MYLOGE("zip_writer_->Finish(): %s\n", ZipWriter::ErrorCodeString(err));
17436e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        return false;
17446e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme    }
17456e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme
17461d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    // TODO: remove once FinishZipFile() is automatically handled by Dumpstate's destructor.
17471d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme    ds.zip_file.reset(nullptr);
17481d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme
1749e9d2c5414c86949f6de12c4291a2d8c34b2d0b34Felipe Leme    MYLOGD("Removing temporary file %s\n", tmp_path_.c_str())
1750e9d2c5414c86949f6de12c4291a2d8c34b2d0b34Felipe Leme    if (remove(tmp_path_.c_str()) != 0) {
1751e9d2c5414c86949f6de12c4291a2d8c34b2d0b34Felipe Leme        MYLOGE("Failed to remove temporary file (%s): %s\n", tmp_path_.c_str(), strerror(errno));
1752c4eee56dab06a7de1db18327f8d4831f89d1d640Felipe Leme    }
1753c4eee56dab06a7de1db18327f8d4831f89d1d640Felipe Leme
17546e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme    return true;
17556e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme}
17566e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme
1757cb057c2e6bf23b43df49282c0db26b663e4535f7Chih-Hung Hsiehstatic std::string SHA256_file_hash(const std::string& filepath) {
175827cd7b256eb08bf9dec7e4e8af8375711ab10225Andreas Gampe    android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filepath.c_str(), O_RDONLY | O_NONBLOCK
175927cd7b256eb08bf9dec7e4e8af8375711ab10225Andreas Gampe            | O_CLOEXEC | O_NOFOLLOW)));
1760aff684300a3b7d6984d3b3c1efddb810cd0205e7Andreas Gampe    if (fd == -1) {
1761cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme        MYLOGE("open(%s): %s\n", filepath.c_str(), strerror(errno));
17624db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski        return NULL;
17634db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    }
17644db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski
17654db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    SHA256_CTX ctx;
1766c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes    SHA256_Init(&ctx);
17674db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski
17684db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    std::vector<uint8_t> buffer(65536);
17694db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    while (1) {
17704db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski        ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd.get(), buffer.data(), buffer.size()));
17714db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski        if (bytes_read == 0) {
17724db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski            break;
17734db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski        } else if (bytes_read == -1) {
1774cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme            MYLOGE("read(%s): %s\n", filepath.c_str(), strerror(errno));
17754db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski            return NULL;
17764db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski        }
17774db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski
1778c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes        SHA256_Update(&ctx, buffer.data(), bytes_read);
17794db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    }
17804db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski
1781c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes    uint8_t hash[SHA256_DIGEST_LENGTH];
1782c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes    SHA256_Final(hash, &ctx);
1783c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes
1784c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes    char hash_buffer[SHA256_DIGEST_LENGTH * 2 + 1];
1785c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes    for(size_t i = 0; i < SHA256_DIGEST_LENGTH; i++) {
1786cbbdf73608bace91270622034e4813a2355b7bf1Michal Karpinski        sprintf(hash_buffer + (i * 2), "%02x", hash[i]);
17874db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    }
17884db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    hash_buffer[sizeof(hash_buffer) - 1] = 0;
17894db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    return std::string(hash_buffer);
17904db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski}
17914db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski
1792a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Lemestatic void SendBroadcast(const std::string& action, const std::vector<std::string>& args) {
1793a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme    // clang-format off
1794a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme    std::vector<std::string> am = {"/system/bin/cmd", "activity", "broadcast", "--user", "0",
1795a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme                    "--receiver-foreground", "--receiver-include-background", "-a", action};
1796a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme    // clang-format on
17978d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme
17988d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme    am.insert(am.end(), args.begin(), args.end());
17998d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme
18008d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme    RunCommand("", am,
18018d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme               CommandOptions::WithTimeout(20)
18028d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme                   .Log("Sending broadcast: '%s'\n")
18038d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme                   .Always()
18048d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme                   .DropRoot()
18058d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme                   .RedirectStderr()
18068d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme                   .Build());
18078d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme}
18088d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme
180935b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Lemestatic void Vibrate(int duration_ms) {
181035b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme    // clang-format off
181135b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme    RunCommand("", {"cmd", "vibrator", "vibrate", std::to_string(duration_ms), "dumpstate"},
181235b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme               CommandOptions::WithTimeout(10)
181335b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme                   .Log("Vibrate: '%s'\n")
181435b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme                   .Always()
181535b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme                   .Build());
181635b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme    // clang-format on
181735b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme}
181835b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme
181920cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nair/** Main entry point for dumpstate. */
182020cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nairint run_main(int argc, char* argv[]) {
1821f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    int do_add_date = 0;
18226e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme    int do_zip_file = 0;
18231f794c442cc63f7962c21e8e712adeca338af63eJohn Michelau    int do_vibrate = 1;
1824f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    char* use_outfile = 0;
1825f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    int use_socket = 0;
18262628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme    int use_control_socket = 0;
1827f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    int do_fb = 0;
182827f9e6d849fce956c9b8f1ad5c3d9a954501a76bJeff Sharkey    int do_broadcast = 0;
18294db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    int is_remote_mode = 0;
1830d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    bool show_header_only = false;
183175876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme    bool do_start_service = false;
18326ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    bool telephony_only = false;
1833253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    bool wifi_only = false;
183420cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nair    int dup_stdout_fd;
183520cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nair    int dup_stderr_fd;
18368fecfdda012928bc2fe6d0e66fd4a4c912946254Felipe Leme
1837f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    /* set as high priority, and protect from OOM killer */
1838f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    setpriority(PRIO_PROCESS, 0, -20);
18399c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang
1840d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    FILE* oom_adj = fopen("/proc/self/oom_score_adj", "we");
1841f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    if (oom_adj) {
18429c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang        fputs("-1000", oom_adj);
1843f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross        fclose(oom_adj);
18449c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang    } else {
18459c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang        /* fallback to kernels <= 2.6.35 */
18469c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang        oom_adj = fopen("/proc/self/oom_adj", "we");
18479c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang        if (oom_adj) {
18489c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang            fputs("-17", oom_adj);
18499c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang            fclose(oom_adj);
18509c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang        }
1851f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    }
1852f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
18531dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown    /* parse arguments */
1854f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    int c;
18552628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme    while ((c = getopt(argc, argv, "dho:svqzpPBRSV:")) != -1) {
1856f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross        switch (c) {
1857e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme            // clang-format off
1858d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'd': do_add_date = 1;            break;
1859d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'z': do_zip_file = 1;            break;
1860d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'o': use_outfile = optarg;       break;
1861d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 's': use_socket = 1;             break;
1862d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'S': use_control_socket = 1;     break;
1863d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'v': show_header_only = true;    break;
1864d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'q': do_vibrate = 0;             break;
1865d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'p': do_fb = 1;                  break;
18669a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            case 'P': ds.update_progress_ = true; break;
1867d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'R': is_remote_mode = 1;         break;
1868d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'B': do_broadcast = 1;           break;
1869d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            case 'V':                             break; // compatibility no-op
18704a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            case 'h':
18714a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme                ShowUsageAndExit(0);
18724a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme                break;
18734a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme            default:
18744a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme                fprintf(stderr, "Invalid option: %c\n", c);
18754a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme                ShowUsageAndExit();
1876e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme                // clang-format on
1877f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross        }
1878f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    }
1879f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
1880d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    // TODO: use helper function to convert argv into a string
1881d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    for (int i = 0; i < argc; i++) {
1882d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        ds.args_ += argv[i];
1883d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        if (i < argc - 1) {
1884d071c6802a03031b26de7b92a76d03849681149bFelipe Leme            ds.args_ += " ";
1885d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        }
1886d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    }
1887d071c6802a03031b26de7b92a76d03849681149bFelipe Leme
1888d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    ds.extra_options_ = android::base::GetProperty(PROPERTY_EXTRA_OPTIONS, "");
18899a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (!ds.extra_options_.empty()) {
18909ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme        // Framework uses a system property to override some command-line args.
18919ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme        // Currently, it contains the type of the requested bugreport.
18929a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        if (ds.extra_options_ == "bugreportplus") {
189375876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme            // Currently, the dumpstate binder is only used by Shell to update progress.
189475876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme            do_start_service = true;
18959a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.update_progress_ = true;
18969ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme            do_fb = 0;
18979a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        } else if (ds.extra_options_ == "bugreportremote") {
18989ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme            do_vibrate = 0;
18999ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme            is_remote_mode = 1;
19009ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme            do_fb = 0;
19019a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        } else if (ds.extra_options_ == "bugreportwear") {
1902446125176065d1d253583f455d1e708044004352lingfan            do_start_service = true;
19039a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.update_progress_ = true;
190446edde3cd8d4bb4eb3765ba5760591127f2e57fdAlain Vongsouvanh            do_zip_file = 1;
19056ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        } else if (ds.extra_options_ == "bugreporttelephony") {
19066ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme            telephony_only = true;
1907253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal        } else if (ds.extra_options_ == "bugreportwifi") {
1908253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal            wifi_only = true;
1909253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal            do_zip_file = 1;
19109ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme        } else {
19119a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            MYLOGE("Unknown extra option: %s\n", ds.extra_options_.c_str());
19129ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme        }
19139ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme        // Reset the property
191496c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme        android::base::SetProperty(PROPERTY_EXTRA_OPTIONS, "");
19159ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme    }
19169ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme
1917b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla    ds.notification_title = android::base::GetProperty(PROPERTY_EXTRA_TITLE, "");
1918b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla    if (!ds.notification_title.empty()) {
1919b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla        // Reset the property
1920b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla        android::base::SetProperty(PROPERTY_EXTRA_TITLE, "");
1921b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla
1922b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla        ds.notification_description = android::base::GetProperty(PROPERTY_EXTRA_DESCRIPTION, "");
1923b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla        if (!ds.notification_description.empty()) {
1924b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla            // Reset the property
1925b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla            android::base::SetProperty(PROPERTY_EXTRA_DESCRIPTION, "");
1926b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla        }
1927b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla        MYLOGD("notification (title:  %s, description: %s)\n",
1928b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla               ds.notification_title.c_str(), ds.notification_description.c_str());
1929b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla    }
1930b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla
19319a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if ((do_zip_file || do_add_date || ds.update_progress_ || do_broadcast) && !use_outfile) {
19324a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme        ExitOnInvalidArgs();
19336e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme    }
19346e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme
19352628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme    if (use_control_socket && !do_zip_file) {
19364a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme        ExitOnInvalidArgs();
19372628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme    }
19382628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme
19399a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (ds.update_progress_ && !do_broadcast) {
19404a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme        ExitOnInvalidArgs();
194171bbfc57974331dce79242ce806d92035fce06baFelipe Leme    }
19426e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme
19439a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (is_remote_mode && (ds.update_progress_ || !do_broadcast || !do_zip_file || !do_add_date)) {
19444a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme        ExitOnInvalidArgs();
19454db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski    }
19464db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski
1947d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    if (ds.version_ == VERSION_DEFAULT) {
1948d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        ds.version_ = VERSION_CURRENT;
1949d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    }
1950d071c6802a03031b26de7b92a76d03849681149bFelipe Leme
195164afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair    if (ds.version_ != VERSION_CURRENT && ds.version_ != VERSION_SPLIT_ANR) {
195264afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair        MYLOGE("invalid version requested ('%s'); suppported values are: ('%s', '%s', '%s')\n",
195364afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair               ds.version_.c_str(), VERSION_DEFAULT.c_str(), VERSION_CURRENT.c_str(),
195464afc024d760e31f3f41e0c5cb8fc543c9392ef1Vishnu Nair               VERSION_SPLIT_ANR.c_str());
1955d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        exit(1);
1956809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme    }
1957809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme
1958d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    if (show_header_only) {
1959d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        ds.PrintHeader();
1960d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        exit(0);
1961809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme    }
1962809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme
19637447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    /* redirect output if needed */
19647447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    bool is_redirecting = !use_socket && use_outfile;
19657447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme
19667447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    // TODO: temporarily set progress until it's part of the Dumpstate constructor
19677447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    std::string stats_path =
19687447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme        is_redirecting ? android::base::StringPrintf("%s/dumpstate-stats.txt", dirname(use_outfile))
19697447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme                       : "";
19707447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    ds.progress_.reset(new Progress(stats_path));
19717447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme
1972d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    /* gets the sequential id */
19737447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    uint32_t last_id = android::base::GetIntProperty(PROPERTY_LAST_ID, 0);
1974d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    ds.id_ = ++last_id;
1975d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    android::base::SetProperty(PROPERTY_LAST_ID, std::to_string(last_id));
1976d071c6802a03031b26de7b92a76d03849681149bFelipe Leme
1977d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    MYLOGI("begin\n");
1978d071c6802a03031b26de7b92a76d03849681149bFelipe Leme
19796ae5c4f52b55943a7a84fb3cb47710effe788e11Felipe Leme    register_sig_handler();
1980d071c6802a03031b26de7b92a76d03849681149bFelipe Leme
198175876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme    if (do_start_service) {
198275876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme        MYLOGI("Starting 'dumpstate' service\n");
198375876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme        android::status_t ret;
198475876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme        if ((ret = android::os::DumpstateService::Start()) != android::OK) {
198575876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme            MYLOGE("Unable to start DumpstateService: %d\n", ret);
198675876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme        }
198775876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme    }
198875876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme
1989f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme    if (PropertiesHelper::IsDryRun()) {
1990d071c6802a03031b26de7b92a76d03849681149bFelipe Leme        MYLOGI("Running on dry-run mode (to disable it, call 'setprop dumpstate.dry_run false')\n");
1991d071c6802a03031b26de7b92a76d03849681149bFelipe Leme    }
1992d071c6802a03031b26de7b92a76d03849681149bFelipe Leme
19937447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    MYLOGI("dumpstate info: id=%d, args='%s', extra_options= %s)\n", ds.id_, ds.args_.c_str(),
1994d071c6802a03031b26de7b92a76d03849681149bFelipe Leme           ds.extra_options_.c_str());
1995d071c6802a03031b26de7b92a76d03849681149bFelipe Leme
1996bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme    MYLOGI("bugreport format version: %s\n", ds.version_.c_str());
1997809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme
19989a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    ds.do_early_screenshot_ = ds.update_progress_;
1999e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme
2000ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris    // If we are going to use a socket, do it as early as possible
2001ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris    // to avoid timeouts from bugreport.
2002ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris    if (use_socket) {
2003ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris        redirect_to_socket(stdout, "dumpstate");
2004ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris    }
2005ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris
20062628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme    if (use_control_socket) {
20072628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme        MYLOGD("Opening control socket\n");
20089a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        ds.control_socket_fd_ = open_socket("dumpstate");
20099a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        ds.update_progress_ = 1;
20102628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme    }
20112628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme
201271bbfc57974331dce79242ce806d92035fce06baFelipe Leme    if (is_redirecting) {
20139a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        ds.bugreport_dir_ = dirname(use_outfile);
2014f8124bd485e29fa013313426463dfe1647e69765Felipe Leme        std::string build_id = android::base::GetProperty("ro.build.id", "UNKNOWN_BUILD");
2015570e6ec1230c9e3458e0de57ebfe2aa2be043293Ian Pedowitz        std::string device_name = android::base::GetProperty("ro.product.name", "UNKNOWN_DEVICE");
2016f8124bd485e29fa013313426463dfe1647e69765Felipe Leme        ds.base_name_ = android::base::StringPrintf("%s-%s-%s", basename(use_outfile),
2017f8124bd485e29fa013313426463dfe1647e69765Felipe Leme                                                    device_name.c_str(), build_id.c_str());
201871bbfc57974331dce79242ce806d92035fce06baFelipe Leme        if (do_add_date) {
201971bbfc57974331dce79242ce806d92035fce06baFelipe Leme            char date[80];
2020bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme            strftime(date, sizeof(date), "%Y-%m-%d-%H-%M-%S", localtime(&ds.now_));
20212b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme            ds.name_ = date;
2022ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme        } else {
20232b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme            ds.name_ = "undated";
202471bbfc57974331dce79242ce806d92035fce06baFelipe Leme        }
20256ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme
20266ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        if (telephony_only) {
20276ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme            ds.base_name_ += "-telephony";
2028253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal        } else if (wifi_only) {
2029253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal            ds.base_name_ += "-wifi";
20306ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        }
20316ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme
203271bbfc57974331dce79242ce806d92035fce06baFelipe Leme        if (do_fb) {
20339a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.screenshot_path_ = ds.GetPath(".png");
203471bbfc57974331dce79242ce806d92035fce06baFelipe Leme        }
20359a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        ds.tmp_path_ = ds.GetPath(".tmp");
203675876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme        ds.log_path_ = ds.GetPath("-dumpstate_log-" + std::to_string(ds.pid_) + ".txt");
2037e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme
2038e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme        MYLOGD(
2039e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme            "Bugreport dir: %s\n"
2040e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme            "Base name: %s\n"
2041e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme            "Suffix: %s\n"
2042e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme            "Log path: %s\n"
2043e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme            "Temporary path: %s\n"
2044e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme            "Screenshot path: %s\n",
20459a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.bugreport_dir_.c_str(), ds.base_name_.c_str(), ds.name_.c_str(),
20469a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.log_path_.c_str(), ds.tmp_path_.c_str(), ds.screenshot_path_.c_str());
204771bbfc57974331dce79242ce806d92035fce06baFelipe Leme
20481e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme        if (do_zip_file) {
20499a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.path_ = ds.GetPath(".zip");
20509a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            MYLOGD("Creating initial .zip file (%s)\n", ds.path_.c_str());
20519a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            create_parent_dirs(ds.path_.c_str());
20529a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.zip_file.reset(fopen(ds.path_.c_str(), "wb"));
20531d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme            if (ds.zip_file == nullptr) {
20549a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                MYLOGE("fopen(%s, 'wb'): %s\n", ds.path_.c_str(), strerror(errno));
20551e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme                do_zip_file = 0;
20561e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme            } else {
2057c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme                ds.zip_writer_.reset(new ZipWriter(ds.zip_file.get()));
20581e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme            }
20591d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme            ds.AddTextZipEntry("version.txt", ds.version_);
20601e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme        }
20611e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme
20629a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        if (ds.update_progress_) {
2063dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme            if (do_broadcast) {
2064dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme                // clang-format off
2065cfaa07ad3207cc2b64586f388ecad95d60082c88Christopher Tate
2066dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme                std::vector<std::string> am_args = {
2067a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme                     "--receiver-permission", "android.permission.DUMP",
20682b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme                     "--es", "android.intent.extra.NAME", ds.name_,
2069e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme                     "--ei", "android.intent.extra.ID", std::to_string(ds.id_),
207075876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme                     "--ei", "android.intent.extra.PID", std::to_string(ds.pid_),
20717447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme                     "--ei", "android.intent.extra.MAX", std::to_string(ds.progress_->GetMax()),
2072dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme                };
2073dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme                // clang-format on
2074a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme                SendBroadcast("com.android.internal.intent.action.BUGREPORT_STARTED", am_args);
2075dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme            }
2076aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme            if (use_control_socket) {
20779a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                dprintf(ds.control_socket_fd_, "BEGIN:%s\n", ds.path_.c_str());
2078aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme            }
207971bbfc57974331dce79242ce806d92035fce06baFelipe Leme        }
208071bbfc57974331dce79242ce806d92035fce06baFelipe Leme    }
208171bbfc57974331dce79242ce806d92035fce06baFelipe Leme
2082f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich    /* read /proc/cmdline before dropping root */
2083f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich    FILE *cmdline = fopen("/proc/cmdline", "re");
2084f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich    if (cmdline) {
2085f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich        fgets(cmdline_buf, sizeof(cmdline_buf), cmdline);
2086f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich        fclose(cmdline);
2087f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich    }
2088f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich
20891f794c442cc63f7962c21e8e712adeca338af63eJohn Michelau    if (do_vibrate) {
209035b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme        Vibrate(150);
20911f794c442cc63f7962c21e8e712adeca338af63eJohn Michelau    }
2092f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
20939a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (do_fb && ds.do_early_screenshot_) {
20949a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        if (ds.screenshot_path_.empty()) {
20953634a1e3459cb609da709646107e246cafbc01f9Felipe Leme            // should not have happened
2096cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme            MYLOGE("INTERNAL ERROR: skipping early screenshot because path was not set\n");
20973634a1e3459cb609da709646107e246cafbc01f9Felipe Leme        } else {
2098cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme            MYLOGI("taking early screenshot\n");
2099bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme            ds.TakeScreenshot();
2100e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme        }
2101e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme    }
2102e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme
21031e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme    if (do_zip_file) {
21049a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        if (chown(ds.path_.c_str(), AID_SHELL, AID_SHELL)) {
21059a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            MYLOGE("Unable to change ownership of zip file %s: %s\n", ds.path_.c_str(),
21061d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme                   strerror(errno));
21071e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme        }
21081e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme    }
21091e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme
211071bbfc57974331dce79242ce806d92035fce06baFelipe Leme    if (is_redirecting) {
211120cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nair        TEMP_FAILURE_RETRY(dup_stderr_fd = dup(fileno(stderr)));
21129a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        redirect_to_file(stderr, const_cast<char*>(ds.log_path_.c_str()));
21139a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        if (chown(ds.log_path_.c_str(), AID_SHELL, AID_SHELL)) {
21149a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            MYLOGE("Unable to change ownership of dumpstate log file %s: %s\n",
21159a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                   ds.log_path_.c_str(), strerror(errno));
21166fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme        }
211720cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nair        TEMP_FAILURE_RETRY(dup_stdout_fd = dup(fileno(stdout)));
21186e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        /* TODO: rather than generating a text file now and zipping it later,
21196e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme           it would be more efficient to redirect stdout to the zip entry
21206e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme           directly, but the libziparchive doesn't support that option yet. */
21219a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        redirect_to_file(stdout, const_cast<char*>(ds.tmp_path_.c_str()));
21229a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        if (chown(ds.tmp_path_.c_str(), AID_SHELL, AID_SHELL)) {
21236fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme            MYLOGE("Unable to change ownership of temporary bugreport file %s: %s\n",
21249a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                   ds.tmp_path_.c_str(), strerror(errno));
21256fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme        }
2126f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    }
2127d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme
2128d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    // Don't buffer stdout
2129d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme    setvbuf(stdout, nullptr, _IONBF, 0);
2130d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme
2131608385dd151e36a93f3e3f4a7514b1e720d20ae9Felipe Leme    // NOTE: there should be no stdout output until now, otherwise it would break the header.
2132608385dd151e36a93f3e3f4a7514b1e720d20ae9Felipe Leme    // In particular, DurationReport objects should be created passing 'title, NULL', so their
2133cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme    // duration is logged into MYLOG instead.
2134bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme    ds.PrintHeader();
2135f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
21366ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    if (telephony_only) {
2137a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C        DumpstateTelephonyOnly();
21386ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        ds.DumpstateBoard();
2139253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal    } else if (wifi_only) {
2140253dad4af7ed9df588d5b1403f7c95f9610c72efmukesh agrawal        DumpstateWifiOnly();
21416ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    } else {
21426ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // Dumps systrace right away, otherwise it will be filled with unnecessary events.
21436ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // First try to dump anrd trace if the daemon is running. Otherwise, dump
21446ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // the raw trace.
21456ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        if (!dump_anrd_trace()) {
21466ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme            dump_systrace();
21476ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        }
214871a74ac75c8687195d27642fa0db31a796102c59Felipe Leme
21496ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // Invoking the following dumpsys calls before dump_traces() to try and
21506ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // keep the system stats as close to its initial state as possible.
2151780b1283e6d219e1ef3cb061f5096dcb359d88caVishnu Nair        RunDumpsysCritical();
2152fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan
21536ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // TODO: Drop root user and move into dumpstate() once b/28633932 is fixed.
21546ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        dump_raft();
2155e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme
21566ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        /* collect stack traces from Dalvik and native processes (needs root) */
21576ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        dump_traces_path = dump_traces();
2158fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan
21596ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        /* Run some operations that require root. */
21605f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez        ds.tombstone_data_ = GetDumpFds(TOMBSTONE_DIR, TOMBSTONE_FILE_PREFIX, !ds.IsZipping());
21615f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez        ds.anr_data_ = GetDumpFds(ANR_DIR, ANR_FILE_PREFIX, !ds.IsZipping());
21628f788290f89c0782ca5cf2d1feaa81250295c5faNarayan Kamath
21636ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        ds.AddDir(RECOVERY_DIR, true);
21646ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        ds.AddDir(RECOVERY_DATA_DIR, true);
21651b34605e92179f2b1c37cc9f101d985750838d9dTianjie Xu        ds.AddDir(UPDATE_ENGINE_LOG_DIR, true);
21666ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        ds.AddDir(LOGPERSIST_DATA_DIR, false);
21676ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        if (!PropertiesHelper::IsUserBuild()) {
21686ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme            ds.AddDir(PROFILE_DATA_DIR_CUR, true);
21696ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme            ds.AddDir(PROFILE_DATA_DIR_REF, true);
21706ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        }
21716ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        add_mountinfo();
2172a94c71732290dd6bba937548bbe748785dd43ab0Jayachandran C        DumpIpTablesAsRoot();
2173fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan
21746ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // Capture any IPSec policies in play.  No keys are exposed here.
21756ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        RunCommand("IP XFRM POLICY", {"ip", "xfrm", "policy"},
21766ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme                   CommandOptions::WithTimeout(10).Build());
217732af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline
21786ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        // Run ss as root so we can see socket marks.
21796ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        RunCommand("DETAILED SOCKET STATE", {"ss", "-eionptu"},
21806ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme                   CommandOptions::WithTimeout(10).Build());
2181d3b809baff20a2ff7e41f4add801f71cce0665f7Lorenzo Colitti
21823cd671e868a3648a4ca00c3e0b063e983d34b702Jin Qian        // Run iotop as root to show top 100 IO threads
21833cd671e868a3648a4ca00c3e0b063e983d34b702Jin Qian        RunCommand("IOTOP", {"iotop", "-n", "1", "-m", "100"});
21843cd671e868a3648a4ca00c3e0b063e983d34b702Jin Qian
21856ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        if (!DropRootUser()) {
21866ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme            return -1;
21876ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        }
2188fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan
21896ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme        dumpstate();
21906ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme    }
2191f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
219255b42a67f69767976ff16ab443b3e7142db693e1Felipe Leme    /* close output if needed */
219371bbfc57974331dce79242ce806d92035fce06baFelipe Leme    if (is_redirecting) {
219420cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nair        TEMP_FAILURE_RETRY(dup2(dup_stdout_fd, fileno(stdout)));
2195f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    }
2196f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
21976e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme    /* rename or zip the (now complete) .tmp file to its final location */
21986e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme    if (use_outfile) {
2199ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme
2200ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme        /* check if user changed the suffix using system properties */
220196c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme        std::string name = android::base::GetProperty(
220275876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme            android::base::StringPrintf("dumpstate.%d.name", ds.pid_), "");
2203ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme        bool change_suffix= false;
220496c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme        if (!name.empty()) {
2205ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme            /* must whitelist which characters are allowed, otherwise it could cross directories */
2206ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme            std::regex valid_regex("^[-_a-zA-Z0-9]+$");
220796c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme            if (std::regex_match(name.c_str(), valid_regex)) {
2208ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme                change_suffix = true;
2209ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme            } else {
221096c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme                MYLOGE("invalid suffix provided by user: %s\n", name.c_str());
2211ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme            }
2212ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme        }
2213ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme        if (change_suffix) {
22142b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme            MYLOGI("changing suffix from %s to %s\n", ds.name_.c_str(), name.c_str());
22152b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme            ds.name_ = name;
22169a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            if (!ds.screenshot_path_.empty()) {
22179a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                std::string new_screenshot_path = ds.GetPath(".png");
22189a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                if (rename(ds.screenshot_path_.c_str(), new_screenshot_path.c_str())) {
22199a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                    MYLOGE("rename(%s, %s): %s\n", ds.screenshot_path_.c_str(),
22209a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                           new_screenshot_path.c_str(), strerror(errno));
2221ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme                } else {
22229a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                    ds.screenshot_path_ = new_screenshot_path;
2223ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme                }
2224ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme            }
2225ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme        }
2226ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme
22276e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        bool do_text_file = true;
22286e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        if (do_zip_file) {
22291d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme            if (!ds.FinishZipFile()) {
2230cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme                MYLOGE("Failed to finish zip file; sending text bugreport instead\n");
22316e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme                do_text_file = true;
22326e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme            } else {
22336e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme                do_text_file = false;
22349127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme                // Since zip file is already created, it needs to be renamed.
22359a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                std::string new_path = ds.GetPath(".zip");
22369a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                if (ds.path_ != new_path) {
22379a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                    MYLOGD("Renaming zip file from %s to %s\n", ds.path_.c_str(), new_path.c_str());
22389a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                    if (rename(ds.path_.c_str(), new_path.c_str())) {
22399a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                        MYLOGE("rename(%s, %s): %s\n", ds.path_.c_str(), new_path.c_str(),
22401d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme                               strerror(errno));
22419127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme                    } else {
22429a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                        ds.path_ = new_path;
22439127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme                    }
22449127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme                }
22456e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme            }
22466e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        }
22476e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        if (do_text_file) {
22489a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            ds.path_ = ds.GetPath(".txt");
22499a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            MYLOGD("Generating .txt bugreport at %s from %s\n", ds.path_.c_str(),
22509a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                   ds.tmp_path_.c_str());
22519a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            if (rename(ds.tmp_path_.c_str(), ds.path_.c_str())) {
22529a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                MYLOGE("rename(%s, %s): %s\n", ds.tmp_path_.c_str(), ds.path_.c_str(),
22531d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme                       strerror(errno));
22549a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                ds.path_.clear();
22556e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme            }
22566e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        }
22572628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme        if (use_control_socket) {
22582628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme            if (do_text_file) {
22599a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                dprintf(ds.control_socket_fd_,
2260e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme                        "FAIL:could not create zip file, check %s "
2261e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme                        "for more details\n",
22629a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                        ds.log_path_.c_str());
22632628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme            } else {
22649a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                dprintf(ds.control_socket_fd_, "OK:%s\n", ds.path_.c_str());
22652628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme            }
22662628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme        }
2267f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    }
2268f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
2269cc2a2fa64e22378d980ae0ae95c8865ebea05f69Felipe Leme    /* vibrate a few but shortly times to let user know it's finished */
227047f644e774a13c81bf8bda5166e65cd5c5171ef3Takuya Ogawa    if (do_vibrate) {
227147f644e774a13c81bf8bda5166e65cd5c5171ef3Takuya Ogawa        for (int i = 0; i < 3; i++) {
227247f644e774a13c81bf8bda5166e65cd5c5171ef3Takuya Ogawa            Vibrate(75);
227347f644e774a13c81bf8bda5166e65cd5c5171ef3Takuya Ogawa            usleep((75 + 50) * 1000);
227447f644e774a13c81bf8bda5166e65cd5c5171ef3Takuya Ogawa        }
2275cc2a2fa64e22378d980ae0ae95c8865ebea05f69Felipe Leme    }
2276cc2a2fa64e22378d980ae0ae95c8865ebea05f69Felipe Leme
22771dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown    /* tell activity manager we're done */
227871bbfc57974331dce79242ce806d92035fce06baFelipe Leme    if (do_broadcast) {
22799a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        if (!ds.path_.empty()) {
22809a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme            MYLOGI("Final bugreport path: %s\n", ds.path_.c_str());
2281aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme            // clang-format off
2282cfaa07ad3207cc2b64586f388ecad95d60082c88Christopher Tate
228336b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme            std::vector<std::string> am_args = {
2284a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme                 "--receiver-permission", "android.permission.DUMP",
2285e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme                 "--ei", "android.intent.extra.ID", std::to_string(ds.id_),
228675876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme                 "--ei", "android.intent.extra.PID", std::to_string(ds.pid_),
22877447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme                 "--ei", "android.intent.extra.MAX", std::to_string(ds.progress_->GetMax()),
22889a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                 "--es", "android.intent.extra.BUGREPORT", ds.path_,
22899a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                 "--es", "android.intent.extra.DUMPSTATE_LOG", ds.log_path_
229036b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme            };
2291aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme            // clang-format on
229236b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme            if (do_fb) {
229336b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme                am_args.push_back("--es");
229436b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme                am_args.push_back("android.intent.extra.SCREENSHOT");
22959a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                am_args.push_back(ds.screenshot_path_);
229636b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme            }
2297b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla            if (!ds.notification_title.empty()) {
2298b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                am_args.push_back("--es");
2299b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                am_args.push_back("android.intent.extra.TITLE");
2300b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                am_args.push_back(ds.notification_title);
2301b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                if (!ds.notification_description.empty()) {
2302b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                    am_args.push_back("--es");
2303b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                    am_args.push_back("android.intent.extra.DESCRIPTION");
2304b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                    am_args.push_back(ds.notification_description);
2305b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla                }
2306b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla            }
23074db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski            if (is_remote_mode) {
23084db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski                am_args.push_back("--es");
23094db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski                am_args.push_back("android.intent.extra.REMOTE_BUGREPORT_HASH");
23109a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme                am_args.push_back(SHA256_file_hash(ds.path_));
2311a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme                SendBroadcast("com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED",
2312a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme                              am_args);
23134db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski            } else {
2314a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme                SendBroadcast("com.android.internal.intent.action.BUGREPORT_FINISHED", am_args);
23154db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski            }
23166e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        } else {
2317cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme            MYLOGE("Skipping finished broadcast because bugreport could not be generated\n");
23186e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme        }
231927f9e6d849fce956c9b8f1ad5c3d9a954501a76bJeff Sharkey    }
232027f9e6d849fce956c9b8f1ad5c3d9a954501a76bJeff Sharkey
23217447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    MYLOGD("Final progress: %d/%d (estimated %d)\n", ds.progress_->Get(), ds.progress_->GetMax(),
23227447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme           ds.progress_->GetInitialMax());
23237447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    ds.progress_->Save();
23247447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme    MYLOGI("done (id %d)\n", ds.id_);
2325f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross
2326107a05f72e711c92545d0be648ab79c4f858f372Felipe Leme    if (is_redirecting) {
232720cf5036c1f373c1acfbb95295f118b7ff6c2227Vishnu Nair        TEMP_FAILURE_RETRY(dup2(dup_stderr_fd, fileno(stderr)));
2328107a05f72e711c92545d0be648ab79c4f858f372Felipe Leme    }
2329107a05f72e711c92545d0be648ab79c4f858f372Felipe Leme
23309a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme    if (use_control_socket && ds.control_socket_fd_ != -1) {
2331e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme        MYLOGD("Closing control socket\n");
23329a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme        close(ds.control_socket_fd_);
23332628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme    }
23342628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme
23355f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    ds.tombstone_data_.clear();
23365f6ee4a11de1de262cea6465c2f991834b2e4792Luis Hector Chavez    ds.anr_data_.clear();
23376b9516ced325e93880e9c8ef2793380866a1c579Narayan Kamath
2338f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross    return 0;
2339f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross}
2340