blob: 5c4988b5752109ca47eb94ba4896e50827cb3a12 [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 Jinb592e3b2018-02-01 15:17:04 -0800154Section::Section(int i, const int64_t timeoutMs) : id(i), timeoutMs(timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800155
Yi Jinb592e3b2018-02-01 15:17:04 -0800156Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800157
Joe Onorato1754d742016-11-21 17:51:35 -0800158// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800159HeaderSection::HeaderSection() : Section(FIELD_ID_INCIDENT_HEADER, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700160
Yi Jinb592e3b2018-02-01 15:17:04 -0800161HeaderSection::~HeaderSection() {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700162
Yi Jinb592e3b2018-02-01 15:17:04 -0800163status_t HeaderSection::Execute(ReportRequestSet* requests) const {
164 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700165 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800166 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700167
Yi Jinb592e3b2018-02-01 15:17:04 -0800168 for (vector<vector<uint8_t>>::const_iterator buf = headers.begin(); buf != headers.end();
169 buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700170 if (buf->empty()) continue;
171
172 // So the idea is only requests with negative fd are written to dropbox file.
173 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800174 write_section_header(fd, id, buf->size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800175 WriteFully(fd, (uint8_t const*)buf->data(), buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700176 // If there was an error now, there will be an error later and we will remove
177 // it from the list then.
178 }
179 }
180 return NO_ERROR;
181}
Yi Jin329130b2018-02-09 16:47:47 -0800182// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800183MetadataSection::MetadataSection() : Section(FIELD_ID_INCIDENT_METADATA, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700184
Yi Jinb592e3b2018-02-01 15:17:04 -0800185MetadataSection::~MetadataSection() {}
Yi Jin329130b2018-02-09 16:47:47 -0800186
Yi Jinb592e3b2018-02-01 15:17:04 -0800187status_t MetadataSection::Execute(ReportRequestSet* requests) const {
Yi Jin86dce412018-03-07 11:36:57 -0800188 ProtoOutputStream proto;
189 IncidentMetadata metadata = requests->metadata();
190 proto.write(FIELD_TYPE_ENUM | IncidentMetadata::kDestFieldNumber, metadata.dest());
191 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::kRequestSizeFieldNumber,
192 metadata.request_size());
193 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::kUseDropboxFieldNumber, metadata.use_dropbox());
194 for (auto iter = requests->allSectionStats().begin(); iter != requests->allSectionStats().end();
195 iter++) {
196 IncidentMetadata::SectionStats stats = iter->second;
197 uint64_t token = proto.start(FIELD_TYPE_MESSAGE | IncidentMetadata::kSectionsFieldNumber);
198 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kIdFieldNumber, stats.id());
199 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kSuccessFieldNumber,
200 stats.success());
201 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kReportSizeBytesFieldNumber,
202 stats.report_size_bytes());
203 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kExecDurationMsFieldNumber,
204 stats.exec_duration_ms());
205 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kDumpSizeBytesFieldNumber,
206 stats.dump_size_bytes());
207 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kDumpDurationMsFieldNumber,
208 stats.dump_duration_ms());
209 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kTimedOutFieldNumber,
210 stats.timed_out());
211 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kIsTruncatedFieldNumber,
212 stats.is_truncated());
213 proto.end(token);
214 }
215
Yi Jinb592e3b2018-02-01 15:17:04 -0800216 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jin329130b2018-02-09 16:47:47 -0800217 const sp<ReportRequest> request = *it;
Yi Jin86dce412018-03-07 11:36:57 -0800218 if (request->fd < 0 || request->err != NO_ERROR) {
Yi Jin329130b2018-02-09 16:47:47 -0800219 continue;
220 }
Yi Jin86dce412018-03-07 11:36:57 -0800221 write_section_header(request->fd, id, proto.size());
222 if (!proto.flush(request->fd)) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800223 ALOGW("Failed to write metadata to fd %d", request->fd);
224 // we don't fail if we can't write to a single request's fd.
225 }
Yi Jin329130b2018-02-09 16:47:47 -0800226 }
Yi Jin86dce412018-03-07 11:36:57 -0800227 if (requests->mainFd() >= 0) {
228 write_section_header(requests->mainFd(), id, proto.size());
229 if (!proto.flush(requests->mainFd())) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800230 ALOGW("Failed to write metadata to dropbox fd %d", requests->mainFd());
231 return -1;
232 }
Yi Jin329130b2018-02-09 16:47:47 -0800233 }
234 return NO_ERROR;
235}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700236// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -0800237static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
238
Yi Jinb44f7d42017-07-21 12:12:59 -0700239FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Yi Jinb592e3b2018-02-01 15:17:04 -0800240 : Section(id, timeoutMs), mFilename(filename) {
Yi Jin3be0b432018-04-20 17:08:11 -0700241 name = "file ";
242 name += filename;
Yi Jin1a11fa12018-02-22 16:44:10 -0800243 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -0700244}
245
246FileSection::~FileSection() {}
247
Yi Jinb592e3b2018-02-01 15:17:04 -0800248status_t FileSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700249 // read from mFilename first, make sure the file is available
250 // add O_CLOEXEC to make sure it is closed when exec incident helper
Yi Jin6355d2f2018-03-14 15:18:02 -0700251 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
252 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700253 ALOGW("[%s] failed to open file", this->name.string());
Yi Jinb592e3b2018-02-01 15:17:04 -0800254 return -errno;
Yi Jin0a3406f2017-06-22 19:23:11 -0700255 }
256
Yi Jinb44f7d42017-07-21 12:12:59 -0700257 FdBuffer buffer;
258 Fpipe p2cPipe;
259 Fpipe c2pPipe;
260 // initiate pipes to pass data to/from incident_helper
261 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700262 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700263 return -errno;
264 }
265
Yi Jin1a11fa12018-02-22 16:44:10 -0800266 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700267 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700268 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700269 return -errno;
270 }
271
272 // parent process
Yi Jine3dab2d2018-03-22 16:56:39 -0700273 status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
274 std::move(c2pPipe.readFd()),
275 this->timeoutMs, mIsSysfs);
Yi Jin98ce8102018-04-12 11:15:39 -0700276 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700277 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700278 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800279 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800280 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700281 return readStatus;
282 }
283
Yi Jinedfd5bb2017-09-06 17:09:11 -0700284 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700285 if (ihStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700286 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700287 return ihStatus;
288 }
289
Yi Jin3be0b432018-04-20 17:08:11 -0700290 return write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700291}
Yi Jin1a11fa12018-02-22 16:44:10 -0800292// ================================================================================
293GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800294 va_list args;
295 va_start(args, filename);
296 mFilenames = varargs(filename, args);
297 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800298 name = "gzip";
299 for (int i = 0; mFilenames[i] != NULL; i++) {
300 name += " ";
301 name += mFilenames[i];
302 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800303}
Yi Jin0a3406f2017-06-22 19:23:11 -0700304
Yi Jin480de782018-04-06 15:37:36 -0700305GZipSection::~GZipSection() { free(mFilenames); }
Yi Jin1a11fa12018-02-22 16:44:10 -0800306
307status_t GZipSection::Execute(ReportRequestSet* requests) const {
308 // Reads the files in order, use the first available one.
309 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700310 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800311 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700312 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
313 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800314 break;
315 }
316 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
317 index++; // look at the next file.
318 }
Yi Jinc858e272018-03-28 15:32:50 -0700319 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700320 ALOGW("[%s] can't open all the files", this->name.string());
Yi Jin6cacbcb2018-03-30 14:04:52 -0700321 return NO_ERROR; // e.g. LAST_KMSG will reach here in user build.
Yi Jinc858e272018-03-28 15:32:50 -0700322 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800323 FdBuffer buffer;
324 Fpipe p2cPipe;
325 Fpipe c2pPipe;
326 // initiate pipes to pass data to/from gzip
327 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700328 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800329 return -errno;
330 }
331
Yi Jinc36e91d2018-03-08 11:25:58 -0800332 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800333 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700334 ALOGW("[%s] failed to fork", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800335 return -errno;
336 }
337 // parent process
338
339 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
340 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
341 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
342 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700343 size_t fileLen = strlen(mFilenames[index]);
344 internalBuffer->writeRawVarint32(fileLen);
345 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800346 internalBuffer->writeRawByte(mFilenames[index][i]);
347 }
348 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
349 WIRE_TYPE_LENGTH_DELIMITED);
350 size_t editPos = internalBuffer->wp()->pos();
351 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
352 size_t dataBeginAt = internalBuffer->wp()->pos();
Yi Jin3be0b432018-04-20 17:08:11 -0700353 VLOG("[%s] editPos=%zu, dataBeginAt=%zu", this->name.string(), editPos, dataBeginAt);
Yi Jin1a11fa12018-02-22 16:44:10 -0800354
Yi Jine3dab2d2018-03-22 16:56:39 -0700355 status_t readStatus = buffer.readProcessedDataInStream(
356 fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
357 isSysfs(mFilenames[index]));
Yi Jin98ce8102018-04-12 11:15:39 -0700358 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jin1a11fa12018-02-22 16:44:10 -0800359 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700360 ALOGW("[%s] failed to read data from gzip: %s, timedout: %s", this->name.string(),
361 strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin1a11fa12018-02-22 16:44:10 -0800362 kill_child(pid);
363 return readStatus;
364 }
365
366 status_t gzipStatus = wait_child(pid);
367 if (gzipStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700368 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-gzipStatus));
Yi Jin1a11fa12018-02-22 16:44:10 -0800369 return gzipStatus;
370 }
371 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
372 size_t dataSize = buffer.size() - dataBeginAt;
373 internalBuffer->wp()->rewind()->move(editPos);
374 internalBuffer->writeRawVarint32(dataSize);
375 internalBuffer->copy(dataBeginAt, dataSize);
Yi Jin1a11fa12018-02-22 16:44:10 -0800376
Yi Jin3be0b432018-04-20 17:08:11 -0700377 return write_report_requests(this->id, buffer, requests);
Yi Jin1a11fa12018-02-22 16:44:10 -0800378}
Kweku Adamseadd1232018-02-05 16:45:13 -0800379
Yi Jin0a3406f2017-06-22 19:23:11 -0700380// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800381struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800382 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700383 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800384
385 // Lock protects these fields
386 mutex lock;
387 bool workerDone;
388 status_t workerError;
389
390 WorkerThreadData(const WorkerThreadSection* section);
391 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800392};
393
394WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700395 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800396
Yi Jinb592e3b2018-02-01 15:17:04 -0800397WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800398
399// ================================================================================
Kweku Adamseadd1232018-02-05 16:45:13 -0800400WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
401 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800402
Yi Jinb592e3b2018-02-01 15:17:04 -0800403WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800404
Yi Jinb592e3b2018-02-01 15:17:04 -0800405static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800406 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700407 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800408
409 {
410 unique_lock<mutex> lock(data->lock);
411 data->workerDone = true;
412 data->workerError = err;
413 }
414
Yi Jin6355d2f2018-03-14 15:18:02 -0700415 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800416 data->decStrong(data->section);
417 // data might be gone now. don't use it after this point in this thread.
418 return NULL;
419}
420
Yi Jinb592e3b2018-02-01 15:17:04 -0800421status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800422 status_t err = NO_ERROR;
423 pthread_t thread;
424 pthread_attr_t attr;
425 bool timedOut = false;
426 FdBuffer buffer;
427
428 // Data shared between this thread and the worker thread.
429 sp<WorkerThreadData> data = new WorkerThreadData(this);
430
431 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700432 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800433 return -errno;
434 }
435
436 // The worker thread needs a reference and we can't let the count go to zero
437 // if that thread is slow to start.
438 data->incStrong(this);
439
440 // Create the thread
441 err = pthread_attr_init(&attr);
442 if (err != 0) {
443 return -err;
444 }
445 // TODO: Do we need to tweak thread priority?
446 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
447 if (err != 0) {
448 pthread_attr_destroy(&attr);
449 return -err;
450 }
451 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
452 if (err != 0) {
453 pthread_attr_destroy(&attr);
454 return -err;
455 }
456 pthread_attr_destroy(&attr);
457
458 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jine3dab2d2018-03-22 16:56:39 -0700459 err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800460 if (err != NO_ERROR) {
461 // TODO: Log this error into the incident report.
Yi Jin3be0b432018-04-20 17:08:11 -0700462 ALOGW("[%s] reader failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800463 }
464
465 // Done with the read fd. The worker thread closes the write one so
466 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700467 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800468
469 // If the worker side is finished, then return its error (which may overwrite
470 // our possible error -- but it's more interesting anyway). If not, then we timed out.
471 {
472 unique_lock<mutex> lock(data->lock);
473 if (!data->workerDone) {
474 // We timed out
475 timedOut = true;
476 } else {
477 if (data->workerError != NO_ERROR) {
478 err = data->workerError;
479 // TODO: Log this error into the incident report.
Yi Jin3be0b432018-04-20 17:08:11 -0700480 ALOGW("[%s] worker failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800481 }
482 }
483 }
Yi Jin98ce8102018-04-12 11:15:39 -0700484 write_section_stats(requests->sectionStats(this->id), buffer);
Joe Onorato1754d742016-11-21 17:51:35 -0800485 if (timedOut || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700486 ALOGW("[%s] timed out", this->name.string());
Joe Onorato1754d742016-11-21 17:51:35 -0800487 return NO_ERROR;
488 }
489
Joe Onorato1754d742016-11-21 17:51:35 -0800490 // TODO: There was an error with the command or buffering. Report that. For now
491 // just exit with a log messasge.
492 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700493 ALOGW("[%s] failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800494 return NO_ERROR;
495 }
496
497 // Write the data that was collected
Yi Jin3be0b432018-04-20 17:08:11 -0700498 return write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800499}
500
501// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700502CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800503 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800504 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700505 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800506 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800507 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800508 name = "cmd";
509 for (int i = 0; mCommand[i] != NULL; i++) {
510 name += " ";
511 name += mCommand[i];
512 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700513}
Joe Onorato1754d742016-11-21 17:51:35 -0800514
Yi Jinb592e3b2018-02-01 15:17:04 -0800515CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700516 va_list args;
517 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800518 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800519 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800520 name = "cmd";
521 for (int i = 0; mCommand[i] != NULL; i++) {
522 name += " ";
523 name += mCommand[i];
524 }
Joe Onorato1754d742016-11-21 17:51:35 -0800525}
526
Yi Jinb592e3b2018-02-01 15:17:04 -0800527CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800528
Yi Jinb592e3b2018-02-01 15:17:04 -0800529status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700530 FdBuffer buffer;
531 Fpipe cmdPipe;
532 Fpipe ihPipe;
533
534 if (!cmdPipe.init() || !ihPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700535 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700536 return -errno;
537 }
538
Yi Jinc36e91d2018-03-08 11:25:58 -0800539 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700540 if (cmdPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700541 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700542 return -errno;
543 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800544 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700545 if (ihPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700546 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700547 return -errno;
548 }
549
Yi Jin6355d2f2018-03-14 15:18:02 -0700550 cmdPipe.writeFd().reset();
Yi Jine3dab2d2018-03-22 16:56:39 -0700551 status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
Yi Jin98ce8102018-04-12 11:15:39 -0700552 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700553 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700554 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800555 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800556 kill_child(cmdPid);
557 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700558 return readStatus;
559 }
560
Kweku Adamseadd1232018-02-05 16:45:13 -0800561 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800562 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700563 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800564 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700565 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700566 ALOGW("[%s] abnormal child processes, return status: command: %s, incident "
Yi Jinb592e3b2018-02-01 15:17:04 -0800567 "helper: %s",
568 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700569 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
570 }
571
Yi Jin3be0b432018-04-20 17:08:11 -0700572 return write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800573}
574
575// ================================================================================
576DumpsysSection::DumpsysSection(int id, const char* service, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800577 : WorkerThreadSection(id), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800578 name = "dumpsys ";
579 name += service;
580
581 va_list args;
582 va_start(args, service);
583 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700584 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800585 if (arg == NULL) {
586 break;
587 }
588 mArgs.add(String16(arg));
589 name += " ";
590 name += arg;
591 }
592 va_end(args);
593}
594
Yi Jinb592e3b2018-02-01 15:17:04 -0800595DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800596
Yi Jinb592e3b2018-02-01 15:17:04 -0800597status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800598 // checkService won't wait for the service to show up like getService will.
599 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700600
Joe Onorato1754d742016-11-21 17:51:35 -0800601 if (service == NULL) {
602 // Returning an error interrupts the entire incident report, so just
603 // log the failure.
604 // TODO: have a meta record inside the report that would log this
605 // failure inside the report, because the fact that we can't find
606 // the service is good data in and of itself. This is running in
607 // another thread so lock that carefully...
608 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
609 return NO_ERROR;
610 }
611
612 service->dump(pipeWriteFd, mArgs);
613
614 return NO_ERROR;
615}
Yi Jin3c034c92017-12-22 17:36:47 -0800616
617// ================================================================================
618// initialization only once in Section.cpp.
619map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
620
Yi Jinb592e3b2018-02-01 15:17:04 -0800621LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3be0b432018-04-20 17:08:11 -0700622 name = "logcat ";
Yi Jin3c034c92017-12-22 17:36:47 -0800623 name += android_log_id_to_name(logID);
624 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800625 case LOG_ID_EVENTS:
626 case LOG_ID_STATS:
627 case LOG_ID_SECURITY:
628 mBinary = true;
629 break;
630 default:
631 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800632 }
633}
634
Yi Jinb592e3b2018-02-01 15:17:04 -0800635LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800636
Yi Jinb592e3b2018-02-01 15:17:04 -0800637static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800638 while (len > 0) {
639 char c = buf[len - 1];
640 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
641 len--;
642 } else {
643 break;
644 }
645 }
646 return len;
647}
648
649static inline int32_t get4LE(uint8_t const* src) {
650 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
651}
652
Yi Jinb592e3b2018-02-01 15:17:04 -0800653status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800654 // Open log buffer and getting logs since last retrieved time if any.
655 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800656 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
657 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
658 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
659 gLastLogsRetrieved[mLogID], 0),
660 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800661
662 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin3be0b432018-04-20 17:08:11 -0700663 ALOGE("[%s] Can't get logger.", this->name.string());
Yi Jin83fb1d52018-03-16 12:03:53 -0700664 return -1;
Yi Jin3c034c92017-12-22 17:36:47 -0800665 }
666
667 log_msg msg;
668 log_time lastTimestamp(0);
669
670 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800671 while (true) { // keeps reading until logd buffer is fully read.
Yi Jin83fb1d52018-03-16 12:03:53 -0700672 status_t err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800673 // err = 0 - no content, unexpected connection drop or EOF.
674 // err = +ive number - size of retrieved data from logger
675 // err = -ive number, OS supplied error _except_ for -EAGAIN
676 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
677 if (err <= 0) {
678 if (err != -EAGAIN) {
Yi Jin3be0b432018-04-20 17:08:11 -0700679 ALOGW("[%s] fails to read a log_msg.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800680 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700681 // dump previous logs and don't consider this error a failure.
Yi Jin3c034c92017-12-22 17:36:47 -0800682 break;
683 }
684 if (mBinary) {
685 // remove the first uint32 which is tag's index in event log tags
686 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800687 msg.len() - sizeof(uint32_t));
688 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800689 android_log_list_element elem;
690
691 lastTimestamp.tv_sec = msg.entry_v1.sec;
692 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
693
694 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800695 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800696 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
697 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800698 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800699 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
700 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800701 proto.write(BinaryLogEntry::TAG_INDEX,
702 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800703 do {
704 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800705 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800706 switch (elem.type) {
707 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800708 proto.write(BinaryLogEntry::Elem::TYPE,
709 BinaryLogEntry::Elem::EVENT_TYPE_INT);
710 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800711 break;
712 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800713 proto.write(BinaryLogEntry::Elem::TYPE,
714 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
715 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800716 break;
717 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800718 proto.write(BinaryLogEntry::Elem::TYPE,
719 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800720 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
721 break;
722 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800723 proto.write(BinaryLogEntry::Elem::TYPE,
724 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800725 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
726 break;
727 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800728 proto.write(BinaryLogEntry::Elem::TYPE,
729 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800730 break;
731 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800732 proto.write(BinaryLogEntry::Elem::TYPE,
733 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800734 break;
735 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800736 proto.write(BinaryLogEntry::Elem::TYPE,
737 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800738 break;
739 }
740 proto.end(elemToken);
741 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
742 proto.end(token);
743 if (context) {
744 android_log_destroy(&context);
745 }
746 } else {
747 AndroidLogEntry entry;
748 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
749 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700750 ALOGW("[%s] fails to process to an entry.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800751 break;
752 }
753 lastTimestamp.tv_sec = entry.tv_sec;
754 lastTimestamp.tv_nsec = entry.tv_nsec;
755
756 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800757 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800758 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
759 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
760 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
761 proto.write(TextLogEntry::UID, entry.uid);
762 proto.write(TextLogEntry::PID, entry.pid);
763 proto.write(TextLogEntry::TID, entry.tid);
764 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800765 proto.write(TextLogEntry::LOG, entry.message,
766 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800767 proto.end(token);
768 }
769 }
770 gLastLogsRetrieved[mLogID] = lastTimestamp;
771 proto.flush(pipeWriteFd);
Yi Jin83fb1d52018-03-16 12:03:53 -0700772 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800773}
Kweku Adamseadd1232018-02-05 16:45:13 -0800774
775// ================================================================================
776
777TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
778 : WorkerThreadSection(id, timeoutMs), mType(type) {
Yi Jin3be0b432018-04-20 17:08:11 -0700779 name = "tombstone ";
Kweku Adamseadd1232018-02-05 16:45:13 -0800780 name += type;
781}
782
783TombstoneSection::~TombstoneSection() {}
784
785status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
786 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
787 if (proc.get() == nullptr) {
788 ALOGE("opendir /proc failed: %s\n", strerror(errno));
789 return -errno;
790 }
791
792 const std::set<int> hal_pids = get_interesting_hal_pids();
793
794 ProtoOutputStream proto;
795 struct dirent* d;
796 status_t err = NO_ERROR;
797 while ((d = readdir(proc.get()))) {
798 int pid = atoi(d->d_name);
799 if (pid <= 0) {
800 continue;
801 }
802
803 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
804 std::string exe;
805 if (!android::base::Readlink(link_name, &exe)) {
806 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
807 continue;
808 }
809
810 bool is_java_process;
811 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
812 if (mType != "java") continue;
813 // Don't bother dumping backtraces for the zygote.
814 if (IsZygote(pid)) {
815 VLOG("Skipping Zygote");
816 continue;
817 }
818
819 is_java_process = true;
820 } else if (should_dump_native_traces(exe.c_str())) {
821 if (mType != "native") continue;
822 is_java_process = false;
823 } else if (hal_pids.find(pid) != hal_pids.end()) {
824 if (mType != "hal") continue;
825 is_java_process = false;
826 } else {
827 // Probably a native process we don't care about, continue.
828 VLOG("Skipping %d", pid);
829 continue;
830 }
831
832 Fpipe dumpPipe;
833 if (!dumpPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700834 ALOGW("[%s] failed to setup dump pipe", this->name.string());
Kweku Adamseadd1232018-02-05 16:45:13 -0800835 err = -errno;
836 break;
837 }
838
839 const uint64_t start = Nanotime();
840 pid_t child = fork();
841 if (child < 0) {
842 ALOGE("Failed to fork child process");
843 break;
844 } else if (child == 0) {
845 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700846 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800847 const int ret = dump_backtrace_to_file_timeout(
848 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700849 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800850 if (ret == -1) {
851 if (errno == 0) {
852 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
853 } else {
854 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
855 }
856 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700857 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800858 _exit(EXIT_SUCCESS);
859 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700860 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800861 // Parent process.
862 // Read from the pipe concurrently to avoid blocking the child.
863 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700864 err = buffer.readFully(dumpPipe.readFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800865 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700866 ALOGW("[%s] failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700867 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800868 break;
869 }
870
871 auto dump = std::make_unique<char[]>(buffer.size());
872 auto iterator = buffer.data();
873 int i = 0;
874 while (iterator.hasNext()) {
875 dump[i] = iterator.next();
876 i++;
877 }
Yi Jin6cacbcb2018-03-30 14:04:52 -0700878 uint64_t token = proto.start(android::os::BackTraceProto::TRACES);
Kweku Adamseadd1232018-02-05 16:45:13 -0800879 proto.write(android::os::BackTraceProto::Stack::PID, pid);
880 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
881 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
882 static_cast<long long>(Nanotime() - start));
883 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700884 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800885 }
886
887 proto.flush(pipeWriteFd);
888 return err;
889}
Yi Jin6cacbcb2018-03-30 14:04:52 -0700890
891} // namespace incidentd
892} // namespace os
Yi Jin98ce8102018-04-12 11:15:39 -0700893} // namespace android