blob: e5bde0d83cf7e8980516c958a7617e24336b9f52 [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 Jin6cacbcb2018-03-30 14:04:52 -070046namespace android {
47namespace os {
48namespace incidentd {
49
Yi Jinb592e3b2018-02-01 15:17:04 -080050using namespace android::base;
Yi Jinc23fad22017-09-15 17:24:59 -070051using namespace android::util;
Joe Onorato1754d742016-11-21 17:51:35 -080052
Yi Jinc23fad22017-09-15 17:24:59 -070053// special section ids
54const int FIELD_ID_INCIDENT_HEADER = 1;
Yi Jin329130b2018-02-09 16:47:47 -080055const int FIELD_ID_INCIDENT_METADATA = 2;
Yi Jinc23fad22017-09-15 17:24:59 -070056
57// incident section parameters
Yi Jin3c034c92017-12-22 17:36:47 -080058const char INCIDENT_HELPER[] = "/system/bin/incident_helper";
Yi Jinc36e91d2018-03-08 11:25:58 -080059const char* GZIP[] = {"/system/bin/gzip", NULL};
Yi Jinb44f7d42017-07-21 12:12:59 -070060
Yi Jin1a11fa12018-02-22 16:44:10 -080061static pid_t fork_execute_incident_helper(const int id, Fpipe* p2cPipe, Fpipe* c2pPipe) {
Yi Jinb592e3b2018-02-01 15:17:04 -080062 const char* ihArgs[]{INCIDENT_HELPER, "-s", String8::format("%d", id).string(), NULL};
Yi Jinc36e91d2018-03-08 11:25:58 -080063 return fork_execute_cmd(const_cast<char**>(ihArgs), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -070064}
65
Yi Jin99c248f2017-08-25 18:11:58 -070066// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -080067static status_t write_section_header(int fd, int sectionId, size_t size) {
Yi Jin99c248f2017-08-25 18:11:58 -070068 uint8_t buf[20];
Yi Jinb592e3b2018-02-01 15:17:04 -080069 uint8_t* p = write_length_delimited_tag_header(buf, sectionId, size);
70 return WriteFully(fd, buf, p - buf) ? NO_ERROR : -errno;
Yi Jin99c248f2017-08-25 18:11:58 -070071}
72
Yi Jin98ce8102018-04-12 11:15:39 -070073static void write_section_stats(IncidentMetadata::SectionStats* stats, const FdBuffer& buffer) {
74 stats->set_dump_size_bytes(buffer.data().size());
75 stats->set_dump_duration_ms(buffer.durationMs());
76 stats->set_timed_out(buffer.timedOut());
77 stats->set_is_truncated(buffer.truncated());
78}
79
Kweku Adamseadd1232018-02-05 16:45:13 -080080// Reads data from FdBuffer and writes it to the requests file descriptor.
Yi Jinb592e3b2018-02-01 15:17:04 -080081static status_t write_report_requests(const int id, const FdBuffer& buffer,
82 ReportRequestSet* requests) {
Yi Jin0f047162017-09-05 13:44:22 -070083 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -070084 EncodedBuffer::iterator data = buffer.data();
85 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -070086 int writeable = 0;
87
Yi Jin0f047162017-09-05 13:44:22 -070088 // The streaming ones, group requests by spec in order to save unnecessary strip operations
89 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -080090 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -070091 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -070092 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -070093 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -070094 }
Yi Jin3ec5cc72018-01-26 13:42:43 -080095 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -070096 requestsBySpec[spec].push_back(request);
97 }
98
Yi Jin3ec5cc72018-01-26 13:42:43 -080099 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -0700100 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700101 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800102 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700103 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700104
Yi Jin3ec5cc72018-01-26 13:42:43 -0800105 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700106 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700107 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800108 if (err != NO_ERROR) {
109 request->err = err;
110 continue;
111 }
Yi Jinc23fad22017-09-15 17:24:59 -0700112 err = privacyBuffer.flush(request->fd);
Yi Jinb592e3b2018-02-01 15:17:04 -0800113 if (err != NO_ERROR) {
114 request->err = err;
115 continue;
116 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700117 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800118 VLOG("Section %d flushed %zu bytes to fd %d with spec %d", id, privacyBuffer.size(),
119 request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700120 }
Yi Jinc23fad22017-09-15 17:24:59 -0700121 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700122 }
123
124 // The dropbox file
125 if (requests->mainFd() >= 0) {
Yi Jin329130b2018-02-09 16:47:47 -0800126 PrivacySpec spec = PrivacySpec::new_spec(requests->mainDest());
Yi Jin3ec5cc72018-01-26 13:42:43 -0800127 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800128 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700129 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700130
Yi Jinc23fad22017-09-15 17:24:59 -0700131 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800132 if (err != NO_ERROR) {
133 requests->setMainFd(-1);
134 goto DONE;
135 }
Yi Jinc23fad22017-09-15 17:24:59 -0700136 err = privacyBuffer.flush(requests->mainFd());
Yi Jinb592e3b2018-02-01 15:17:04 -0800137 if (err != NO_ERROR) {
138 requests->setMainFd(-1);
139 goto DONE;
140 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700141 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800142 VLOG("Section %d flushed %zu bytes to dropbox %d with spec %d", id, privacyBuffer.size(),
143 requests->mainFd(), spec.dest);
Yi Jin98ce8102018-04-12 11:15:39 -0700144 // Reports bytes of the section uploaded via dropbox after filtering.
145 requests->sectionStats(id)->set_report_size_bytes(privacyBuffer.size());
Yi Jin99c248f2017-08-25 18:11:58 -0700146 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700147
148DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700149 // only returns error if there is no fd to write to.
150 return writeable > 0 ? NO_ERROR : err;
151}
152
153// ================================================================================
Yi Jin7fe3dee2018-04-16 16:13:04 -0700154Section::Section(int i, int64_t timeoutMs, bool deviceSpecific)
155 : id(i), timeoutMs(timeoutMs), deviceSpecific(deviceSpecific) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800156
Yi Jinb592e3b2018-02-01 15:17:04 -0800157Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800158
Joe Onorato1754d742016-11-21 17:51:35 -0800159// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800160HeaderSection::HeaderSection() : Section(FIELD_ID_INCIDENT_HEADER, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700161
Yi Jinb592e3b2018-02-01 15:17:04 -0800162HeaderSection::~HeaderSection() {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700163
Yi Jinb592e3b2018-02-01 15:17:04 -0800164status_t HeaderSection::Execute(ReportRequestSet* requests) const {
165 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700166 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800167 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700168
Yi Jinb592e3b2018-02-01 15:17:04 -0800169 for (vector<vector<uint8_t>>::const_iterator buf = headers.begin(); buf != headers.end();
170 buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700171 if (buf->empty()) continue;
172
173 // So the idea is only requests with negative fd are written to dropbox file.
174 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800175 write_section_header(fd, id, buf->size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800176 WriteFully(fd, (uint8_t const*)buf->data(), buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700177 // If there was an error now, there will be an error later and we will remove
178 // it from the list then.
179 }
180 }
181 return NO_ERROR;
182}
Yi Jin329130b2018-02-09 16:47:47 -0800183// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800184MetadataSection::MetadataSection() : Section(FIELD_ID_INCIDENT_METADATA, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700185
Yi Jinb592e3b2018-02-01 15:17:04 -0800186MetadataSection::~MetadataSection() {}
Yi Jin329130b2018-02-09 16:47:47 -0800187
Yi Jinb592e3b2018-02-01 15:17:04 -0800188status_t MetadataSection::Execute(ReportRequestSet* requests) const {
Yi Jin86dce412018-03-07 11:36:57 -0800189 ProtoOutputStream proto;
190 IncidentMetadata metadata = requests->metadata();
191 proto.write(FIELD_TYPE_ENUM | IncidentMetadata::kDestFieldNumber, metadata.dest());
192 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::kRequestSizeFieldNumber,
193 metadata.request_size());
194 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::kUseDropboxFieldNumber, metadata.use_dropbox());
195 for (auto iter = requests->allSectionStats().begin(); iter != requests->allSectionStats().end();
196 iter++) {
197 IncidentMetadata::SectionStats stats = iter->second;
198 uint64_t token = proto.start(FIELD_TYPE_MESSAGE | IncidentMetadata::kSectionsFieldNumber);
199 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kIdFieldNumber, stats.id());
200 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kSuccessFieldNumber,
201 stats.success());
202 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kReportSizeBytesFieldNumber,
203 stats.report_size_bytes());
204 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kExecDurationMsFieldNumber,
205 stats.exec_duration_ms());
206 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kDumpSizeBytesFieldNumber,
207 stats.dump_size_bytes());
208 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kDumpDurationMsFieldNumber,
209 stats.dump_duration_ms());
210 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kTimedOutFieldNumber,
211 stats.timed_out());
212 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kIsTruncatedFieldNumber,
213 stats.is_truncated());
214 proto.end(token);
215 }
216
Yi Jinb592e3b2018-02-01 15:17:04 -0800217 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jin329130b2018-02-09 16:47:47 -0800218 const sp<ReportRequest> request = *it;
Yi Jin86dce412018-03-07 11:36:57 -0800219 if (request->fd < 0 || request->err != NO_ERROR) {
Yi Jin329130b2018-02-09 16:47:47 -0800220 continue;
221 }
Yi Jin86dce412018-03-07 11:36:57 -0800222 write_section_header(request->fd, id, proto.size());
223 if (!proto.flush(request->fd)) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800224 ALOGW("Failed to write metadata to fd %d", request->fd);
225 // we don't fail if we can't write to a single request's fd.
226 }
Yi Jin329130b2018-02-09 16:47:47 -0800227 }
Yi Jin86dce412018-03-07 11:36:57 -0800228 if (requests->mainFd() >= 0) {
229 write_section_header(requests->mainFd(), id, proto.size());
230 if (!proto.flush(requests->mainFd())) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800231 ALOGW("Failed to write metadata to dropbox fd %d", requests->mainFd());
232 return -1;
233 }
Yi Jin329130b2018-02-09 16:47:47 -0800234 }
235 return NO_ERROR;
236}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700237// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -0800238static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
239
Yi Jin7fe3dee2018-04-16 16:13:04 -0700240FileSection::FileSection(int id, const char* filename, const bool deviceSpecific,
241 const int64_t timeoutMs)
242 : Section(id, timeoutMs, deviceSpecific), mFilename(filename) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700243 name = filename;
Yi Jin1a11fa12018-02-22 16:44:10 -0800244 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -0700245}
246
247FileSection::~FileSection() {}
248
Yi Jinb592e3b2018-02-01 15:17:04 -0800249status_t FileSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700250 // read from mFilename first, make sure the file is available
251 // add O_CLOEXEC to make sure it is closed when exec incident helper
Yi Jin6355d2f2018-03-14 15:18:02 -0700252 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
253 if (fd.get() == -1) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800254 ALOGW("FileSection '%s' failed to open file", this->name.string());
Yi Jin7fe3dee2018-04-16 16:13:04 -0700255 return this->deviceSpecific ? NO_ERROR : -errno;
Yi Jin0a3406f2017-06-22 19:23:11 -0700256 }
257
Yi Jinb44f7d42017-07-21 12:12:59 -0700258 FdBuffer buffer;
259 Fpipe p2cPipe;
260 Fpipe c2pPipe;
261 // initiate pipes to pass data to/from incident_helper
262 if (!p2cPipe.init() || !c2pPipe.init()) {
263 ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700264 return -errno;
265 }
266
Yi Jin1a11fa12018-02-22 16:44:10 -0800267 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700268 if (pid == -1) {
269 ALOGW("FileSection '%s' failed to fork", this->name.string());
270 return -errno;
271 }
272
273 // parent process
Yi Jine3dab2d2018-03-22 16:56:39 -0700274 status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
275 std::move(c2pPipe.readFd()),
276 this->timeoutMs, mIsSysfs);
Yi Jin98ce8102018-04-12 11:15:39 -0700277 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700278 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800279 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800280 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800281 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700282 return readStatus;
283 }
284
Yi Jinedfd5bb2017-09-06 17:09:11 -0700285 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700286 if (ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800287 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(),
288 strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700289 return ihStatus;
290 }
291
Yi Jinb592e3b2018-02-01 15:17:04 -0800292 VLOG("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
293 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700294 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700295 if (err != NO_ERROR) {
296 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
297 return err;
298 }
299
300 return NO_ERROR;
301}
Yi Jin1a11fa12018-02-22 16:44:10 -0800302// ================================================================================
303GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800304 va_list args;
305 va_start(args, filename);
306 mFilenames = varargs(filename, args);
307 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800308 name = "gzip";
309 for (int i = 0; mFilenames[i] != NULL; i++) {
310 name += " ";
311 name += mFilenames[i];
312 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800313}
Yi Jin0a3406f2017-06-22 19:23:11 -0700314
Yi Jin480de782018-04-06 15:37:36 -0700315GZipSection::~GZipSection() { free(mFilenames); }
Yi Jin1a11fa12018-02-22 16:44:10 -0800316
317status_t GZipSection::Execute(ReportRequestSet* requests) const {
318 // Reads the files in order, use the first available one.
319 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700320 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800321 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700322 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
323 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800324 break;
325 }
326 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
327 index++; // look at the next file.
328 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700329 VLOG("GZipSection is using file %s, fd=%d", mFilenames[index], fd.get());
Yi Jinc858e272018-03-28 15:32:50 -0700330 if (fd.get() == -1) {
Yi Jin6cacbcb2018-03-30 14:04:52 -0700331 ALOGW("GZipSection %s can't open all the files", this->name.string());
332 return NO_ERROR; // e.g. LAST_KMSG will reach here in user build.
Yi Jinc858e272018-03-28 15:32:50 -0700333 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800334 FdBuffer buffer;
335 Fpipe p2cPipe;
336 Fpipe c2pPipe;
337 // initiate pipes to pass data to/from gzip
338 if (!p2cPipe.init() || !c2pPipe.init()) {
339 ALOGW("GZipSection '%s' failed to setup pipes", this->name.string());
340 return -errno;
341 }
342
Yi Jinc36e91d2018-03-08 11:25:58 -0800343 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800344 if (pid == -1) {
345 ALOGW("GZipSection '%s' failed to fork", this->name.string());
346 return -errno;
347 }
348 // parent process
349
350 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
351 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
352 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
353 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700354 size_t fileLen = strlen(mFilenames[index]);
355 internalBuffer->writeRawVarint32(fileLen);
356 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800357 internalBuffer->writeRawByte(mFilenames[index][i]);
358 }
359 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
360 WIRE_TYPE_LENGTH_DELIMITED);
361 size_t editPos = internalBuffer->wp()->pos();
362 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
363 size_t dataBeginAt = internalBuffer->wp()->pos();
364 VLOG("GZipSection '%s' editPos=%zd, dataBeginAt=%zd", this->name.string(), editPos,
365 dataBeginAt);
366
Yi Jine3dab2d2018-03-22 16:56:39 -0700367 status_t readStatus = buffer.readProcessedDataInStream(
368 fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
369 isSysfs(mFilenames[index]));
Yi Jin98ce8102018-04-12 11:15:39 -0700370 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jin1a11fa12018-02-22 16:44:10 -0800371 if (readStatus != NO_ERROR || buffer.timedOut()) {
372 ALOGW("GZipSection '%s' failed to read data from gzip: %s, timedout: %s",
373 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
374 kill_child(pid);
375 return readStatus;
376 }
377
378 status_t gzipStatus = wait_child(pid);
379 if (gzipStatus != NO_ERROR) {
380 ALOGW("GZipSection '%s' abnormal child process: %s", this->name.string(),
381 strerror(-gzipStatus));
382 return gzipStatus;
383 }
384 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
385 size_t dataSize = buffer.size() - dataBeginAt;
386 internalBuffer->wp()->rewind()->move(editPos);
387 internalBuffer->writeRawVarint32(dataSize);
388 internalBuffer->copy(dataBeginAt, dataSize);
389 VLOG("GZipSection '%s' wrote %zd bytes in %d ms, dataSize=%zd", this->name.string(),
390 buffer.size(), (int)buffer.durationMs(), dataSize);
391 status_t err = write_report_requests(this->id, buffer, requests);
392 if (err != NO_ERROR) {
393 ALOGW("GZipSection '%s' failed writing: %s", this->name.string(), strerror(-err));
394 return err;
395 }
396
397 return NO_ERROR;
398}
Kweku Adamseadd1232018-02-05 16:45:13 -0800399
Yi Jin0a3406f2017-06-22 19:23:11 -0700400// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800401struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800402 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700403 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800404
405 // Lock protects these fields
406 mutex lock;
407 bool workerDone;
408 status_t workerError;
409
410 WorkerThreadData(const WorkerThreadSection* section);
411 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800412};
413
414WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700415 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800416
Yi Jinb592e3b2018-02-01 15:17:04 -0800417WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800418
419// ================================================================================
Kweku Adamseadd1232018-02-05 16:45:13 -0800420WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
421 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800422
Yi Jinb592e3b2018-02-01 15:17:04 -0800423WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800424
Yi Jinb592e3b2018-02-01 15:17:04 -0800425static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800426 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700427 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800428
429 {
430 unique_lock<mutex> lock(data->lock);
431 data->workerDone = true;
432 data->workerError = err;
433 }
434
Yi Jin6355d2f2018-03-14 15:18:02 -0700435 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800436 data->decStrong(data->section);
437 // data might be gone now. don't use it after this point in this thread.
438 return NULL;
439}
440
Yi Jinb592e3b2018-02-01 15:17:04 -0800441status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800442 status_t err = NO_ERROR;
443 pthread_t thread;
444 pthread_attr_t attr;
445 bool timedOut = false;
446 FdBuffer buffer;
447
448 // Data shared between this thread and the worker thread.
449 sp<WorkerThreadData> data = new WorkerThreadData(this);
450
451 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700452 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800453 return -errno;
454 }
455
456 // The worker thread needs a reference and we can't let the count go to zero
457 // if that thread is slow to start.
458 data->incStrong(this);
459
460 // Create the thread
461 err = pthread_attr_init(&attr);
462 if (err != 0) {
463 return -err;
464 }
465 // TODO: Do we need to tweak thread priority?
466 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
467 if (err != 0) {
468 pthread_attr_destroy(&attr);
469 return -err;
470 }
471 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
472 if (err != 0) {
473 pthread_attr_destroy(&attr);
474 return -err;
475 }
476 pthread_attr_destroy(&attr);
477
478 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jine3dab2d2018-03-22 16:56:39 -0700479 err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800480 if (err != NO_ERROR) {
481 // TODO: Log this error into the incident report.
482 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800483 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800484 }
485
486 // Done with the read fd. The worker thread closes the write one so
487 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700488 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800489
490 // If the worker side is finished, then return its error (which may overwrite
491 // our possible error -- but it's more interesting anyway). If not, then we timed out.
492 {
493 unique_lock<mutex> lock(data->lock);
494 if (!data->workerDone) {
495 // We timed out
496 timedOut = true;
497 } else {
498 if (data->workerError != NO_ERROR) {
499 err = data->workerError;
500 // TODO: Log this error into the incident report.
501 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800502 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800503 }
504 }
505 }
Yi Jin98ce8102018-04-12 11:15:39 -0700506 write_section_stats(requests->sectionStats(this->id), buffer);
Joe Onorato1754d742016-11-21 17:51:35 -0800507 if (timedOut || buffer.timedOut()) {
508 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
509 return NO_ERROR;
510 }
511
512 if (buffer.truncated()) {
513 // TODO: Log this into the incident report.
514 }
515
516 // TODO: There was an error with the command or buffering. Report that. For now
517 // just exit with a log messasge.
518 if (err != NO_ERROR) {
519 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800520 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800521 return NO_ERROR;
522 }
523
524 // Write the data that was collected
Yi Jinb592e3b2018-02-01 15:17:04 -0800525 VLOG("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
526 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700527 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800528 if (err != NO_ERROR) {
529 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
530 return err;
531 }
532
533 return NO_ERROR;
534}
535
536// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700537CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800538 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800539 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700540 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800541 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800542 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800543 name = "cmd";
544 for (int i = 0; mCommand[i] != NULL; i++) {
545 name += " ";
546 name += mCommand[i];
547 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700548}
Joe Onorato1754d742016-11-21 17:51:35 -0800549
Yi Jinb592e3b2018-02-01 15:17:04 -0800550CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700551 va_list args;
552 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800553 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800554 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800555 name = "cmd";
556 for (int i = 0; mCommand[i] != NULL; i++) {
557 name += " ";
558 name += mCommand[i];
559 }
Joe Onorato1754d742016-11-21 17:51:35 -0800560}
561
Yi Jinb592e3b2018-02-01 15:17:04 -0800562CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800563
Yi Jinb592e3b2018-02-01 15:17:04 -0800564status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700565 FdBuffer buffer;
566 Fpipe cmdPipe;
567 Fpipe ihPipe;
568
569 if (!cmdPipe.init() || !ihPipe.init()) {
570 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
571 return -errno;
572 }
573
Yi Jinc36e91d2018-03-08 11:25:58 -0800574 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700575 if (cmdPid == -1) {
576 ALOGW("CommandSection '%s' failed to fork", this->name.string());
577 return -errno;
578 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800579 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700580 if (ihPid == -1) {
581 ALOGW("CommandSection '%s' failed to fork", this->name.string());
582 return -errno;
583 }
584
Yi Jin6355d2f2018-03-14 15:18:02 -0700585 cmdPipe.writeFd().reset();
Yi Jine3dab2d2018-03-22 16:56:39 -0700586 status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
Yi Jin98ce8102018-04-12 11:15:39 -0700587 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700588 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800589 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800590 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800591 kill_child(cmdPid);
592 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700593 return readStatus;
594 }
595
Kweku Adamseadd1232018-02-05 16:45:13 -0800596 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800597 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700598 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800599 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700600 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800601 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident "
602 "helper: %s",
603 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700604 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
605 }
606
Yi Jinb592e3b2018-02-01 15:17:04 -0800607 VLOG("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
608 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700609 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700610 if (err != NO_ERROR) {
611 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
612 return err;
613 }
Joe Onorato1754d742016-11-21 17:51:35 -0800614 return NO_ERROR;
615}
616
617// ================================================================================
618DumpsysSection::DumpsysSection(int id, const char* service, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800619 : WorkerThreadSection(id), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800620 name = "dumpsys ";
621 name += service;
622
623 va_list args;
624 va_start(args, service);
625 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700626 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800627 if (arg == NULL) {
628 break;
629 }
630 mArgs.add(String16(arg));
631 name += " ";
632 name += arg;
633 }
634 va_end(args);
635}
636
Yi Jinb592e3b2018-02-01 15:17:04 -0800637DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800638
Yi Jinb592e3b2018-02-01 15:17:04 -0800639status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800640 // checkService won't wait for the service to show up like getService will.
641 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700642
Joe Onorato1754d742016-11-21 17:51:35 -0800643 if (service == NULL) {
644 // Returning an error interrupts the entire incident report, so just
645 // log the failure.
646 // TODO: have a meta record inside the report that would log this
647 // failure inside the report, because the fact that we can't find
648 // the service is good data in and of itself. This is running in
649 // another thread so lock that carefully...
650 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
651 return NO_ERROR;
652 }
653
654 service->dump(pipeWriteFd, mArgs);
655
656 return NO_ERROR;
657}
Yi Jin3c034c92017-12-22 17:36:47 -0800658
659// ================================================================================
660// initialization only once in Section.cpp.
661map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
662
Yi Jinb592e3b2018-02-01 15:17:04 -0800663LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3c034c92017-12-22 17:36:47 -0800664 name += "logcat ";
665 name += android_log_id_to_name(logID);
666 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800667 case LOG_ID_EVENTS:
668 case LOG_ID_STATS:
669 case LOG_ID_SECURITY:
670 mBinary = true;
671 break;
672 default:
673 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800674 }
675}
676
Yi Jinb592e3b2018-02-01 15:17:04 -0800677LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800678
Yi Jinb592e3b2018-02-01 15:17:04 -0800679static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800680 while (len > 0) {
681 char c = buf[len - 1];
682 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
683 len--;
684 } else {
685 break;
686 }
687 }
688 return len;
689}
690
691static inline int32_t get4LE(uint8_t const* src) {
692 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
693}
694
Yi Jinb592e3b2018-02-01 15:17:04 -0800695status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800696 // Open log buffer and getting logs since last retrieved time if any.
697 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800698 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
699 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
700 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
701 gLastLogsRetrieved[mLogID], 0),
702 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800703
704 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700705 ALOGE("LogSection %s: Can't get logger.", this->name.string());
706 return -1;
Yi Jin3c034c92017-12-22 17:36:47 -0800707 }
708
709 log_msg msg;
710 log_time lastTimestamp(0);
711
712 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800713 while (true) { // keeps reading until logd buffer is fully read.
Yi Jin83fb1d52018-03-16 12:03:53 -0700714 status_t err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800715 // err = 0 - no content, unexpected connection drop or EOF.
716 // err = +ive number - size of retrieved data from logger
717 // err = -ive number, OS supplied error _except_ for -EAGAIN
718 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
719 if (err <= 0) {
720 if (err != -EAGAIN) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700721 ALOGW("LogSection %s: fails to read a log_msg.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800722 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700723 // dump previous logs and don't consider this error a failure.
Yi Jin3c034c92017-12-22 17:36:47 -0800724 break;
725 }
726 if (mBinary) {
727 // remove the first uint32 which is tag's index in event log tags
728 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800729 msg.len() - sizeof(uint32_t));
730 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800731 android_log_list_element elem;
732
733 lastTimestamp.tv_sec = msg.entry_v1.sec;
734 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
735
736 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800737 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800738 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
739 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800740 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800741 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
742 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800743 proto.write(BinaryLogEntry::TAG_INDEX,
744 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800745 do {
746 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800747 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800748 switch (elem.type) {
749 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800750 proto.write(BinaryLogEntry::Elem::TYPE,
751 BinaryLogEntry::Elem::EVENT_TYPE_INT);
752 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800753 break;
754 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800755 proto.write(BinaryLogEntry::Elem::TYPE,
756 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
757 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800758 break;
759 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800760 proto.write(BinaryLogEntry::Elem::TYPE,
761 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800762 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
763 break;
764 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800765 proto.write(BinaryLogEntry::Elem::TYPE,
766 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800767 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
768 break;
769 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800770 proto.write(BinaryLogEntry::Elem::TYPE,
771 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800772 break;
773 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800774 proto.write(BinaryLogEntry::Elem::TYPE,
775 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800776 break;
777 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800778 proto.write(BinaryLogEntry::Elem::TYPE,
779 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800780 break;
781 }
782 proto.end(elemToken);
783 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
784 proto.end(token);
785 if (context) {
786 android_log_destroy(&context);
787 }
788 } else {
789 AndroidLogEntry entry;
790 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
791 if (err != NO_ERROR) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700792 ALOGW("LogSection %s: fails to process to an entry.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800793 break;
794 }
795 lastTimestamp.tv_sec = entry.tv_sec;
796 lastTimestamp.tv_nsec = entry.tv_nsec;
797
798 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800799 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800800 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
801 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
802 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
803 proto.write(TextLogEntry::UID, entry.uid);
804 proto.write(TextLogEntry::PID, entry.pid);
805 proto.write(TextLogEntry::TID, entry.tid);
806 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800807 proto.write(TextLogEntry::LOG, entry.message,
808 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800809 proto.end(token);
810 }
811 }
812 gLastLogsRetrieved[mLogID] = lastTimestamp;
813 proto.flush(pipeWriteFd);
Yi Jin83fb1d52018-03-16 12:03:53 -0700814 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800815}
Kweku Adamseadd1232018-02-05 16:45:13 -0800816
817// ================================================================================
818
819TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
820 : WorkerThreadSection(id, timeoutMs), mType(type) {
821 name += "tombstone ";
822 name += type;
823}
824
825TombstoneSection::~TombstoneSection() {}
826
827status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
828 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
829 if (proc.get() == nullptr) {
830 ALOGE("opendir /proc failed: %s\n", strerror(errno));
831 return -errno;
832 }
833
834 const std::set<int> hal_pids = get_interesting_hal_pids();
835
836 ProtoOutputStream proto;
837 struct dirent* d;
838 status_t err = NO_ERROR;
839 while ((d = readdir(proc.get()))) {
840 int pid = atoi(d->d_name);
841 if (pid <= 0) {
842 continue;
843 }
844
845 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
846 std::string exe;
847 if (!android::base::Readlink(link_name, &exe)) {
848 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
849 continue;
850 }
851
852 bool is_java_process;
853 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
854 if (mType != "java") continue;
855 // Don't bother dumping backtraces for the zygote.
856 if (IsZygote(pid)) {
857 VLOG("Skipping Zygote");
858 continue;
859 }
860
861 is_java_process = true;
862 } else if (should_dump_native_traces(exe.c_str())) {
863 if (mType != "native") continue;
864 is_java_process = false;
865 } else if (hal_pids.find(pid) != hal_pids.end()) {
866 if (mType != "hal") continue;
867 is_java_process = false;
868 } else {
869 // Probably a native process we don't care about, continue.
870 VLOG("Skipping %d", pid);
871 continue;
872 }
873
874 Fpipe dumpPipe;
875 if (!dumpPipe.init()) {
876 ALOGW("TombstoneSection '%s' failed to setup dump pipe", this->name.string());
877 err = -errno;
878 break;
879 }
880
881 const uint64_t start = Nanotime();
882 pid_t child = fork();
883 if (child < 0) {
884 ALOGE("Failed to fork child process");
885 break;
886 } else if (child == 0) {
887 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700888 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800889 const int ret = dump_backtrace_to_file_timeout(
890 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700891 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800892 if (ret == -1) {
893 if (errno == 0) {
894 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
895 } else {
896 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
897 }
898 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700899 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800900 _exit(EXIT_SUCCESS);
901 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700902 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800903 // Parent process.
904 // Read from the pipe concurrently to avoid blocking the child.
905 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700906 err = buffer.readFully(dumpPipe.readFd().get());
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700907 // Wait on the child to avoid it becoming a zombie process.
908 status_t cStatus = wait_child(child);
Kweku Adamseadd1232018-02-05 16:45:13 -0800909 if (err != NO_ERROR) {
910 ALOGW("TombstoneSection '%s' failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700911 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800912 break;
913 }
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700914 if (cStatus != NO_ERROR) {
915 ALOGE("TombstoneSection '%s' child had an issue: %s\n", this->name.string(), strerror(-cStatus));
916 }
Kweku Adamseadd1232018-02-05 16:45:13 -0800917
918 auto dump = std::make_unique<char[]>(buffer.size());
919 auto iterator = buffer.data();
920 int i = 0;
921 while (iterator.hasNext()) {
922 dump[i] = iterator.next();
923 i++;
924 }
Yi Jin6cacbcb2018-03-30 14:04:52 -0700925 uint64_t token = proto.start(android::os::BackTraceProto::TRACES);
Kweku Adamseadd1232018-02-05 16:45:13 -0800926 proto.write(android::os::BackTraceProto::Stack::PID, pid);
927 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
928 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
929 static_cast<long long>(Nanotime() - start));
930 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700931 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800932 }
933
934 proto.flush(pipeWriteFd);
935 return err;
936}
Yi Jin6cacbcb2018-03-30 14:04:52 -0700937
938} // namespace incidentd
939} // namespace os
Yi Jin98ce8102018-04-12 11:15:39 -0700940} // namespace android