blob: d964651aab3af269c9d1f0d0b1784707f35fe9b3 [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 Jin6355d2f2018-03-14 15:18:02 -0700267 status_t readStatus = buffer.readProcessedDataInStream(
268 &fd, &p2cPipe.writeFd(), &c2pPipe.readFd(), this->timeoutMs, mIsSysfs);
Yi Jin1a11fa12018-02-22 16:44:10 -0800269
Yi Jinb44f7d42017-07-21 12:12:59 -0700270 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800271 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800272 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800273 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700274 return readStatus;
275 }
276
Yi Jinedfd5bb2017-09-06 17:09:11 -0700277 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700278 if (ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800279 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(),
280 strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700281 return ihStatus;
282 }
283
Yi Jinb592e3b2018-02-01 15:17:04 -0800284 VLOG("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
285 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700286 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700287 if (err != NO_ERROR) {
288 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
289 return err;
290 }
291
292 return NO_ERROR;
293}
Yi Jin1a11fa12018-02-22 16:44:10 -0800294// ================================================================================
295GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800296 va_list args;
297 va_start(args, filename);
298 mFilenames = varargs(filename, args);
299 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800300 name = "gzip";
301 for (int i = 0; mFilenames[i] != NULL; i++) {
302 name += " ";
303 name += mFilenames[i];
304 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800305}
Yi Jin0a3406f2017-06-22 19:23:11 -0700306
Yi Jin1a11fa12018-02-22 16:44:10 -0800307GZipSection::~GZipSection() {}
308
309status_t GZipSection::Execute(ReportRequestSet* requests) const {
310 // Reads the files in order, use the first available one.
311 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700312 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800313 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700314 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
315 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800316 break;
317 }
318 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
319 index++; // look at the next file.
320 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700321 VLOG("GZipSection is using file %s, fd=%d", mFilenames[index], fd.get());
Yi Jinc858e272018-03-28 15:32:50 -0700322 if (fd.get() == -1) {
323 ALOGW("GZipSection %s can't open all the files", this->name.string());
324 return NO_ERROR; // e.g. LAST_KMSG will reach here in user build.
325 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800326 FdBuffer buffer;
327 Fpipe p2cPipe;
328 Fpipe c2pPipe;
329 // initiate pipes to pass data to/from gzip
330 if (!p2cPipe.init() || !c2pPipe.init()) {
331 ALOGW("GZipSection '%s' failed to setup pipes", this->name.string());
332 return -errno;
333 }
334
Yi Jinc36e91d2018-03-08 11:25:58 -0800335 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800336 if (pid == -1) {
337 ALOGW("GZipSection '%s' failed to fork", this->name.string());
338 return -errno;
339 }
340 // parent process
341
342 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
343 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
344 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
345 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700346 size_t fileLen = strlen(mFilenames[index]);
347 internalBuffer->writeRawVarint32(fileLen);
348 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800349 internalBuffer->writeRawByte(mFilenames[index][i]);
350 }
351 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
352 WIRE_TYPE_LENGTH_DELIMITED);
353 size_t editPos = internalBuffer->wp()->pos();
354 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
355 size_t dataBeginAt = internalBuffer->wp()->pos();
356 VLOG("GZipSection '%s' editPos=%zd, dataBeginAt=%zd", this->name.string(), editPos,
357 dataBeginAt);
358
Yi Jin6355d2f2018-03-14 15:18:02 -0700359 status_t readStatus =
360 buffer.readProcessedDataInStream(&fd, &p2cPipe.writeFd(), &c2pPipe.readFd(),
361 this->timeoutMs, isSysfs(mFilenames[index]));
Yi Jin1a11fa12018-02-22 16:44:10 -0800362
363 if (readStatus != NO_ERROR || buffer.timedOut()) {
364 ALOGW("GZipSection '%s' failed to read data from gzip: %s, timedout: %s",
365 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
366 kill_child(pid);
367 return readStatus;
368 }
369
370 status_t gzipStatus = wait_child(pid);
371 if (gzipStatus != NO_ERROR) {
372 ALOGW("GZipSection '%s' abnormal child process: %s", this->name.string(),
373 strerror(-gzipStatus));
374 return gzipStatus;
375 }
376 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
377 size_t dataSize = buffer.size() - dataBeginAt;
378 internalBuffer->wp()->rewind()->move(editPos);
379 internalBuffer->writeRawVarint32(dataSize);
380 internalBuffer->copy(dataBeginAt, dataSize);
381 VLOG("GZipSection '%s' wrote %zd bytes in %d ms, dataSize=%zd", this->name.string(),
382 buffer.size(), (int)buffer.durationMs(), dataSize);
383 status_t err = write_report_requests(this->id, buffer, requests);
384 if (err != NO_ERROR) {
385 ALOGW("GZipSection '%s' failed writing: %s", this->name.string(), strerror(-err));
386 return err;
387 }
388
389 return NO_ERROR;
390}
Kweku Adamseadd1232018-02-05 16:45:13 -0800391
Yi Jin0a3406f2017-06-22 19:23:11 -0700392// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800393struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800394 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700395 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800396
397 // Lock protects these fields
398 mutex lock;
399 bool workerDone;
400 status_t workerError;
401
402 WorkerThreadData(const WorkerThreadSection* section);
403 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800404};
405
406WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700407 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800408
Yi Jinb592e3b2018-02-01 15:17:04 -0800409WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800410
411// ================================================================================
Kweku Adamseadd1232018-02-05 16:45:13 -0800412WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
413 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800414
Yi Jinb592e3b2018-02-01 15:17:04 -0800415WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800416
Yi Jinb592e3b2018-02-01 15:17:04 -0800417static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800418 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700419 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800420
421 {
422 unique_lock<mutex> lock(data->lock);
423 data->workerDone = true;
424 data->workerError = err;
425 }
426
Yi Jin6355d2f2018-03-14 15:18:02 -0700427 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800428 data->decStrong(data->section);
429 // data might be gone now. don't use it after this point in this thread.
430 return NULL;
431}
432
Yi Jinb592e3b2018-02-01 15:17:04 -0800433status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800434 status_t err = NO_ERROR;
435 pthread_t thread;
436 pthread_attr_t attr;
437 bool timedOut = false;
438 FdBuffer buffer;
439
440 // Data shared between this thread and the worker thread.
441 sp<WorkerThreadData> data = new WorkerThreadData(this);
442
443 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700444 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800445 return -errno;
446 }
447
448 // The worker thread needs a reference and we can't let the count go to zero
449 // if that thread is slow to start.
450 data->incStrong(this);
451
452 // Create the thread
453 err = pthread_attr_init(&attr);
454 if (err != 0) {
455 return -err;
456 }
457 // TODO: Do we need to tweak thread priority?
458 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
459 if (err != 0) {
460 pthread_attr_destroy(&attr);
461 return -err;
462 }
463 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
464 if (err != 0) {
465 pthread_attr_destroy(&attr);
466 return -err;
467 }
468 pthread_attr_destroy(&attr);
469
470 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jin6355d2f2018-03-14 15:18:02 -0700471 err = buffer.read(&data->pipe.readFd(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800472 if (err != NO_ERROR) {
473 // TODO: Log this error into the incident report.
474 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800475 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800476 }
477
478 // Done with the read fd. The worker thread closes the write one so
479 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700480 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800481
482 // If the worker side is finished, then return its error (which may overwrite
483 // our possible error -- but it's more interesting anyway). If not, then we timed out.
484 {
485 unique_lock<mutex> lock(data->lock);
486 if (!data->workerDone) {
487 // We timed out
488 timedOut = true;
489 } else {
490 if (data->workerError != NO_ERROR) {
491 err = data->workerError;
492 // TODO: Log this error into the incident report.
493 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800494 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800495 }
496 }
497 }
498
499 if (timedOut || buffer.timedOut()) {
500 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
501 return NO_ERROR;
502 }
503
504 if (buffer.truncated()) {
505 // TODO: Log this into the incident report.
506 }
507
508 // TODO: There was an error with the command or buffering. Report that. For now
509 // just exit with a log messasge.
510 if (err != NO_ERROR) {
511 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800512 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800513 return NO_ERROR;
514 }
515
516 // Write the data that was collected
Yi Jinb592e3b2018-02-01 15:17:04 -0800517 VLOG("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
518 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700519 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800520 if (err != NO_ERROR) {
521 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
522 return err;
523 }
524
525 return NO_ERROR;
526}
527
528// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700529CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800530 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800531 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700532 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800533 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800534 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800535 name = "cmd";
536 for (int i = 0; mCommand[i] != NULL; i++) {
537 name += " ";
538 name += mCommand[i];
539 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700540}
Joe Onorato1754d742016-11-21 17:51:35 -0800541
Yi Jinb592e3b2018-02-01 15:17:04 -0800542CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700543 va_list args;
544 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800545 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800546 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800547 name = "cmd";
548 for (int i = 0; mCommand[i] != NULL; i++) {
549 name += " ";
550 name += mCommand[i];
551 }
Joe Onorato1754d742016-11-21 17:51:35 -0800552}
553
Yi Jinb592e3b2018-02-01 15:17:04 -0800554CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800555
Yi Jinb592e3b2018-02-01 15:17:04 -0800556status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700557 FdBuffer buffer;
558 Fpipe cmdPipe;
559 Fpipe ihPipe;
560
561 if (!cmdPipe.init() || !ihPipe.init()) {
562 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
563 return -errno;
564 }
565
Yi Jinc36e91d2018-03-08 11:25:58 -0800566 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700567 if (cmdPid == -1) {
568 ALOGW("CommandSection '%s' failed to fork", this->name.string());
569 return -errno;
570 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800571 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700572 if (ihPid == -1) {
573 ALOGW("CommandSection '%s' failed to fork", this->name.string());
574 return -errno;
575 }
576
Yi Jin6355d2f2018-03-14 15:18:02 -0700577 cmdPipe.writeFd().reset();
578 status_t readStatus = buffer.read(&ihPipe.readFd(), this->timeoutMs);
Yi Jinb44f7d42017-07-21 12:12:59 -0700579 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800580 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800581 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800582 kill_child(cmdPid);
583 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700584 return readStatus;
585 }
586
Kweku Adamseadd1232018-02-05 16:45:13 -0800587 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800588 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700589 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800590 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700591 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800592 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident "
593 "helper: %s",
594 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700595 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
596 }
597
Yi Jinb592e3b2018-02-01 15:17:04 -0800598 VLOG("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
599 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700600 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700601 if (err != NO_ERROR) {
602 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
603 return err;
604 }
Joe Onorato1754d742016-11-21 17:51:35 -0800605 return NO_ERROR;
606}
607
608// ================================================================================
609DumpsysSection::DumpsysSection(int id, const char* service, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800610 : WorkerThreadSection(id), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800611 name = "dumpsys ";
612 name += service;
613
614 va_list args;
615 va_start(args, service);
616 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700617 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800618 if (arg == NULL) {
619 break;
620 }
621 mArgs.add(String16(arg));
622 name += " ";
623 name += arg;
624 }
625 va_end(args);
626}
627
Yi Jinb592e3b2018-02-01 15:17:04 -0800628DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800629
Yi Jinb592e3b2018-02-01 15:17:04 -0800630status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800631 // checkService won't wait for the service to show up like getService will.
632 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700633
Joe Onorato1754d742016-11-21 17:51:35 -0800634 if (service == NULL) {
635 // Returning an error interrupts the entire incident report, so just
636 // log the failure.
637 // TODO: have a meta record inside the report that would log this
638 // failure inside the report, because the fact that we can't find
639 // the service is good data in and of itself. This is running in
640 // another thread so lock that carefully...
641 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
642 return NO_ERROR;
643 }
644
645 service->dump(pipeWriteFd, mArgs);
646
647 return NO_ERROR;
648}
Yi Jin3c034c92017-12-22 17:36:47 -0800649
650// ================================================================================
651// initialization only once in Section.cpp.
652map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
653
Yi Jinb592e3b2018-02-01 15:17:04 -0800654LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3c034c92017-12-22 17:36:47 -0800655 name += "logcat ";
656 name += android_log_id_to_name(logID);
657 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800658 case LOG_ID_EVENTS:
659 case LOG_ID_STATS:
660 case LOG_ID_SECURITY:
661 mBinary = true;
662 break;
663 default:
664 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800665 }
666}
667
Yi Jinb592e3b2018-02-01 15:17:04 -0800668LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800669
Yi Jinb592e3b2018-02-01 15:17:04 -0800670static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800671 while (len > 0) {
672 char c = buf[len - 1];
673 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
674 len--;
675 } else {
676 break;
677 }
678 }
679 return len;
680}
681
682static inline int32_t get4LE(uint8_t const* src) {
683 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
684}
685
Yi Jinb592e3b2018-02-01 15:17:04 -0800686status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800687 // Open log buffer and getting logs since last retrieved time if any.
688 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800689 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
690 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
691 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
692 gLastLogsRetrieved[mLogID], 0),
693 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800694
695 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700696 ALOGE("LogSection %s: Can't get logger.", this->name.string());
697 return -1;
Yi Jin3c034c92017-12-22 17:36:47 -0800698 }
699
700 log_msg msg;
701 log_time lastTimestamp(0);
702
703 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800704 while (true) { // keeps reading until logd buffer is fully read.
Yi Jin83fb1d52018-03-16 12:03:53 -0700705 status_t err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800706 // err = 0 - no content, unexpected connection drop or EOF.
707 // err = +ive number - size of retrieved data from logger
708 // err = -ive number, OS supplied error _except_ for -EAGAIN
709 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
710 if (err <= 0) {
711 if (err != -EAGAIN) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700712 ALOGW("LogSection %s: fails to read a log_msg.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800713 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700714 // dump previous logs and don't consider this error a failure.
Yi Jin3c034c92017-12-22 17:36:47 -0800715 break;
716 }
717 if (mBinary) {
718 // remove the first uint32 which is tag's index in event log tags
719 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800720 msg.len() - sizeof(uint32_t));
721 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800722 android_log_list_element elem;
723
724 lastTimestamp.tv_sec = msg.entry_v1.sec;
725 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
726
727 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800728 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800729 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
730 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800731 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800732 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
733 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800734 proto.write(BinaryLogEntry::TAG_INDEX,
735 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800736 do {
737 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800738 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800739 switch (elem.type) {
740 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800741 proto.write(BinaryLogEntry::Elem::TYPE,
742 BinaryLogEntry::Elem::EVENT_TYPE_INT);
743 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800744 break;
745 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800746 proto.write(BinaryLogEntry::Elem::TYPE,
747 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
748 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800749 break;
750 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800751 proto.write(BinaryLogEntry::Elem::TYPE,
752 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800753 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
754 break;
755 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800756 proto.write(BinaryLogEntry::Elem::TYPE,
757 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800758 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
759 break;
760 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800761 proto.write(BinaryLogEntry::Elem::TYPE,
762 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800763 break;
764 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800765 proto.write(BinaryLogEntry::Elem::TYPE,
766 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800767 break;
768 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800769 proto.write(BinaryLogEntry::Elem::TYPE,
770 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800771 break;
772 }
773 proto.end(elemToken);
774 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
775 proto.end(token);
776 if (context) {
777 android_log_destroy(&context);
778 }
779 } else {
780 AndroidLogEntry entry;
781 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
782 if (err != NO_ERROR) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700783 ALOGW("LogSection %s: fails to process to an entry.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800784 break;
785 }
786 lastTimestamp.tv_sec = entry.tv_sec;
787 lastTimestamp.tv_nsec = entry.tv_nsec;
788
789 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800790 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800791 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
792 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
793 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
794 proto.write(TextLogEntry::UID, entry.uid);
795 proto.write(TextLogEntry::PID, entry.pid);
796 proto.write(TextLogEntry::TID, entry.tid);
797 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800798 proto.write(TextLogEntry::LOG, entry.message,
799 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800800 proto.end(token);
801 }
802 }
803 gLastLogsRetrieved[mLogID] = lastTimestamp;
804 proto.flush(pipeWriteFd);
Yi Jin83fb1d52018-03-16 12:03:53 -0700805 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800806}
Kweku Adamseadd1232018-02-05 16:45:13 -0800807
808// ================================================================================
809
810TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
811 : WorkerThreadSection(id, timeoutMs), mType(type) {
812 name += "tombstone ";
813 name += type;
814}
815
816TombstoneSection::~TombstoneSection() {}
817
818status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
819 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
820 if (proc.get() == nullptr) {
821 ALOGE("opendir /proc failed: %s\n", strerror(errno));
822 return -errno;
823 }
824
825 const std::set<int> hal_pids = get_interesting_hal_pids();
826
827 ProtoOutputStream proto;
828 struct dirent* d;
829 status_t err = NO_ERROR;
830 while ((d = readdir(proc.get()))) {
831 int pid = atoi(d->d_name);
832 if (pid <= 0) {
833 continue;
834 }
835
836 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
837 std::string exe;
838 if (!android::base::Readlink(link_name, &exe)) {
839 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
840 continue;
841 }
842
843 bool is_java_process;
844 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
845 if (mType != "java") continue;
846 // Don't bother dumping backtraces for the zygote.
847 if (IsZygote(pid)) {
848 VLOG("Skipping Zygote");
849 continue;
850 }
851
852 is_java_process = true;
853 } else if (should_dump_native_traces(exe.c_str())) {
854 if (mType != "native") continue;
855 is_java_process = false;
856 } else if (hal_pids.find(pid) != hal_pids.end()) {
857 if (mType != "hal") continue;
858 is_java_process = false;
859 } else {
860 // Probably a native process we don't care about, continue.
861 VLOG("Skipping %d", pid);
862 continue;
863 }
864
865 Fpipe dumpPipe;
866 if (!dumpPipe.init()) {
867 ALOGW("TombstoneSection '%s' failed to setup dump pipe", this->name.string());
868 err = -errno;
869 break;
870 }
871
872 const uint64_t start = Nanotime();
873 pid_t child = fork();
874 if (child < 0) {
875 ALOGE("Failed to fork child process");
876 break;
877 } else if (child == 0) {
878 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700879 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800880 const int ret = dump_backtrace_to_file_timeout(
881 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700882 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800883 if (ret == -1) {
884 if (errno == 0) {
885 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
886 } else {
887 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
888 }
889 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700890 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800891 _exit(EXIT_SUCCESS);
892 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700893 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800894 // Parent process.
895 // Read from the pipe concurrently to avoid blocking the child.
896 FdBuffer buffer;
Yi Jin6355d2f2018-03-14 15:18:02 -0700897 err = buffer.readFully(&dumpPipe.readFd());
Kweku Adamseadd1232018-02-05 16:45:13 -0800898 if (err != NO_ERROR) {
899 ALOGW("TombstoneSection '%s' failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700900 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800901 break;
902 }
903
904 auto dump = std::make_unique<char[]>(buffer.size());
905 auto iterator = buffer.data();
906 int i = 0;
907 while (iterator.hasNext()) {
908 dump[i] = iterator.next();
909 i++;
910 }
911 long long token = proto.start(android::os::BackTraceProto::TRACES);
912 proto.write(android::os::BackTraceProto::Stack::PID, pid);
913 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
914 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
915 static_cast<long long>(Nanotime() - start));
916 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700917 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800918 }
919
920 proto.flush(pipeWriteFd);
921 return err;
922}