blob: 33e764988b7516461fa5fb476e627d616db5fc3f [file] [log] [blame]
Joe Onorato1754d742016-11-21 17:51:35 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Yi Jin4e843102018-02-14 15:36:18 -080016#define DEBUG false
Yi Jinb592e3b2018-02-01 15:17:04 -080017#include "Log.h"
Joe Onorato1754d742016-11-21 17:51:35 -080018
19#include "Section.h"
Yi Jin99c248f2017-08-25 18:11:58 -070020
Kweku Adamseadd1232018-02-05 16:45:13 -080021#include <dirent.h>
22#include <errno.h>
Yi Jin3c034c92017-12-22 17:36:47 -080023#include <mutex>
Kweku Adamseadd1232018-02-05 16:45:13 -080024#include <set>
Mike Ma5510f7c2020-02-19 02:56:04 -080025#include <thread>
Joe Onorato1754d742016-11-21 17:51:35 -080026
Yi Jinb592e3b2018-02-01 15:17:04 -080027#include <android-base/file.h>
Joe Onoratofe7bbf42019-03-24 20:57:16 -070028#include <android-base/properties.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080029#include <android-base/stringprintf.h>
Yi Jinc23fad22017-09-15 17:24:59 -070030#include <android/util/protobuf.h>
Joe Onorato99598ee2019-02-11 15:55:13 +000031#include <android/util/ProtoOutputStream.h>
Joe Onorato1754d742016-11-21 17:51:35 -080032#include <binder/IServiceManager.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080033#include <debuggerd/client.h>
34#include <dumputils/dump_utils.h>
Yi Jin3c034c92017-12-22 17:36:47 -080035#include <log/log_event_list.h>
Yi Jin3c034c92017-12-22 17:36:47 -080036#include <log/log_read.h>
Yi Jinb592e3b2018-02-01 15:17:04 -080037#include <log/logprint.h>
Yi Jin3c034c92017-12-22 17:36:47 -080038#include <private/android_logger.h>
Mike Ma892ccd92020-03-20 16:30:37 -070039#include <sys/mman.h>
Yi Jin3c034c92017-12-22 17:36:47 -080040
41#include "FdBuffer.h"
Yi Jin3c034c92017-12-22 17:36:47 -080042#include "Privacy.h"
Kweku Adamseadd1232018-02-05 16:45:13 -080043#include "frameworks/base/core/proto/android/os/backtrace.proto.h"
Yi Jin1a11fa12018-02-22 16:44:10 -080044#include "frameworks/base/core/proto/android/os/data.proto.h"
Yi Jinb592e3b2018-02-01 15:17:04 -080045#include "frameworks/base/core/proto/android/util/log.proto.h"
Mike Ma5510f7c2020-02-19 02:56:04 -080046#include "frameworks/base/core/proto/android/util/textdump.proto.h"
Yi Jinb592e3b2018-02-01 15:17:04 -080047#include "incidentd_util.h"
Joe Onorato1754d742016-11-21 17:51:35 -080048
Yi Jin6cacbcb2018-03-30 14:04:52 -070049namespace android {
50namespace os {
51namespace incidentd {
52
Yi Jinb592e3b2018-02-01 15:17:04 -080053using namespace android::base;
Yi Jinc23fad22017-09-15 17:24:59 -070054using namespace android::util;
Joe Onorato1754d742016-11-21 17:51:35 -080055
Yi Jinc23fad22017-09-15 17:24:59 -070056// special section ids
Yi Jin329130b2018-02-09 16:47:47 -080057const int FIELD_ID_INCIDENT_METADATA = 2;
Yi Jinc23fad22017-09-15 17:24:59 -070058
59// incident section parameters
Yi Jin3c034c92017-12-22 17:36:47 -080060const char INCIDENT_HELPER[] = "/system/bin/incident_helper";
Yi Jinc36e91d2018-03-08 11:25:58 -080061const char* GZIP[] = {"/system/bin/gzip", NULL};
Yi Jinb44f7d42017-07-21 12:12:59 -070062
Yi Jin1a11fa12018-02-22 16:44:10 -080063static pid_t fork_execute_incident_helper(const int id, Fpipe* p2cPipe, Fpipe* c2pPipe) {
Yi Jinb592e3b2018-02-01 15:17:04 -080064 const char* ihArgs[]{INCIDENT_HELPER, "-s", String8::format("%d", id).string(), NULL};
Yi Jinc36e91d2018-03-08 11:25:58 -080065 return fork_execute_cmd(const_cast<char**>(ihArgs), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -070066}
67
Joe Onorato7a406b42019-04-12 18:11:30 -070068bool section_requires_specific_mention(int sectionId) {
69 switch (sectionId) {
70 case 3025: // restricted_images
71 return true;
Ryan Savitskicc7d9972019-06-03 23:57:09 +010072 case 3026: // system_trace
73 return true;
Joe Onorato7a406b42019-04-12 18:11:30 -070074 default:
75 return false;
76 }
77}
78
Yi Jin99c248f2017-08-25 18:11:58 -070079// ================================================================================
Joe Onoratofe7bbf42019-03-24 20:57:16 -070080Section::Section(int i, int64_t timeoutMs)
Kweku Adams3d160912018-05-07 11:26:27 -070081 : id(i),
Joe Onoratofe7bbf42019-03-24 20:57:16 -070082 timeoutMs(timeoutMs) {
83}
Joe Onorato1754d742016-11-21 17:51:35 -080084
Yi Jinb592e3b2018-02-01 15:17:04 -080085Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -080086
Joe Onorato1754d742016-11-21 17:51:35 -080087// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -080088static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
89
Kweku Adamse04ef772018-06-13 12:24:38 -070090FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Joe Onoratofe7bbf42019-03-24 20:57:16 -070091 : Section(id, timeoutMs), mFilename(filename) {
Yi Jin3be0b432018-04-20 17:08:11 -070092 name = "file ";
93 name += filename;
Yi Jin1a11fa12018-02-22 16:44:10 -080094 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -070095}
96
97FileSection::~FileSection() {}
98
Joe Onorato99598ee2019-02-11 15:55:13 +000099status_t FileSection::Execute(ReportWriter* writer) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700100 // read from mFilename first, make sure the file is available
101 // add O_CLOEXEC to make sure it is closed when exec incident helper
Yi Jin6355d2f2018-03-14 15:18:02 -0700102 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
103 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700104 ALOGW("[%s] failed to open file", this->name.string());
Kweku Adamse04ef772018-06-13 12:24:38 -0700105 // There may be some devices/architectures that won't have the file.
106 // Just return here without an error.
107 return NO_ERROR;
Yi Jin0a3406f2017-06-22 19:23:11 -0700108 }
109
Yi Jinb44f7d42017-07-21 12:12:59 -0700110 Fpipe p2cPipe;
111 Fpipe c2pPipe;
112 // initiate pipes to pass data to/from incident_helper
113 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700114 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700115 return -errno;
116 }
117
Yi Jin1a11fa12018-02-22 16:44:10 -0800118 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700119 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700120 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700121 return -errno;
122 }
123
124 // parent process
Mike Ma892ccd92020-03-20 16:30:37 -0700125 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700126 status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
127 std::move(c2pPipe.readFd()),
128 this->timeoutMs, mIsSysfs);
Joe Onorato99598ee2019-02-11 15:55:13 +0000129 writer->setSectionStats(buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700130 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700131 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800132 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800133 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700134 return readStatus;
135 }
136
Yi Jinedfd5bb2017-09-06 17:09:11 -0700137 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700138 if (ihStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700139 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-ihStatus));
Mike Ma5510f7c2020-02-19 02:56:04 -0800140 return OK; // Not a fatal error.
Yi Jinb44f7d42017-07-21 12:12:59 -0700141 }
142
Joe Onorato99598ee2019-02-11 15:55:13 +0000143 return writer->writeSection(buffer);
Yi Jin0a3406f2017-06-22 19:23:11 -0700144}
Yi Jin1a11fa12018-02-22 16:44:10 -0800145// ================================================================================
146GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800147 va_list args;
148 va_start(args, filename);
149 mFilenames = varargs(filename, args);
150 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800151 name = "gzip";
152 for (int i = 0; mFilenames[i] != NULL; i++) {
153 name += " ";
154 name += mFilenames[i];
155 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800156}
Yi Jin0a3406f2017-06-22 19:23:11 -0700157
Yi Jin480de782018-04-06 15:37:36 -0700158GZipSection::~GZipSection() { free(mFilenames); }
Yi Jin1a11fa12018-02-22 16:44:10 -0800159
Joe Onorato99598ee2019-02-11 15:55:13 +0000160status_t GZipSection::Execute(ReportWriter* writer) const {
Yi Jin1a11fa12018-02-22 16:44:10 -0800161 // Reads the files in order, use the first available one.
162 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700163 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800164 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700165 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
166 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800167 break;
168 }
169 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
170 index++; // look at the next file.
171 }
Yi Jinc858e272018-03-28 15:32:50 -0700172 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700173 ALOGW("[%s] can't open all the files", this->name.string());
Yi Jin6cacbcb2018-03-30 14:04:52 -0700174 return NO_ERROR; // e.g. LAST_KMSG will reach here in user build.
Yi Jinc858e272018-03-28 15:32:50 -0700175 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800176 FdBuffer buffer;
177 Fpipe p2cPipe;
178 Fpipe c2pPipe;
179 // initiate pipes to pass data to/from gzip
180 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700181 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800182 return -errno;
183 }
184
Yi Jinc36e91d2018-03-08 11:25:58 -0800185 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800186 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700187 ALOGW("[%s] failed to fork", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800188 return -errno;
189 }
190 // parent process
191
192 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
193 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
Joe Onorato99598ee2019-02-11 15:55:13 +0000194 sp<EncodedBuffer> internalBuffer = buffer.data();
Yi Jin1a11fa12018-02-22 16:44:10 -0800195 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700196 size_t fileLen = strlen(mFilenames[index]);
197 internalBuffer->writeRawVarint32(fileLen);
198 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800199 internalBuffer->writeRawByte(mFilenames[index][i]);
200 }
201 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
202 WIRE_TYPE_LENGTH_DELIMITED);
203 size_t editPos = internalBuffer->wp()->pos();
204 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
205 size_t dataBeginAt = internalBuffer->wp()->pos();
Yi Jin3be0b432018-04-20 17:08:11 -0700206 VLOG("[%s] editPos=%zu, dataBeginAt=%zu", this->name.string(), editPos, dataBeginAt);
Yi Jin1a11fa12018-02-22 16:44:10 -0800207
Yi Jine3dab2d2018-03-22 16:56:39 -0700208 status_t readStatus = buffer.readProcessedDataInStream(
209 fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
210 isSysfs(mFilenames[index]));
Joe Onorato99598ee2019-02-11 15:55:13 +0000211 writer->setSectionStats(buffer);
Yi Jin1a11fa12018-02-22 16:44:10 -0800212 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700213 ALOGW("[%s] failed to read data from gzip: %s, timedout: %s", this->name.string(),
214 strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin1a11fa12018-02-22 16:44:10 -0800215 kill_child(pid);
216 return readStatus;
217 }
218
219 status_t gzipStatus = wait_child(pid);
220 if (gzipStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700221 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-gzipStatus));
Yi Jin1a11fa12018-02-22 16:44:10 -0800222 return gzipStatus;
223 }
224 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
225 size_t dataSize = buffer.size() - dataBeginAt;
226 internalBuffer->wp()->rewind()->move(editPos);
227 internalBuffer->writeRawVarint32(dataSize);
228 internalBuffer->copy(dataBeginAt, dataSize);
Yi Jin1a11fa12018-02-22 16:44:10 -0800229
Joe Onorato99598ee2019-02-11 15:55:13 +0000230 return writer->writeSection(buffer);
Yi Jin1a11fa12018-02-22 16:44:10 -0800231}
Kweku Adamseadd1232018-02-05 16:45:13 -0800232
Yi Jin0a3406f2017-06-22 19:23:11 -0700233// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800234struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800235 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700236 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800237
238 // Lock protects these fields
Mike Ma5510f7c2020-02-19 02:56:04 -0800239 std::mutex lock;
Joe Onorato1754d742016-11-21 17:51:35 -0800240 bool workerDone;
241 status_t workerError;
242
Chih-Hung Hsieh7a88a932018-12-20 13:45:04 -0800243 explicit WorkerThreadData(const WorkerThreadSection* section);
Joe Onorato1754d742016-11-21 17:51:35 -0800244 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800245};
246
247WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700248 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800249
Yi Jinb592e3b2018-02-01 15:17:04 -0800250WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800251
252// ================================================================================
Joe Onoratofe7bbf42019-03-24 20:57:16 -0700253WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
254 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800255
Yi Jinb592e3b2018-02-01 15:17:04 -0800256WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800257
Kweku Adams5b763c12018-09-13 15:44:58 -0700258void sigpipe_handler(int signum) {
259 if (signum == SIGPIPE) {
260 ALOGE("Wrote to a broken pipe\n");
261 } else {
262 ALOGE("Received unexpected signal: %d\n", signum);
263 }
264}
265
Joe Onorato99598ee2019-02-11 15:55:13 +0000266status_t WorkerThreadSection::Execute(ReportWriter* writer) const {
Mike Mab328e292020-03-18 01:52:36 -0700267 // Create shared data and pipe. Don't put data on the stack since this thread may exit early.
268 sp<WorkerThreadData> data = new WorkerThreadData(this);
269 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800270 return -errno;
271 }
Mike Mab328e292020-03-18 01:52:36 -0700272 data->incStrong(this);
273 std::thread([data, this]() {
Mike Ma5510f7c2020-02-19 02:56:04 -0800274 // Don't crash the service if writing to a closed pipe (may happen if dumping times out)
275 signal(SIGPIPE, sigpipe_handler);
Mike Mab328e292020-03-18 01:52:36 -0700276 status_t err = data->section->BlockingCall(data->pipe.writeFd());
Mike Ma5510f7c2020-02-19 02:56:04 -0800277 {
Mike Mab328e292020-03-18 01:52:36 -0700278 std::scoped_lock<std::mutex> lock(data->lock);
279 data->workerDone = true;
280 data->workerError = err;
Mike Ma5510f7c2020-02-19 02:56:04 -0800281 // unique_fd is not thread safe. If we don't lock it, reset() may pause half way while
282 // the other thread executes to the end, calling ~Fpipe, which is a race condition.
Mike Mab328e292020-03-18 01:52:36 -0700283 data->pipe.writeFd().reset();
Mike Ma5510f7c2020-02-19 02:56:04 -0800284 }
Mike Mab328e292020-03-18 01:52:36 -0700285 data->decStrong(this);
Mike Ma5510f7c2020-02-19 02:56:04 -0800286 }).detach();
Joe Onorato1754d742016-11-21 17:51:35 -0800287
288 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Mike Ma87003ad2020-03-19 12:31:29 -0700289 status_t err = NO_ERROR;
290 bool workerDone = false;
291 FdBuffer buffer;
Mike Mab328e292020-03-18 01:52:36 -0700292 err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800293 if (err != NO_ERROR) {
Mike Ma28381692018-12-04 15:46:29 -0800294 ALOGE("[%s] reader failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800295 }
296
Joe Onorato1754d742016-11-21 17:51:35 -0800297 // If the worker side is finished, then return its error (which may overwrite
Mike Ma28381692018-12-04 15:46:29 -0800298 // our possible error -- but it's more interesting anyway). If not, then we timed out.
Joe Onorato1754d742016-11-21 17:51:35 -0800299 {
Mike Mab328e292020-03-18 01:52:36 -0700300 std::scoped_lock<std::mutex> lock(data->lock);
301 data->pipe.close();
302 if (data->workerError != NO_ERROR) {
303 err = data->workerError;
Mike Ma28381692018-12-04 15:46:29 -0800304 ALOGE("[%s] worker failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800305 }
Mike Mab328e292020-03-18 01:52:36 -0700306 workerDone = data->workerDone;
Joe Onorato1754d742016-11-21 17:51:35 -0800307 }
Kweku Adams5b763c12018-09-13 15:44:58 -0700308
Joe Onorato99598ee2019-02-11 15:55:13 +0000309 writer->setSectionStats(buffer);
Mike Ma28381692018-12-04 15:46:29 -0800310 if (err != NO_ERROR) {
311 char errMsg[128];
312 snprintf(errMsg, 128, "[%s] failed with error '%s'",
313 this->name.string(), strerror(-err));
Joe Onorato99598ee2019-02-11 15:55:13 +0000314 writer->error(this, err, "WorkerThreadSection failed.");
Joe Onorato1754d742016-11-21 17:51:35 -0800315 return NO_ERROR;
316 }
Mike Ma28381692018-12-04 15:46:29 -0800317 if (buffer.truncated()) {
318 ALOGW("[%s] too large, truncating", this->name.string());
Joe Onorato99598ee2019-02-11 15:55:13 +0000319 // Do not write a truncated section. It won't pass through the PrivacyFilter.
Mike Ma28381692018-12-04 15:46:29 -0800320 return NO_ERROR;
321 }
322 if (!workerDone || buffer.timedOut()) {
323 ALOGW("[%s] timed out", this->name.string());
Joe Onorato1754d742016-11-21 17:51:35 -0800324 return NO_ERROR;
325 }
326
327 // Write the data that was collected
Joe Onorato99598ee2019-02-11 15:55:13 +0000328 return writer->writeSection(buffer);
Joe Onorato1754d742016-11-21 17:51:35 -0800329}
330
331// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700332CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800333 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800334 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700335 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800336 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800337 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800338 name = "cmd";
339 for (int i = 0; mCommand[i] != NULL; i++) {
340 name += " ";
341 name += mCommand[i];
342 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700343}
Joe Onorato1754d742016-11-21 17:51:35 -0800344
Yi Jinb592e3b2018-02-01 15:17:04 -0800345CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700346 va_list args;
347 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800348 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800349 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800350 name = "cmd";
351 for (int i = 0; mCommand[i] != NULL; i++) {
352 name += " ";
353 name += mCommand[i];
354 }
Joe Onorato1754d742016-11-21 17:51:35 -0800355}
356
Yi Jinb592e3b2018-02-01 15:17:04 -0800357CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800358
Joe Onorato99598ee2019-02-11 15:55:13 +0000359status_t CommandSection::Execute(ReportWriter* writer) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700360 Fpipe cmdPipe;
361 Fpipe ihPipe;
362
363 if (!cmdPipe.init() || !ihPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700364 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700365 return -errno;
366 }
367
Yi Jinc36e91d2018-03-08 11:25:58 -0800368 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700369 if (cmdPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700370 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700371 return -errno;
372 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800373 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700374 if (ihPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700375 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700376 return -errno;
377 }
378
Yi Jin6355d2f2018-03-14 15:18:02 -0700379 cmdPipe.writeFd().reset();
Mike Ma892ccd92020-03-20 16:30:37 -0700380 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700381 status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
Joe Onorato99598ee2019-02-11 15:55:13 +0000382 writer->setSectionStats(buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700383 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700384 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800385 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800386 kill_child(cmdPid);
387 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700388 return readStatus;
389 }
390
Kweku Adamseadd1232018-02-05 16:45:13 -0800391 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800392 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700393 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800394 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700395 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Joe Onorato99598ee2019-02-11 15:55:13 +0000396 ALOGW("[%s] abnormal child processes, return status: command: %s, incident helper: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800397 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Joe Onorato99598ee2019-02-11 15:55:13 +0000398 // Not a fatal error.
399 return NO_ERROR;
Yi Jinb44f7d42017-07-21 12:12:59 -0700400 }
401
Joe Onorato99598ee2019-02-11 15:55:13 +0000402 return writer->writeSection(buffer);
Joe Onorato1754d742016-11-21 17:51:35 -0800403}
404
405// ================================================================================
Joe Onoratofe7bbf42019-03-24 20:57:16 -0700406DumpsysSection::DumpsysSection(int id, const char* service, ...)
407 : WorkerThreadSection(id, REMOTE_CALL_TIMEOUT_MS), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800408 name = "dumpsys ";
409 name += service;
410
411 va_list args;
412 va_start(args, service);
413 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700414 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800415 if (arg == NULL) {
416 break;
417 }
418 mArgs.add(String16(arg));
419 name += " ";
420 name += arg;
421 }
422 va_end(args);
423}
424
Yi Jinb592e3b2018-02-01 15:17:04 -0800425DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800426
Mike Ma643de922019-12-17 10:56:17 -0800427status_t DumpsysSection::BlockingCall(unique_fd& pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800428 // checkService won't wait for the service to show up like getService will.
429 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700430
Joe Onorato1754d742016-11-21 17:51:35 -0800431 if (service == NULL) {
Joe Onorato1754d742016-11-21 17:51:35 -0800432 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
Mike Ma28381692018-12-04 15:46:29 -0800433 return NAME_NOT_FOUND;
Joe Onorato1754d742016-11-21 17:51:35 -0800434 }
435
Mike Ma643de922019-12-17 10:56:17 -0800436 service->dump(pipeWriteFd.get(), mArgs);
Joe Onorato1754d742016-11-21 17:51:35 -0800437
438 return NO_ERROR;
439}
Yi Jin3c034c92017-12-22 17:36:47 -0800440
441// ================================================================================
Mike Ma5510f7c2020-02-19 02:56:04 -0800442TextDumpsysSection::TextDumpsysSection(int id, const char* service, ...)
Mike Ma87003ad2020-03-19 12:31:29 -0700443 :Section(id), mService(service) {
Mike Ma5510f7c2020-02-19 02:56:04 -0800444 name = "dumpsys ";
445 name += service;
446
447 va_list args;
448 va_start(args, service);
449 while (true) {
450 const char* arg = va_arg(args, const char*);
451 if (arg == NULL) {
452 break;
453 }
454 mArgs.add(String16(arg));
455 name += " ";
456 name += arg;
457 }
458 va_end(args);
459}
460
461TextDumpsysSection::~TextDumpsysSection() {}
462
Mike Ma87003ad2020-03-19 12:31:29 -0700463status_t TextDumpsysSection::Execute(ReportWriter* writer) const {
Mike Ma5510f7c2020-02-19 02:56:04 -0800464 // checkService won't wait for the service to show up like getService will.
465 sp<IBinder> service = defaultServiceManager()->checkService(mService);
466 if (service == NULL) {
467 ALOGW("TextDumpsysSection: Can't lookup service: %s", String8(mService).string());
468 return NAME_NOT_FOUND;
469 }
470
471 // Create pipe
472 Fpipe dumpPipe;
473 if (!dumpPipe.init()) {
474 ALOGW("[%s] failed to setup pipe", this->name.string());
475 return -errno;
476 }
477
478 // Run dumping thread
479 const uint64_t start = Nanotime();
Mike Ma4686c242020-06-05 00:51:22 -0700480 std::thread worker([write_fd = std::move(dumpPipe.writeFd()), service = std::move(service),
481 this]() mutable {
Mike Ma5510f7c2020-02-19 02:56:04 -0800482 // Don't crash the service if writing to a closed pipe (may happen if dumping times out)
483 signal(SIGPIPE, sigpipe_handler);
Mike Ma4686c242020-06-05 00:51:22 -0700484 status_t err = service->dump(write_fd.get(), this->mArgs);
Mike Ma5510f7c2020-02-19 02:56:04 -0800485 if (err != OK) {
486 ALOGW("[%s] dump thread failed. Error: %s", this->name.string(), strerror(-err));
487 }
Mike Ma4686c242020-06-05 00:51:22 -0700488 write_fd.reset();
Mike Ma5510f7c2020-02-19 02:56:04 -0800489 });
490
491 // Collect dump content
Mike Ma87003ad2020-03-19 12:31:29 -0700492 FdBuffer buffer;
Mike Ma5510f7c2020-02-19 02:56:04 -0800493 ProtoOutputStream proto;
Mike Ma87003ad2020-03-19 12:31:29 -0700494 proto.write(TextDumpProto::COMMAND, std::string(name.string()));
495 proto.write(TextDumpProto::DUMP_DURATION_NS, int64_t(Nanotime() - start));
496 buffer.write(proto.data());
Mike Ma5510f7c2020-02-19 02:56:04 -0800497
Mike Ma87003ad2020-03-19 12:31:29 -0700498 sp<EncodedBuffer> internalBuffer = buffer.data();
499 internalBuffer->writeHeader((uint32_t)TextDumpProto::CONTENT, WIRE_TYPE_LENGTH_DELIMITED);
500 size_t editPos = internalBuffer->wp()->pos();
501 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size
502 size_t dataBeginPos = internalBuffer->wp()->pos();
503
504 status_t readStatus = buffer.read(dumpPipe.readFd(), this->timeoutMs);
505 dumpPipe.readFd().reset();
506 writer->setSectionStats(buffer);
507 if (readStatus != OK || buffer.timedOut()) {
508 ALOGW("[%s] failed to read from dumpsys: %s, timedout: %s", this->name.string(),
509 strerror(-readStatus), buffer.timedOut() ? "true" : "false");
510 worker.detach();
511 return readStatus;
Mike Ma5510f7c2020-02-19 02:56:04 -0800512 }
Mike Ma87003ad2020-03-19 12:31:29 -0700513 worker.join(); // wait for worker to finish
514
515 // Revisit the actual size from dumpsys and edit the internal buffer accordingly.
516 size_t dumpSize = buffer.size() - dataBeginPos;
517 internalBuffer->wp()->rewind()->move(editPos);
518 internalBuffer->writeRawVarint32(dumpSize);
519 internalBuffer->copy(dataBeginPos, dumpSize);
520
521 return writer->writeSection(buffer);
Mike Ma5510f7c2020-02-19 02:56:04 -0800522}
523
524// ================================================================================
Yi Jin3c034c92017-12-22 17:36:47 -0800525// initialization only once in Section.cpp.
526map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
527
zhouwenjiec3bf8042019-10-30 14:31:54 -0700528LogSection::LogSection(int id, const char* logID, ...) : WorkerThreadSection(id), mLogMode(logModeBase) {
529 name = "logcat -b ";
530 name += logID;
531
532 va_list args;
533 va_start(args, logID);
534 mLogID = android_name_to_log_id(logID);
535 while(true) {
536 const char* arg = va_arg(args, const char*);
537 if (arg == NULL) {
538 break;
539 }
540 if (!strcmp(arg, "-L")) {
541 // Read from last logcat buffer
542 mLogMode = mLogMode | ANDROID_LOG_PSTORE;
543 }
544 name += " ";
545 name += arg;
546 }
Greg Kaiserfa89cde2019-11-04 06:04:42 -0800547 va_end(args);
zhouwenjiec3bf8042019-10-30 14:31:54 -0700548
549 switch (mLogID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800550 case LOG_ID_EVENTS:
551 case LOG_ID_STATS:
552 case LOG_ID_SECURITY:
553 mBinary = true;
554 break;
555 default:
556 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800557 }
558}
559
Yi Jinb592e3b2018-02-01 15:17:04 -0800560LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800561
Yi Jinb592e3b2018-02-01 15:17:04 -0800562static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800563 while (len > 0) {
564 char c = buf[len - 1];
565 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
566 len--;
567 } else {
568 break;
569 }
570 }
571 return len;
572}
573
574static inline int32_t get4LE(uint8_t const* src) {
575 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
576}
577
Mike Ma643de922019-12-17 10:56:17 -0800578status_t LogSection::BlockingCall(unique_fd& pipeWriteFd) const {
Mike Ma892ccd92020-03-20 16:30:37 -0700579 // heap profile shows that liblog malloc & free significant amount of memory in this process.
580 // Hence forking a new process to prevent memory fragmentation.
581 pid_t pid = fork();
582 if (pid < 0) {
583 ALOGW("[%s] failed to fork", this->name.string());
584 return errno;
585 }
586 if (pid > 0) {
587 return wait_child(pid, this->timeoutMs);
588 }
Yi Jin3c034c92017-12-22 17:36:47 -0800589 // Open log buffer and getting logs since last retrieved time if any.
590 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800591 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
zhouwenjiec3bf8042019-10-30 14:31:54 -0700592 ? android_logger_list_alloc(mLogMode, 0, 0)
593 : android_logger_list_alloc_time(mLogMode, gLastLogsRetrieved[mLogID], 0),
Yi Jinb592e3b2018-02-01 15:17:04 -0800594 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800595
596 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin3be0b432018-04-20 17:08:11 -0700597 ALOGE("[%s] Can't get logger.", this->name.string());
Mike Ma892ccd92020-03-20 16:30:37 -0700598 _exit(EXIT_FAILURE);
Yi Jin3c034c92017-12-22 17:36:47 -0800599 }
600
601 log_msg msg;
602 log_time lastTimestamp(0);
603
604 ProtoOutputStream proto;
Mike Ma892ccd92020-03-20 16:30:37 -0700605 status_t err = OK;
Yi Jinb592e3b2018-02-01 15:17:04 -0800606 while (true) { // keeps reading until logd buffer is fully read.
Mike Ma892ccd92020-03-20 16:30:37 -0700607 status_t status = android_logger_list_read(loggers.get(), &msg);
608 // status = 0 - no content, unexpected connection drop or EOF.
609 // status = +ive number - size of retrieved data from logger
610 // status = -ive number, OS supplied error _except_ for -EAGAIN
611 // status = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end.
612 if (status <= 0) {
613 if (status != -EAGAIN) {
Yi Jin3be0b432018-04-20 17:08:11 -0700614 ALOGW("[%s] fails to read a log_msg.\n", this->name.string());
Mike Ma892ccd92020-03-20 16:30:37 -0700615 err = -status;
Yi Jin3c034c92017-12-22 17:36:47 -0800616 }
617 break;
618 }
619 if (mBinary) {
620 // remove the first uint32 which is tag's index in event log tags
621 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800622 msg.len() - sizeof(uint32_t));
Yi Jin3c034c92017-12-22 17:36:47 -0800623 android_log_list_element elem;
624
Tom Cherryd0269892019-10-15 17:10:15 -0700625 lastTimestamp.tv_sec = msg.entry.sec;
626 lastTimestamp.tv_nsec = msg.entry.nsec;
Yi Jin3c034c92017-12-22 17:36:47 -0800627
628 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800629 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Tom Cherryd0269892019-10-15 17:10:15 -0700630 proto.write(BinaryLogEntry::SEC, (int32_t)msg.entry.sec);
631 proto.write(BinaryLogEntry::NANOSEC, (int32_t)msg.entry.nsec);
632 proto.write(BinaryLogEntry::UID, (int)msg.entry.uid);
633 proto.write(BinaryLogEntry::PID, msg.entry.pid);
634 proto.write(BinaryLogEntry::TID, (int32_t)msg.entry.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800635 proto.write(BinaryLogEntry::TAG_INDEX,
636 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800637 do {
638 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800639 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800640 switch (elem.type) {
641 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800642 proto.write(BinaryLogEntry::Elem::TYPE,
643 BinaryLogEntry::Elem::EVENT_TYPE_INT);
644 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800645 break;
646 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800647 proto.write(BinaryLogEntry::Elem::TYPE,
648 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
649 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800650 break;
651 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800652 proto.write(BinaryLogEntry::Elem::TYPE,
653 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800654 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
655 break;
656 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800657 proto.write(BinaryLogEntry::Elem::TYPE,
658 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800659 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
660 break;
661 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800662 proto.write(BinaryLogEntry::Elem::TYPE,
663 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800664 break;
665 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800666 proto.write(BinaryLogEntry::Elem::TYPE,
667 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800668 break;
669 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800670 proto.write(BinaryLogEntry::Elem::TYPE,
671 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800672 break;
673 }
674 proto.end(elemToken);
675 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
676 proto.end(token);
677 if (context) {
678 android_log_destroy(&context);
679 }
680 } else {
681 AndroidLogEntry entry;
Mike Ma892ccd92020-03-20 16:30:37 -0700682 status = android_log_processLogBuffer(&msg.entry, &entry);
683 if (status != OK) {
Yi Jin3be0b432018-04-20 17:08:11 -0700684 ALOGW("[%s] fails to process to an entry.\n", this->name.string());
Mike Ma892ccd92020-03-20 16:30:37 -0700685 err = status;
Yi Jin3c034c92017-12-22 17:36:47 -0800686 break;
687 }
688 lastTimestamp.tv_sec = entry.tv_sec;
689 lastTimestamp.tv_nsec = entry.tv_nsec;
690
691 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800692 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800693 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
694 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
695 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
696 proto.write(TextLogEntry::UID, entry.uid);
697 proto.write(TextLogEntry::PID, entry.pid);
698 proto.write(TextLogEntry::TID, entry.tid);
699 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800700 proto.write(TextLogEntry::LOG, entry.message,
701 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800702 proto.end(token);
703 }
Mike Ma892ccd92020-03-20 16:30:37 -0700704 if (!proto.flush(pipeWriteFd.get())) {
705 if (errno == EPIPE) {
706 ALOGW("[%s] wrote to a broken pipe\n", this->name.string());
707 }
708 err = errno;
709 break;
710 }
711 proto.clear();
Yi Jin3c034c92017-12-22 17:36:47 -0800712 }
713 gLastLogsRetrieved[mLogID] = lastTimestamp;
Mike Ma892ccd92020-03-20 16:30:37 -0700714 _exit(err);
Yi Jin3c034c92017-12-22 17:36:47 -0800715}
Kweku Adamseadd1232018-02-05 16:45:13 -0800716
717// ================================================================================
718
Mike Ma892ccd92020-03-20 16:30:37 -0700719const int LINK_NAME_LEN = 64;
720const int EXE_NAME_LEN = 1024;
721
Kweku Adamseadd1232018-02-05 16:45:13 -0800722TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
723 : WorkerThreadSection(id, timeoutMs), mType(type) {
Yi Jin3be0b432018-04-20 17:08:11 -0700724 name = "tombstone ";
Kweku Adamseadd1232018-02-05 16:45:13 -0800725 name += type;
726}
727
728TombstoneSection::~TombstoneSection() {}
729
Mike Ma643de922019-12-17 10:56:17 -0800730status_t TombstoneSection::BlockingCall(unique_fd& pipeWriteFd) const {
Kweku Adamseadd1232018-02-05 16:45:13 -0800731 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
732 if (proc.get() == nullptr) {
733 ALOGE("opendir /proc failed: %s\n", strerror(errno));
734 return -errno;
735 }
736
737 const std::set<int> hal_pids = get_interesting_hal_pids();
738
Mike Ma892ccd92020-03-20 16:30:37 -0700739 auto pooledBuffer = get_buffer_from_pool();
740 ProtoOutputStream proto(pooledBuffer);
741 // dumpBufferSize should be a multiple of page size (4 KB) to reduce memory fragmentation
742 size_t dumpBufferSize = 64 * 1024; // 64 KB is enough for most tombstone dump
743 char* dumpBuffer = (char*)mmap(NULL, dumpBufferSize, PROT_READ | PROT_WRITE,
744 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
Kweku Adamseadd1232018-02-05 16:45:13 -0800745 struct dirent* d;
Mike Ma892ccd92020-03-20 16:30:37 -0700746 char link_name[LINK_NAME_LEN];
747 char exe_name[EXE_NAME_LEN];
Kweku Adamseadd1232018-02-05 16:45:13 -0800748 status_t err = NO_ERROR;
749 while ((d = readdir(proc.get()))) {
750 int pid = atoi(d->d_name);
751 if (pid <= 0) {
752 continue;
753 }
Mike Ma892ccd92020-03-20 16:30:37 -0700754 snprintf(link_name, LINK_NAME_LEN, "/proc/%d/exe", pid);
755 struct stat fileStat;
756 if (stat(link_name, &fileStat) != OK) {
Kweku Adamseadd1232018-02-05 16:45:13 -0800757 continue;
758 }
Mike Mab98050f2020-03-30 13:37:31 -0700759 ssize_t exe_name_len = readlink(link_name, exe_name, EXE_NAME_LEN);
Mike Ma892ccd92020-03-20 16:30:37 -0700760 if (exe_name_len < 0 || exe_name_len >= EXE_NAME_LEN) {
761 ALOGE("[%s] Can't read '%s': %s", name.string(), link_name, strerror(errno));
762 continue;
763 }
764 // readlink(2) does not put a null terminator at the end
765 exe_name[exe_name_len] = '\0';
Kweku Adamseadd1232018-02-05 16:45:13 -0800766
767 bool is_java_process;
Mike Ma892ccd92020-03-20 16:30:37 -0700768 if (strncmp(exe_name, "/system/bin/app_process32", LINK_NAME_LEN) == 0 ||
769 strncmp(exe_name, "/system/bin/app_process64", LINK_NAME_LEN) == 0) {
Kweku Adamseadd1232018-02-05 16:45:13 -0800770 if (mType != "java") continue;
771 // Don't bother dumping backtraces for the zygote.
772 if (IsZygote(pid)) {
773 VLOG("Skipping Zygote");
774 continue;
775 }
776
777 is_java_process = true;
Mike Ma892ccd92020-03-20 16:30:37 -0700778 } else if (should_dump_native_traces(exe_name)) {
Kweku Adamseadd1232018-02-05 16:45:13 -0800779 if (mType != "native") continue;
780 is_java_process = false;
781 } else if (hal_pids.find(pid) != hal_pids.end()) {
782 if (mType != "hal") continue;
783 is_java_process = false;
784 } else {
785 // Probably a native process we don't care about, continue.
786 VLOG("Skipping %d", pid);
787 continue;
788 }
789
790 Fpipe dumpPipe;
791 if (!dumpPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700792 ALOGW("[%s] failed to setup dump pipe", this->name.string());
Kweku Adamseadd1232018-02-05 16:45:13 -0800793 err = -errno;
794 break;
795 }
796
797 const uint64_t start = Nanotime();
798 pid_t child = fork();
799 if (child < 0) {
800 ALOGE("Failed to fork child process");
801 break;
802 } else if (child == 0) {
803 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700804 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800805 const int ret = dump_backtrace_to_file_timeout(
806 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700807 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800808 if (ret == -1) {
809 if (errno == 0) {
810 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
811 } else {
812 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
813 }
814 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700815 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800816 _exit(EXIT_SUCCESS);
817 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700818 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800819 // Parent process.
820 // Read from the pipe concurrently to avoid blocking the child.
821 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700822 err = buffer.readFully(dumpPipe.readFd().get());
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700823 // Wait on the child to avoid it becoming a zombie process.
824 status_t cStatus = wait_child(child);
Kweku Adamseadd1232018-02-05 16:45:13 -0800825 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700826 ALOGW("[%s] failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700827 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800828 break;
829 }
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700830 if (cStatus != NO_ERROR) {
Kweku Adams5b763c12018-09-13 15:44:58 -0700831 ALOGE("[%s] child had an issue: %s\n", this->name.string(), strerror(-cStatus));
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700832 }
Kweku Adamseadd1232018-02-05 16:45:13 -0800833
Mike Ma892ccd92020-03-20 16:30:37 -0700834 // Resize dump buffer
835 if (dumpBufferSize < buffer.size()) {
836 munmap(dumpBuffer, dumpBufferSize);
837 while(dumpBufferSize < buffer.size()) dumpBufferSize = dumpBufferSize << 1;
838 dumpBuffer = (char*)mmap(NULL, dumpBufferSize, PROT_READ | PROT_WRITE,
839 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
840 }
Joe Onorato99598ee2019-02-11 15:55:13 +0000841 sp<ProtoReader> reader = buffer.data()->read();
Kweku Adamseadd1232018-02-05 16:45:13 -0800842 int i = 0;
Joe Onorato99598ee2019-02-11 15:55:13 +0000843 while (reader->hasNext()) {
Mike Ma892ccd92020-03-20 16:30:37 -0700844 dumpBuffer[i] = reader->next();
Kweku Adamseadd1232018-02-05 16:45:13 -0800845 i++;
846 }
Yi Jin6cacbcb2018-03-30 14:04:52 -0700847 uint64_t token = proto.start(android::os::BackTraceProto::TRACES);
Kweku Adamseadd1232018-02-05 16:45:13 -0800848 proto.write(android::os::BackTraceProto::Stack::PID, pid);
Mike Ma892ccd92020-03-20 16:30:37 -0700849 proto.write(android::os::BackTraceProto::Stack::DUMP, dumpBuffer, i);
Kweku Adamseadd1232018-02-05 16:45:13 -0800850 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
851 static_cast<long long>(Nanotime() - start));
852 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700853 dumpPipe.readFd().reset();
Mike Ma892ccd92020-03-20 16:30:37 -0700854 if (!proto.flush(pipeWriteFd.get())) {
855 if (errno == EPIPE) {
856 ALOGE("[%s] wrote to a broken pipe\n", this->name.string());
857 }
858 err = errno;
859 break;
Kweku Adams5b763c12018-09-13 15:44:58 -0700860 }
Mike Ma892ccd92020-03-20 16:30:37 -0700861 proto.clear();
Kweku Adams5b763c12018-09-13 15:44:58 -0700862 }
Mike Ma892ccd92020-03-20 16:30:37 -0700863 munmap(dumpBuffer, dumpBufferSize);
864 return_buffer_to_pool(pooledBuffer);
Kweku Adamseadd1232018-02-05 16:45:13 -0800865 return err;
866}
Yi Jin6cacbcb2018-03-30 14:04:52 -0700867
Mike Ma643de922019-12-17 10:56:17 -0800868// ================================================================================
869BringYourOwnSection::BringYourOwnSection(int id, const char* customName, const uid_t callingUid,
870 const sp<IIncidentDumpCallback>& callback)
871 : WorkerThreadSection(id, REMOTE_CALL_TIMEOUT_MS), uid(callingUid), mCallback(callback) {
872 name = "registered ";
873 name += customName;
874}
875
876BringYourOwnSection::~BringYourOwnSection() {}
877
878status_t BringYourOwnSection::BlockingCall(unique_fd& pipeWriteFd) const {
879 android::os::ParcelFileDescriptor pfd(std::move(pipeWriteFd));
Wenjie Zhou751c7c92020-05-14 12:49:19 -0700880 if(mCallback != nullptr) {
881 mCallback->onDumpSection(pfd);
882 }
Mike Ma643de922019-12-17 10:56:17 -0800883 return NO_ERROR;
884}
885
Yi Jin6cacbcb2018-03-30 14:04:52 -0700886} // namespace incidentd
887} // namespace os
Yi Jin98ce8102018-04-12 11:15:39 -0700888} // namespace android