blob: 66e747c0a3cbedfc49d4a1103f518c3e127be6c9 [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
Yi Jin3c034c92017-12-22 17:36:47 -080024#include <mutex>
Kweku Adamseadd1232018-02-05 16:45:13 -080025#include <set>
Joe Onorato1754d742016-11-21 17:51:35 -080026
Yi Jinb592e3b2018-02-01 15:17:04 -080027#include <android-base/file.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080028#include <android-base/stringprintf.h>
Yi Jinc23fad22017-09-15 17:24:59 -070029#include <android/util/protobuf.h>
Joe Onorato1754d742016-11-21 17:51:35 -080030#include <binder/IServiceManager.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080031#include <debuggerd/client.h>
32#include <dumputils/dump_utils.h>
Yi Jin3c034c92017-12-22 17:36:47 -080033#include <log/log_event_list.h>
Yi Jin3c034c92017-12-22 17:36:47 -080034#include <log/log_read.h>
Yi Jinb592e3b2018-02-01 15:17:04 -080035#include <log/logprint.h>
Yi Jin3c034c92017-12-22 17:36:47 -080036#include <private/android_logger.h>
37
38#include "FdBuffer.h"
Yi Jin3c034c92017-12-22 17:36:47 -080039#include "Privacy.h"
40#include "PrivacyBuffer.h"
Kweku Adamseadd1232018-02-05 16:45:13 -080041#include "frameworks/base/core/proto/android/os/backtrace.proto.h"
Yi Jin1a11fa12018-02-22 16:44:10 -080042#include "frameworks/base/core/proto/android/os/data.proto.h"
Yi Jinb592e3b2018-02-01 15:17:04 -080043#include "frameworks/base/core/proto/android/util/log.proto.h"
44#include "incidentd_util.h"
Joe Onorato1754d742016-11-21 17:51:35 -080045
Yi Jinb592e3b2018-02-01 15:17:04 -080046using namespace android::base;
Yi Jinc23fad22017-09-15 17:24:59 -070047using namespace android::util;
Joe Onorato1754d742016-11-21 17:51:35 -080048using namespace std;
49
Yi Jinc23fad22017-09-15 17:24:59 -070050// special section ids
51const int FIELD_ID_INCIDENT_HEADER = 1;
Yi Jin329130b2018-02-09 16:47:47 -080052const int FIELD_ID_INCIDENT_METADATA = 2;
Yi Jinc23fad22017-09-15 17:24:59 -070053
54// incident section parameters
Yi Jin3c034c92017-12-22 17:36:47 -080055const char INCIDENT_HELPER[] = "/system/bin/incident_helper";
Yi Jinc36e91d2018-03-08 11:25:58 -080056const char* GZIP[] = {"/system/bin/gzip", NULL};
Yi Jinb44f7d42017-07-21 12:12:59 -070057
Yi Jin1a11fa12018-02-22 16:44:10 -080058static pid_t fork_execute_incident_helper(const int id, Fpipe* p2cPipe, Fpipe* c2pPipe) {
Yi Jinb592e3b2018-02-01 15:17:04 -080059 const char* ihArgs[]{INCIDENT_HELPER, "-s", String8::format("%d", id).string(), NULL};
Yi Jinc36e91d2018-03-08 11:25:58 -080060 return fork_execute_cmd(const_cast<char**>(ihArgs), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -070061}
62
Yi Jin99c248f2017-08-25 18:11:58 -070063// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -080064static status_t write_section_header(int fd, int sectionId, size_t size) {
Yi Jin99c248f2017-08-25 18:11:58 -070065 uint8_t buf[20];
Yi Jinb592e3b2018-02-01 15:17:04 -080066 uint8_t* p = write_length_delimited_tag_header(buf, sectionId, size);
67 return WriteFully(fd, buf, p - buf) ? NO_ERROR : -errno;
Yi Jin99c248f2017-08-25 18:11:58 -070068}
69
Kweku Adamseadd1232018-02-05 16:45:13 -080070// Reads data from FdBuffer and writes it to the requests file descriptor.
Yi Jinb592e3b2018-02-01 15:17:04 -080071static status_t write_report_requests(const int id, const FdBuffer& buffer,
72 ReportRequestSet* requests) {
Yi Jin0f047162017-09-05 13:44:22 -070073 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -070074 EncodedBuffer::iterator data = buffer.data();
75 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -070076 int writeable = 0;
Yi Jin86dce412018-03-07 11:36:57 -080077 IncidentMetadata::SectionStats* stats = requests->sectionStats(id);
Yi Jin329130b2018-02-09 16:47:47 -080078
79 stats->set_dump_size_bytes(data.size());
80 stats->set_dump_duration_ms(buffer.durationMs());
81 stats->set_timed_out(buffer.timedOut());
82 stats->set_is_truncated(buffer.truncated());
Yi Jin99c248f2017-08-25 18:11:58 -070083
Yi Jin0f047162017-09-05 13:44:22 -070084 // The streaming ones, group requests by spec in order to save unnecessary strip operations
85 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -080086 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -070087 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -070088 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -070089 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -070090 }
Yi Jin3ec5cc72018-01-26 13:42:43 -080091 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -070092 requestsBySpec[spec].push_back(request);
93 }
94
Yi Jin3ec5cc72018-01-26 13:42:43 -080095 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -070096 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -070097 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -080098 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -070099 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700100
Yi Jin3ec5cc72018-01-26 13:42:43 -0800101 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700102 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700103 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800104 if (err != NO_ERROR) {
105 request->err = err;
106 continue;
107 }
Yi Jinc23fad22017-09-15 17:24:59 -0700108 err = privacyBuffer.flush(request->fd);
Yi Jinb592e3b2018-02-01 15:17:04 -0800109 if (err != NO_ERROR) {
110 request->err = err;
111 continue;
112 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700113 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800114 VLOG("Section %d flushed %zu bytes to fd %d with spec %d", id, privacyBuffer.size(),
115 request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700116 }
Yi Jinc23fad22017-09-15 17:24:59 -0700117 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700118 }
119
120 // The dropbox file
121 if (requests->mainFd() >= 0) {
Yi Jin329130b2018-02-09 16:47:47 -0800122 PrivacySpec spec = PrivacySpec::new_spec(requests->mainDest());
Yi Jin3ec5cc72018-01-26 13:42:43 -0800123 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800124 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700125 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700126
Yi Jinc23fad22017-09-15 17:24:59 -0700127 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800128 if (err != NO_ERROR) {
129 requests->setMainFd(-1);
130 goto DONE;
131 }
Yi Jinc23fad22017-09-15 17:24:59 -0700132 err = privacyBuffer.flush(requests->mainFd());
Yi Jinb592e3b2018-02-01 15:17:04 -0800133 if (err != NO_ERROR) {
134 requests->setMainFd(-1);
135 goto DONE;
136 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700137 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800138 VLOG("Section %d flushed %zu bytes to dropbox %d with spec %d", id, privacyBuffer.size(),
139 requests->mainFd(), spec.dest);
Yi Jin329130b2018-02-09 16:47:47 -0800140 stats->set_report_size_bytes(privacyBuffer.size());
Yi Jin99c248f2017-08-25 18:11:58 -0700141 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700142
143DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700144 // only returns error if there is no fd to write to.
145 return writeable > 0 ? NO_ERROR : err;
146}
147
148// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800149Section::Section(int i, const int64_t timeoutMs) : id(i), timeoutMs(timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800150
Yi Jinb592e3b2018-02-01 15:17:04 -0800151Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800152
Joe Onorato1754d742016-11-21 17:51:35 -0800153// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800154HeaderSection::HeaderSection() : Section(FIELD_ID_INCIDENT_HEADER, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700155
Yi Jinb592e3b2018-02-01 15:17:04 -0800156HeaderSection::~HeaderSection() {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700157
Yi Jinb592e3b2018-02-01 15:17:04 -0800158status_t HeaderSection::Execute(ReportRequestSet* requests) const {
159 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700160 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800161 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700162
Yi Jinb592e3b2018-02-01 15:17:04 -0800163 for (vector<vector<uint8_t>>::const_iterator buf = headers.begin(); buf != headers.end();
164 buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700165 if (buf->empty()) continue;
166
167 // So the idea is only requests with negative fd are written to dropbox file.
168 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800169 write_section_header(fd, id, buf->size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800170 WriteFully(fd, (uint8_t const*)buf->data(), buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700171 // If there was an error now, there will be an error later and we will remove
172 // it from the list then.
173 }
174 }
175 return NO_ERROR;
176}
Yi Jin329130b2018-02-09 16:47:47 -0800177// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800178MetadataSection::MetadataSection() : Section(FIELD_ID_INCIDENT_METADATA, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700179
Yi Jinb592e3b2018-02-01 15:17:04 -0800180MetadataSection::~MetadataSection() {}
Yi Jin329130b2018-02-09 16:47:47 -0800181
Yi Jinb592e3b2018-02-01 15:17:04 -0800182status_t MetadataSection::Execute(ReportRequestSet* requests) const {
Yi Jin86dce412018-03-07 11:36:57 -0800183 ProtoOutputStream proto;
184 IncidentMetadata metadata = requests->metadata();
185 proto.write(FIELD_TYPE_ENUM | IncidentMetadata::kDestFieldNumber, metadata.dest());
186 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::kRequestSizeFieldNumber,
187 metadata.request_size());
188 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::kUseDropboxFieldNumber, metadata.use_dropbox());
189 for (auto iter = requests->allSectionStats().begin(); iter != requests->allSectionStats().end();
190 iter++) {
191 IncidentMetadata::SectionStats stats = iter->second;
192 uint64_t token = proto.start(FIELD_TYPE_MESSAGE | IncidentMetadata::kSectionsFieldNumber);
193 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kIdFieldNumber, stats.id());
194 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kSuccessFieldNumber,
195 stats.success());
196 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kReportSizeBytesFieldNumber,
197 stats.report_size_bytes());
198 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kExecDurationMsFieldNumber,
199 stats.exec_duration_ms());
200 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kDumpSizeBytesFieldNumber,
201 stats.dump_size_bytes());
202 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kDumpDurationMsFieldNumber,
203 stats.dump_duration_ms());
204 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kTimedOutFieldNumber,
205 stats.timed_out());
206 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kIsTruncatedFieldNumber,
207 stats.is_truncated());
208 proto.end(token);
209 }
210
Yi Jinb592e3b2018-02-01 15:17:04 -0800211 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jin329130b2018-02-09 16:47:47 -0800212 const sp<ReportRequest> request = *it;
Yi Jin86dce412018-03-07 11:36:57 -0800213 if (request->fd < 0 || request->err != NO_ERROR) {
Yi Jin329130b2018-02-09 16:47:47 -0800214 continue;
215 }
Yi Jin86dce412018-03-07 11:36:57 -0800216 write_section_header(request->fd, id, proto.size());
217 if (!proto.flush(request->fd)) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800218 ALOGW("Failed to write metadata to fd %d", request->fd);
219 // we don't fail if we can't write to a single request's fd.
220 }
Yi Jin329130b2018-02-09 16:47:47 -0800221 }
Yi Jin86dce412018-03-07 11:36:57 -0800222 if (requests->mainFd() >= 0) {
223 write_section_header(requests->mainFd(), id, proto.size());
224 if (!proto.flush(requests->mainFd())) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800225 ALOGW("Failed to write metadata to dropbox fd %d", requests->mainFd());
226 return -1;
227 }
Yi Jin329130b2018-02-09 16:47:47 -0800228 }
229 return NO_ERROR;
230}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700231// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -0800232static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
233
Yi Jinb44f7d42017-07-21 12:12:59 -0700234FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Yi Jinb592e3b2018-02-01 15:17:04 -0800235 : Section(id, timeoutMs), mFilename(filename) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700236 name = filename;
Yi Jin1a11fa12018-02-22 16:44:10 -0800237 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -0700238}
239
240FileSection::~FileSection() {}
241
Yi Jinb592e3b2018-02-01 15:17:04 -0800242status_t FileSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700243 // read from mFilename first, make sure the file is available
244 // add O_CLOEXEC to make sure it is closed when exec incident helper
Yi Jin6355d2f2018-03-14 15:18:02 -0700245 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
246 if (fd.get() == -1) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800247 ALOGW("FileSection '%s' failed to open file", this->name.string());
248 return -errno;
Yi Jin0a3406f2017-06-22 19:23:11 -0700249 }
250
Yi Jinb44f7d42017-07-21 12:12:59 -0700251 FdBuffer buffer;
252 Fpipe p2cPipe;
253 Fpipe c2pPipe;
254 // initiate pipes to pass data to/from incident_helper
255 if (!p2cPipe.init() || !c2pPipe.init()) {
256 ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700257 return -errno;
258 }
259
Yi Jin1a11fa12018-02-22 16:44:10 -0800260 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700261 if (pid == -1) {
262 ALOGW("FileSection '%s' failed to fork", this->name.string());
263 return -errno;
264 }
265
266 // parent process
Yi Jine3dab2d2018-03-22 16:56:39 -0700267 status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
268 std::move(c2pPipe.readFd()),
269 this->timeoutMs, mIsSysfs);
Yi Jin1a11fa12018-02-22 16:44:10 -0800270
Yi Jinb44f7d42017-07-21 12:12:59 -0700271 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800272 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800273 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800274 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700275 return readStatus;
276 }
277
Yi Jinedfd5bb2017-09-06 17:09:11 -0700278 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700279 if (ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800280 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(),
281 strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700282 return ihStatus;
283 }
284
Yi Jinb592e3b2018-02-01 15:17:04 -0800285 VLOG("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
286 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700287 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700288 if (err != NO_ERROR) {
289 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
290 return err;
291 }
292
293 return NO_ERROR;
294}
Yi Jin1a11fa12018-02-22 16:44:10 -0800295// ================================================================================
296GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800297 va_list args;
298 va_start(args, filename);
299 mFilenames = varargs(filename, args);
300 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800301 name = "gzip";
302 for (int i = 0; mFilenames[i] != NULL; i++) {
303 name += " ";
304 name += mFilenames[i];
305 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800306}
Yi Jin0a3406f2017-06-22 19:23:11 -0700307
Yi Jin1a11fa12018-02-22 16:44:10 -0800308GZipSection::~GZipSection() {}
309
310status_t GZipSection::Execute(ReportRequestSet* requests) const {
311 // Reads the files in order, use the first available one.
312 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700313 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800314 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700315 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
316 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800317 break;
318 }
319 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
320 index++; // look at the next file.
321 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700322 VLOG("GZipSection is using file %s, fd=%d", mFilenames[index], fd.get());
323 if (fd.get() == -1) return -1;
Yi Jin1a11fa12018-02-22 16:44:10 -0800324
325 FdBuffer buffer;
326 Fpipe p2cPipe;
327 Fpipe c2pPipe;
328 // initiate pipes to pass data to/from gzip
329 if (!p2cPipe.init() || !c2pPipe.init()) {
330 ALOGW("GZipSection '%s' failed to setup pipes", this->name.string());
331 return -errno;
332 }
333
Yi Jinc36e91d2018-03-08 11:25:58 -0800334 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800335 if (pid == -1) {
336 ALOGW("GZipSection '%s' failed to fork", this->name.string());
337 return -errno;
338 }
339 // parent process
340
341 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
342 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
343 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
344 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700345 size_t fileLen = strlen(mFilenames[index]);
346 internalBuffer->writeRawVarint32(fileLen);
347 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800348 internalBuffer->writeRawByte(mFilenames[index][i]);
349 }
350 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
351 WIRE_TYPE_LENGTH_DELIMITED);
352 size_t editPos = internalBuffer->wp()->pos();
353 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
354 size_t dataBeginAt = internalBuffer->wp()->pos();
355 VLOG("GZipSection '%s' editPos=%zd, dataBeginAt=%zd", this->name.string(), editPos,
356 dataBeginAt);
357
Yi Jine3dab2d2018-03-22 16:56:39 -0700358 status_t readStatus = buffer.readProcessedDataInStream(
359 fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
360 isSysfs(mFilenames[index]));
Yi Jin1a11fa12018-02-22 16:44:10 -0800361
362 if (readStatus != NO_ERROR || buffer.timedOut()) {
363 ALOGW("GZipSection '%s' failed to read data from gzip: %s, timedout: %s",
364 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
365 kill_child(pid);
366 return readStatus;
367 }
368
369 status_t gzipStatus = wait_child(pid);
370 if (gzipStatus != NO_ERROR) {
371 ALOGW("GZipSection '%s' abnormal child process: %s", this->name.string(),
372 strerror(-gzipStatus));
373 return gzipStatus;
374 }
375 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
376 size_t dataSize = buffer.size() - dataBeginAt;
377 internalBuffer->wp()->rewind()->move(editPos);
378 internalBuffer->writeRawVarint32(dataSize);
379 internalBuffer->copy(dataBeginAt, dataSize);
380 VLOG("GZipSection '%s' wrote %zd bytes in %d ms, dataSize=%zd", this->name.string(),
381 buffer.size(), (int)buffer.durationMs(), dataSize);
382 status_t err = write_report_requests(this->id, buffer, requests);
383 if (err != NO_ERROR) {
384 ALOGW("GZipSection '%s' failed writing: %s", this->name.string(), strerror(-err));
385 return err;
386 }
387
388 return NO_ERROR;
389}
Kweku Adamseadd1232018-02-05 16:45:13 -0800390
Yi Jin0a3406f2017-06-22 19:23:11 -0700391// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800392struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800393 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700394 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800395
396 // Lock protects these fields
397 mutex lock;
398 bool workerDone;
399 status_t workerError;
400
401 WorkerThreadData(const WorkerThreadSection* section);
402 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800403};
404
405WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700406 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800407
Yi Jinb592e3b2018-02-01 15:17:04 -0800408WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800409
410// ================================================================================
Kweku Adamseadd1232018-02-05 16:45:13 -0800411WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
412 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800413
Yi Jinb592e3b2018-02-01 15:17:04 -0800414WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800415
Yi Jinb592e3b2018-02-01 15:17:04 -0800416static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800417 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700418 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800419
420 {
421 unique_lock<mutex> lock(data->lock);
422 data->workerDone = true;
423 data->workerError = err;
424 }
425
Yi Jin6355d2f2018-03-14 15:18:02 -0700426 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800427 data->decStrong(data->section);
428 // data might be gone now. don't use it after this point in this thread.
429 return NULL;
430}
431
Yi Jinb592e3b2018-02-01 15:17:04 -0800432status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800433 status_t err = NO_ERROR;
434 pthread_t thread;
435 pthread_attr_t attr;
436 bool timedOut = false;
437 FdBuffer buffer;
438
439 // Data shared between this thread and the worker thread.
440 sp<WorkerThreadData> data = new WorkerThreadData(this);
441
442 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700443 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800444 return -errno;
445 }
446
447 // The worker thread needs a reference and we can't let the count go to zero
448 // if that thread is slow to start.
449 data->incStrong(this);
450
451 // Create the thread
452 err = pthread_attr_init(&attr);
453 if (err != 0) {
454 return -err;
455 }
456 // TODO: Do we need to tweak thread priority?
457 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
458 if (err != 0) {
459 pthread_attr_destroy(&attr);
460 return -err;
461 }
462 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
463 if (err != 0) {
464 pthread_attr_destroy(&attr);
465 return -err;
466 }
467 pthread_attr_destroy(&attr);
468
469 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jine3dab2d2018-03-22 16:56:39 -0700470 err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800471 if (err != NO_ERROR) {
472 // TODO: Log this error into the incident report.
473 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800474 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800475 }
476
477 // Done with the read fd. The worker thread closes the write one so
478 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700479 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800480
481 // If the worker side is finished, then return its error (which may overwrite
482 // our possible error -- but it's more interesting anyway). If not, then we timed out.
483 {
484 unique_lock<mutex> lock(data->lock);
485 if (!data->workerDone) {
486 // We timed out
487 timedOut = true;
488 } else {
489 if (data->workerError != NO_ERROR) {
490 err = data->workerError;
491 // TODO: Log this error into the incident report.
492 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800493 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800494 }
495 }
496 }
497
498 if (timedOut || buffer.timedOut()) {
499 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
500 return NO_ERROR;
501 }
502
503 if (buffer.truncated()) {
504 // TODO: Log this into the incident report.
505 }
506
507 // TODO: There was an error with the command or buffering. Report that. For now
508 // just exit with a log messasge.
509 if (err != NO_ERROR) {
510 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800511 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800512 return NO_ERROR;
513 }
514
515 // Write the data that was collected
Yi Jinb592e3b2018-02-01 15:17:04 -0800516 VLOG("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
517 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700518 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800519 if (err != NO_ERROR) {
520 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
521 return err;
522 }
523
524 return NO_ERROR;
525}
526
527// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700528CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800529 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800530 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700531 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800532 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800533 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800534 name = "cmd";
535 for (int i = 0; mCommand[i] != NULL; i++) {
536 name += " ";
537 name += mCommand[i];
538 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700539}
Joe Onorato1754d742016-11-21 17:51:35 -0800540
Yi Jinb592e3b2018-02-01 15:17:04 -0800541CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700542 va_list args;
543 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800544 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800545 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800546 name = "cmd";
547 for (int i = 0; mCommand[i] != NULL; i++) {
548 name += " ";
549 name += mCommand[i];
550 }
Joe Onorato1754d742016-11-21 17:51:35 -0800551}
552
Yi Jinb592e3b2018-02-01 15:17:04 -0800553CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800554
Yi Jinb592e3b2018-02-01 15:17:04 -0800555status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700556 FdBuffer buffer;
557 Fpipe cmdPipe;
558 Fpipe ihPipe;
559
560 if (!cmdPipe.init() || !ihPipe.init()) {
561 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
562 return -errno;
563 }
564
Yi Jinc36e91d2018-03-08 11:25:58 -0800565 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700566 if (cmdPid == -1) {
567 ALOGW("CommandSection '%s' failed to fork", this->name.string());
568 return -errno;
569 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800570 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700571 if (ihPid == -1) {
572 ALOGW("CommandSection '%s' failed to fork", this->name.string());
573 return -errno;
574 }
575
Yi Jin6355d2f2018-03-14 15:18:02 -0700576 cmdPipe.writeFd().reset();
Yi Jine3dab2d2018-03-22 16:56:39 -0700577 status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
Yi Jinb44f7d42017-07-21 12:12:59 -0700578 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800579 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800580 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800581 kill_child(cmdPid);
582 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700583 return readStatus;
584 }
585
Kweku Adamseadd1232018-02-05 16:45:13 -0800586 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800587 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700588 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800589 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700590 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800591 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident "
592 "helper: %s",
593 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700594 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
595 }
596
Yi Jinb592e3b2018-02-01 15:17:04 -0800597 VLOG("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
598 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700599 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700600 if (err != NO_ERROR) {
601 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
602 return err;
603 }
Joe Onorato1754d742016-11-21 17:51:35 -0800604 return NO_ERROR;
605}
606
607// ================================================================================
608DumpsysSection::DumpsysSection(int id, const char* service, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800609 : WorkerThreadSection(id), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800610 name = "dumpsys ";
611 name += service;
612
613 va_list args;
614 va_start(args, service);
615 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700616 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800617 if (arg == NULL) {
618 break;
619 }
620 mArgs.add(String16(arg));
621 name += " ";
622 name += arg;
623 }
624 va_end(args);
625}
626
Yi Jinb592e3b2018-02-01 15:17:04 -0800627DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800628
Yi Jinb592e3b2018-02-01 15:17:04 -0800629status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800630 // checkService won't wait for the service to show up like getService will.
631 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700632
Joe Onorato1754d742016-11-21 17:51:35 -0800633 if (service == NULL) {
634 // Returning an error interrupts the entire incident report, so just
635 // log the failure.
636 // TODO: have a meta record inside the report that would log this
637 // failure inside the report, because the fact that we can't find
638 // the service is good data in and of itself. This is running in
639 // another thread so lock that carefully...
640 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
641 return NO_ERROR;
642 }
643
644 service->dump(pipeWriteFd, mArgs);
645
646 return NO_ERROR;
647}
Yi Jin3c034c92017-12-22 17:36:47 -0800648
649// ================================================================================
650// initialization only once in Section.cpp.
651map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
652
Yi Jinb592e3b2018-02-01 15:17:04 -0800653LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3c034c92017-12-22 17:36:47 -0800654 name += "logcat ";
655 name += android_log_id_to_name(logID);
656 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800657 case LOG_ID_EVENTS:
658 case LOG_ID_STATS:
659 case LOG_ID_SECURITY:
660 mBinary = true;
661 break;
662 default:
663 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800664 }
665}
666
Yi Jinb592e3b2018-02-01 15:17:04 -0800667LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800668
Yi Jinb592e3b2018-02-01 15:17:04 -0800669static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800670 while (len > 0) {
671 char c = buf[len - 1];
672 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
673 len--;
674 } else {
675 break;
676 }
677 }
678 return len;
679}
680
681static inline int32_t get4LE(uint8_t const* src) {
682 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
683}
684
Yi Jinb592e3b2018-02-01 15:17:04 -0800685status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800686 // Open log buffer and getting logs since last retrieved time if any.
687 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800688 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
689 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
690 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
691 gLastLogsRetrieved[mLogID], 0),
692 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800693
694 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700695 ALOGE("LogSection %s: Can't get logger.", this->name.string());
696 return -1;
Yi Jin3c034c92017-12-22 17:36:47 -0800697 }
698
699 log_msg msg;
700 log_time lastTimestamp(0);
701
702 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800703 while (true) { // keeps reading until logd buffer is fully read.
Yi Jin83fb1d52018-03-16 12:03:53 -0700704 status_t err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800705 // err = 0 - no content, unexpected connection drop or EOF.
706 // err = +ive number - size of retrieved data from logger
707 // err = -ive number, OS supplied error _except_ for -EAGAIN
708 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
709 if (err <= 0) {
710 if (err != -EAGAIN) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700711 ALOGW("LogSection %s: fails to read a log_msg.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800712 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700713 // dump previous logs and don't consider this error a failure.
Yi Jin3c034c92017-12-22 17:36:47 -0800714 break;
715 }
716 if (mBinary) {
717 // remove the first uint32 which is tag's index in event log tags
718 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800719 msg.len() - sizeof(uint32_t));
720 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800721 android_log_list_element elem;
722
723 lastTimestamp.tv_sec = msg.entry_v1.sec;
724 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
725
726 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800727 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800728 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
729 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800730 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800731 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
732 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800733 proto.write(BinaryLogEntry::TAG_INDEX,
734 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800735 do {
736 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800737 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800738 switch (elem.type) {
739 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800740 proto.write(BinaryLogEntry::Elem::TYPE,
741 BinaryLogEntry::Elem::EVENT_TYPE_INT);
742 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800743 break;
744 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800745 proto.write(BinaryLogEntry::Elem::TYPE,
746 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
747 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800748 break;
749 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800750 proto.write(BinaryLogEntry::Elem::TYPE,
751 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800752 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
753 break;
754 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800755 proto.write(BinaryLogEntry::Elem::TYPE,
756 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800757 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
758 break;
759 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800760 proto.write(BinaryLogEntry::Elem::TYPE,
761 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800762 break;
763 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800764 proto.write(BinaryLogEntry::Elem::TYPE,
765 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800766 break;
767 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800768 proto.write(BinaryLogEntry::Elem::TYPE,
769 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800770 break;
771 }
772 proto.end(elemToken);
773 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
774 proto.end(token);
775 if (context) {
776 android_log_destroy(&context);
777 }
778 } else {
779 AndroidLogEntry entry;
780 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
781 if (err != NO_ERROR) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700782 ALOGW("LogSection %s: fails to process to an entry.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800783 break;
784 }
785 lastTimestamp.tv_sec = entry.tv_sec;
786 lastTimestamp.tv_nsec = entry.tv_nsec;
787
788 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800789 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800790 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
791 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
792 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
793 proto.write(TextLogEntry::UID, entry.uid);
794 proto.write(TextLogEntry::PID, entry.pid);
795 proto.write(TextLogEntry::TID, entry.tid);
796 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800797 proto.write(TextLogEntry::LOG, entry.message,
798 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800799 proto.end(token);
800 }
801 }
802 gLastLogsRetrieved[mLogID] = lastTimestamp;
803 proto.flush(pipeWriteFd);
Yi Jin83fb1d52018-03-16 12:03:53 -0700804 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800805}
Kweku Adamseadd1232018-02-05 16:45:13 -0800806
807// ================================================================================
808
809TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
810 : WorkerThreadSection(id, timeoutMs), mType(type) {
811 name += "tombstone ";
812 name += type;
813}
814
815TombstoneSection::~TombstoneSection() {}
816
817status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
818 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
819 if (proc.get() == nullptr) {
820 ALOGE("opendir /proc failed: %s\n", strerror(errno));
821 return -errno;
822 }
823
824 const std::set<int> hal_pids = get_interesting_hal_pids();
825
826 ProtoOutputStream proto;
827 struct dirent* d;
828 status_t err = NO_ERROR;
829 while ((d = readdir(proc.get()))) {
830 int pid = atoi(d->d_name);
831 if (pid <= 0) {
832 continue;
833 }
834
835 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
836 std::string exe;
837 if (!android::base::Readlink(link_name, &exe)) {
838 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
839 continue;
840 }
841
842 bool is_java_process;
843 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
844 if (mType != "java") continue;
845 // Don't bother dumping backtraces for the zygote.
846 if (IsZygote(pid)) {
847 VLOG("Skipping Zygote");
848 continue;
849 }
850
851 is_java_process = true;
852 } else if (should_dump_native_traces(exe.c_str())) {
853 if (mType != "native") continue;
854 is_java_process = false;
855 } else if (hal_pids.find(pid) != hal_pids.end()) {
856 if (mType != "hal") continue;
857 is_java_process = false;
858 } else {
859 // Probably a native process we don't care about, continue.
860 VLOG("Skipping %d", pid);
861 continue;
862 }
863
864 Fpipe dumpPipe;
865 if (!dumpPipe.init()) {
866 ALOGW("TombstoneSection '%s' failed to setup dump pipe", this->name.string());
867 err = -errno;
868 break;
869 }
870
871 const uint64_t start = Nanotime();
872 pid_t child = fork();
873 if (child < 0) {
874 ALOGE("Failed to fork child process");
875 break;
876 } else if (child == 0) {
877 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700878 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800879 const int ret = dump_backtrace_to_file_timeout(
880 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700881 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800882 if (ret == -1) {
883 if (errno == 0) {
884 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
885 } else {
886 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
887 }
888 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700889 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800890 _exit(EXIT_SUCCESS);
891 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700892 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800893 // Parent process.
894 // Read from the pipe concurrently to avoid blocking the child.
895 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700896 err = buffer.readFully(dumpPipe.readFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800897 if (err != NO_ERROR) {
898 ALOGW("TombstoneSection '%s' failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700899 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800900 break;
901 }
902
903 auto dump = std::make_unique<char[]>(buffer.size());
904 auto iterator = buffer.data();
905 int i = 0;
906 while (iterator.hasNext()) {
907 dump[i] = iterator.next();
908 i++;
909 }
910 long long token = proto.start(android::os::BackTraceProto::TRACES);
911 proto.write(android::os::BackTraceProto::Stack::PID, pid);
912 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
913 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
914 static_cast<long long>(Nanotime() - start));
915 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700916 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800917 }
918
919 proto.flush(pipeWriteFd);
920 return err;
921}