blob: 32ec1ba90cdaf593e070cc7797463e4ab8043a6d [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());
Mike Ma28381692018-12-04 15:46:29 -080078 stats->set_success(!buffer.timedOut() && !buffer.truncated());
Yi Jin98ce8102018-04-12 11:15:39 -070079}
80
Kweku Adamseadd1232018-02-05 16:45:13 -080081// Reads data from FdBuffer and writes it to the requests file descriptor.
Yi Jinb592e3b2018-02-01 15:17:04 -080082static status_t write_report_requests(const int id, const FdBuffer& buffer,
83 ReportRequestSet* requests) {
Yi Jin0f047162017-09-05 13:44:22 -070084 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -070085 EncodedBuffer::iterator data = buffer.data();
86 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Mike Ma28381692018-12-04 15:46:29 -080087 IncidentMetadata::SectionStats* stats = requests->sectionStats(id);
88 int nPassed = 0;
Yi Jin99c248f2017-08-25 18:11:58 -070089
Yi Jin0f047162017-09-05 13:44:22 -070090 // The streaming ones, group requests by spec in order to save unnecessary strip operations
91 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -080092 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -070093 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -070094 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -070095 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -070096 }
Yi Jin3ec5cc72018-01-26 13:42:43 -080097 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -070098 requestsBySpec[spec].push_back(request);
99 }
100
Yi Jin3ec5cc72018-01-26 13:42:43 -0800101 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -0700102 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700103 err = privacyBuffer.strip(spec);
Mike Ma28381692018-12-04 15:46:29 -0800104 if (err != NO_ERROR) {
105 // Privacy Buffer is corrupted, probably due to an ill-formatted proto. This is a
106 // non-fatal error. The whole report is still valid. So just log the failure.
107 ALOGW("Failed to strip section %d with spec %d: %s",
108 id, spec.dest, strerror(-err));
109 stats->set_success(false);
110 stats->set_error_msg("Failed to strip section: privacy buffer corrupted, probably "
111 "due to an ill-formatted proto");
112 nPassed++;
113 continue;
114 }
115
Yi Jinc23fad22017-09-15 17:24:59 -0700116 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700117
Yi Jin3ec5cc72018-01-26 13:42:43 -0800118 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700119 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700120 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800121 if (err != NO_ERROR) {
122 request->err = err;
123 continue;
124 }
Yi Jinc23fad22017-09-15 17:24:59 -0700125 err = privacyBuffer.flush(request->fd);
Yi Jinb592e3b2018-02-01 15:17:04 -0800126 if (err != NO_ERROR) {
127 request->err = err;
128 continue;
129 }
Mike Ma28381692018-12-04 15:46:29 -0800130 nPassed++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800131 VLOG("Section %d flushed %zu bytes to fd %d with spec %d", id, privacyBuffer.size(),
132 request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700133 }
Yi Jinc23fad22017-09-15 17:24:59 -0700134 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700135 }
136
137 // The dropbox file
138 if (requests->mainFd() >= 0) {
Yi Jin329130b2018-02-09 16:47:47 -0800139 PrivacySpec spec = PrivacySpec::new_spec(requests->mainDest());
Yi Jin3ec5cc72018-01-26 13:42:43 -0800140 err = privacyBuffer.strip(spec);
Mike Ma28381692018-12-04 15:46:29 -0800141 if (err != NO_ERROR) {
142 ALOGW("Failed to strip section %d with spec %d for dropbox: %s",
143 id, spec.dest, strerror(-err));
144 stats->set_success(false);
145 stats->set_error_msg("Failed to strip section: privacy buffer corrupted, probably "
146 "due to an ill-formatted proto");
147 nPassed++;
148 goto DONE;
149 }
Yi Jinc23fad22017-09-15 17:24:59 -0700150 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700151
Yi Jinc23fad22017-09-15 17:24:59 -0700152 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800153 if (err != NO_ERROR) {
154 requests->setMainFd(-1);
155 goto DONE;
156 }
Yi Jinc23fad22017-09-15 17:24:59 -0700157 err = privacyBuffer.flush(requests->mainFd());
Yi Jinb592e3b2018-02-01 15:17:04 -0800158 if (err != NO_ERROR) {
159 requests->setMainFd(-1);
160 goto DONE;
161 }
Mike Ma28381692018-12-04 15:46:29 -0800162 nPassed++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800163 VLOG("Section %d flushed %zu bytes to dropbox %d with spec %d", id, privacyBuffer.size(),
164 requests->mainFd(), spec.dest);
Yi Jin98ce8102018-04-12 11:15:39 -0700165 // Reports bytes of the section uploaded via dropbox after filtering.
166 requests->sectionStats(id)->set_report_size_bytes(privacyBuffer.size());
Yi Jin99c248f2017-08-25 18:11:58 -0700167 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700168
169DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700170 // only returns error if there is no fd to write to.
Mike Ma28381692018-12-04 15:46:29 -0800171 return nPassed > 0 ? NO_ERROR : err;
Yi Jin99c248f2017-08-25 18:11:58 -0700172}
173
174// ================================================================================
Kweku Adamse04ef772018-06-13 12:24:38 -0700175Section::Section(int i, int64_t timeoutMs, bool userdebugAndEngOnly)
Kweku Adams3d160912018-05-07 11:26:27 -0700176 : id(i),
177 timeoutMs(timeoutMs),
Kweku Adamse04ef772018-06-13 12:24:38 -0700178 userdebugAndEngOnly(userdebugAndEngOnly) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800179
Yi Jinb592e3b2018-02-01 15:17:04 -0800180Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800181
Joe Onorato1754d742016-11-21 17:51:35 -0800182// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800183HeaderSection::HeaderSection() : Section(FIELD_ID_INCIDENT_HEADER, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700184
Yi Jinb592e3b2018-02-01 15:17:04 -0800185HeaderSection::~HeaderSection() {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700186
Yi Jinb592e3b2018-02-01 15:17:04 -0800187status_t HeaderSection::Execute(ReportRequestSet* requests) const {
188 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700189 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800190 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700191
Yi Jinb592e3b2018-02-01 15:17:04 -0800192 for (vector<vector<uint8_t>>::const_iterator buf = headers.begin(); buf != headers.end();
193 buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700194 if (buf->empty()) continue;
195
196 // So the idea is only requests with negative fd are written to dropbox file.
197 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800198 write_section_header(fd, id, buf->size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800199 WriteFully(fd, (uint8_t const*)buf->data(), buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700200 // If there was an error now, there will be an error later and we will remove
201 // it from the list then.
202 }
203 }
204 return NO_ERROR;
205}
Yi Jin329130b2018-02-09 16:47:47 -0800206// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800207MetadataSection::MetadataSection() : Section(FIELD_ID_INCIDENT_METADATA, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700208
Yi Jinb592e3b2018-02-01 15:17:04 -0800209MetadataSection::~MetadataSection() {}
Yi Jin329130b2018-02-09 16:47:47 -0800210
Yi Jinb592e3b2018-02-01 15:17:04 -0800211status_t MetadataSection::Execute(ReportRequestSet* requests) const {
Yi Jin86dce412018-03-07 11:36:57 -0800212 ProtoOutputStream proto;
213 IncidentMetadata metadata = requests->metadata();
214 proto.write(FIELD_TYPE_ENUM | IncidentMetadata::kDestFieldNumber, metadata.dest());
215 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::kRequestSizeFieldNumber,
216 metadata.request_size());
217 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::kUseDropboxFieldNumber, metadata.use_dropbox());
218 for (auto iter = requests->allSectionStats().begin(); iter != requests->allSectionStats().end();
219 iter++) {
220 IncidentMetadata::SectionStats stats = iter->second;
221 uint64_t token = proto.start(FIELD_TYPE_MESSAGE | IncidentMetadata::kSectionsFieldNumber);
222 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kIdFieldNumber, stats.id());
223 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kSuccessFieldNumber,
224 stats.success());
225 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kReportSizeBytesFieldNumber,
226 stats.report_size_bytes());
227 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kExecDurationMsFieldNumber,
228 stats.exec_duration_ms());
229 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kDumpSizeBytesFieldNumber,
230 stats.dump_size_bytes());
231 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kDumpDurationMsFieldNumber,
232 stats.dump_duration_ms());
233 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kTimedOutFieldNumber,
234 stats.timed_out());
235 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kIsTruncatedFieldNumber,
236 stats.is_truncated());
Mike Ma28381692018-12-04 15:46:29 -0800237 proto.write(FIELD_TYPE_STRING | IncidentMetadata::SectionStats::kErrorMsgFieldNumber,
238 stats.error_msg());
Yi Jin86dce412018-03-07 11:36:57 -0800239 proto.end(token);
240 }
241
Yi Jinb592e3b2018-02-01 15:17:04 -0800242 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jin329130b2018-02-09 16:47:47 -0800243 const sp<ReportRequest> request = *it;
Yi Jin86dce412018-03-07 11:36:57 -0800244 if (request->fd < 0 || request->err != NO_ERROR) {
Yi Jin329130b2018-02-09 16:47:47 -0800245 continue;
246 }
Yi Jin86dce412018-03-07 11:36:57 -0800247 write_section_header(request->fd, id, proto.size());
248 if (!proto.flush(request->fd)) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800249 ALOGW("Failed to write metadata to fd %d", request->fd);
250 // we don't fail if we can't write to a single request's fd.
251 }
Yi Jin329130b2018-02-09 16:47:47 -0800252 }
Yi Jin86dce412018-03-07 11:36:57 -0800253 if (requests->mainFd() >= 0) {
254 write_section_header(requests->mainFd(), id, proto.size());
255 if (!proto.flush(requests->mainFd())) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800256 ALOGW("Failed to write metadata to dropbox fd %d", requests->mainFd());
257 return -1;
258 }
Yi Jin329130b2018-02-09 16:47:47 -0800259 }
260 return NO_ERROR;
261}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700262// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -0800263static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
264
Kweku Adamse04ef772018-06-13 12:24:38 -0700265FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
266 : Section(id, timeoutMs, false), mFilename(filename) {
Yi Jin3be0b432018-04-20 17:08:11 -0700267 name = "file ";
268 name += filename;
Yi Jin1a11fa12018-02-22 16:44:10 -0800269 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -0700270}
271
272FileSection::~FileSection() {}
273
Yi Jinb592e3b2018-02-01 15:17:04 -0800274status_t FileSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700275 // read from mFilename first, make sure the file is available
276 // add O_CLOEXEC to make sure it is closed when exec incident helper
Yi Jin6355d2f2018-03-14 15:18:02 -0700277 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
278 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700279 ALOGW("[%s] failed to open file", this->name.string());
Kweku Adamse04ef772018-06-13 12:24:38 -0700280 // There may be some devices/architectures that won't have the file.
281 // Just return here without an error.
282 return NO_ERROR;
Yi Jin0a3406f2017-06-22 19:23:11 -0700283 }
284
Yi Jinb44f7d42017-07-21 12:12:59 -0700285 FdBuffer buffer;
286 Fpipe p2cPipe;
287 Fpipe c2pPipe;
288 // initiate pipes to pass data to/from incident_helper
289 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700290 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700291 return -errno;
292 }
293
Yi Jin1a11fa12018-02-22 16:44:10 -0800294 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700295 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700296 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700297 return -errno;
298 }
299
300 // parent process
Yi Jine3dab2d2018-03-22 16:56:39 -0700301 status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
302 std::move(c2pPipe.readFd()),
303 this->timeoutMs, mIsSysfs);
Yi Jin98ce8102018-04-12 11:15:39 -0700304 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700305 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700306 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800307 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800308 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700309 return readStatus;
310 }
311
Yi Jinedfd5bb2017-09-06 17:09:11 -0700312 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700313 if (ihStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700314 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700315 return ihStatus;
316 }
317
Yi Jin3be0b432018-04-20 17:08:11 -0700318 return write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700319}
Yi Jin1a11fa12018-02-22 16:44:10 -0800320// ================================================================================
321GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800322 va_list args;
323 va_start(args, filename);
324 mFilenames = varargs(filename, args);
325 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800326 name = "gzip";
327 for (int i = 0; mFilenames[i] != NULL; i++) {
328 name += " ";
329 name += mFilenames[i];
330 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800331}
Yi Jin0a3406f2017-06-22 19:23:11 -0700332
Yi Jin480de782018-04-06 15:37:36 -0700333GZipSection::~GZipSection() { free(mFilenames); }
Yi Jin1a11fa12018-02-22 16:44:10 -0800334
335status_t GZipSection::Execute(ReportRequestSet* requests) const {
336 // Reads the files in order, use the first available one.
337 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700338 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800339 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700340 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
341 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800342 break;
343 }
344 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
345 index++; // look at the next file.
346 }
Yi Jinc858e272018-03-28 15:32:50 -0700347 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700348 ALOGW("[%s] can't open all the files", this->name.string());
Yi Jin6cacbcb2018-03-30 14:04:52 -0700349 return NO_ERROR; // e.g. LAST_KMSG will reach here in user build.
Yi Jinc858e272018-03-28 15:32:50 -0700350 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800351 FdBuffer buffer;
352 Fpipe p2cPipe;
353 Fpipe c2pPipe;
354 // initiate pipes to pass data to/from gzip
355 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700356 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800357 return -errno;
358 }
359
Yi Jinc36e91d2018-03-08 11:25:58 -0800360 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800361 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700362 ALOGW("[%s] failed to fork", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800363 return -errno;
364 }
365 // parent process
366
367 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
368 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
369 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
370 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700371 size_t fileLen = strlen(mFilenames[index]);
372 internalBuffer->writeRawVarint32(fileLen);
373 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800374 internalBuffer->writeRawByte(mFilenames[index][i]);
375 }
376 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
377 WIRE_TYPE_LENGTH_DELIMITED);
378 size_t editPos = internalBuffer->wp()->pos();
379 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
380 size_t dataBeginAt = internalBuffer->wp()->pos();
Yi Jin3be0b432018-04-20 17:08:11 -0700381 VLOG("[%s] editPos=%zu, dataBeginAt=%zu", this->name.string(), editPos, dataBeginAt);
Yi Jin1a11fa12018-02-22 16:44:10 -0800382
Yi Jine3dab2d2018-03-22 16:56:39 -0700383 status_t readStatus = buffer.readProcessedDataInStream(
384 fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
385 isSysfs(mFilenames[index]));
Yi Jin98ce8102018-04-12 11:15:39 -0700386 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jin1a11fa12018-02-22 16:44:10 -0800387 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700388 ALOGW("[%s] failed to read data from gzip: %s, timedout: %s", this->name.string(),
389 strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin1a11fa12018-02-22 16:44:10 -0800390 kill_child(pid);
391 return readStatus;
392 }
393
394 status_t gzipStatus = wait_child(pid);
395 if (gzipStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700396 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-gzipStatus));
Yi Jin1a11fa12018-02-22 16:44:10 -0800397 return gzipStatus;
398 }
399 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
400 size_t dataSize = buffer.size() - dataBeginAt;
401 internalBuffer->wp()->rewind()->move(editPos);
402 internalBuffer->writeRawVarint32(dataSize);
403 internalBuffer->copy(dataBeginAt, dataSize);
Yi Jin1a11fa12018-02-22 16:44:10 -0800404
Yi Jin3be0b432018-04-20 17:08:11 -0700405 return write_report_requests(this->id, buffer, requests);
Yi Jin1a11fa12018-02-22 16:44:10 -0800406}
Kweku Adamseadd1232018-02-05 16:45:13 -0800407
Yi Jin0a3406f2017-06-22 19:23:11 -0700408// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800409struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800410 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700411 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800412
413 // Lock protects these fields
414 mutex lock;
415 bool workerDone;
416 status_t workerError;
417
Chih-Hung Hsieh7a88a932018-12-20 13:45:04 -0800418 explicit WorkerThreadData(const WorkerThreadSection* section);
Joe Onorato1754d742016-11-21 17:51:35 -0800419 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800420};
421
422WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700423 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800424
Yi Jinb592e3b2018-02-01 15:17:04 -0800425WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800426
427// ================================================================================
Kweku Adams3d160912018-05-07 11:26:27 -0700428WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs, bool userdebugAndEngOnly)
429 : Section(id, timeoutMs, userdebugAndEngOnly) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800430
Yi Jinb592e3b2018-02-01 15:17:04 -0800431WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800432
Kweku Adams5b763c12018-09-13 15:44:58 -0700433void sigpipe_handler(int signum) {
434 if (signum == SIGPIPE) {
435 ALOGE("Wrote to a broken pipe\n");
436 } else {
437 ALOGE("Received unexpected signal: %d\n", signum);
438 }
439}
440
Yi Jinb592e3b2018-02-01 15:17:04 -0800441static void* worker_thread_func(void* cookie) {
Kweku Adams5b763c12018-09-13 15:44:58 -0700442 // Don't crash the service if we write to a closed pipe (which can happen if
443 // dumping times out).
444 signal(SIGPIPE, sigpipe_handler);
445
Joe Onorato1754d742016-11-21 17:51:35 -0800446 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700447 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800448
449 {
450 unique_lock<mutex> lock(data->lock);
451 data->workerDone = true;
452 data->workerError = err;
453 }
454
Yi Jin6355d2f2018-03-14 15:18:02 -0700455 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800456 data->decStrong(data->section);
457 // data might be gone now. don't use it after this point in this thread.
458 return NULL;
459}
460
Yi Jinb592e3b2018-02-01 15:17:04 -0800461status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800462 status_t err = NO_ERROR;
463 pthread_t thread;
464 pthread_attr_t attr;
Mike Ma28381692018-12-04 15:46:29 -0800465 bool workerDone = false;
Joe Onorato1754d742016-11-21 17:51:35 -0800466 FdBuffer buffer;
Mike Ma28381692018-12-04 15:46:29 -0800467 IncidentMetadata::SectionStats* stats = requests->sectionStats(this->id);
Joe Onorato1754d742016-11-21 17:51:35 -0800468
469 // Data shared between this thread and the worker thread.
470 sp<WorkerThreadData> data = new WorkerThreadData(this);
471
472 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700473 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800474 return -errno;
475 }
476
477 // The worker thread needs a reference and we can't let the count go to zero
478 // if that thread is slow to start.
479 data->incStrong(this);
480
481 // Create the thread
482 err = pthread_attr_init(&attr);
483 if (err != 0) {
484 return -err;
485 }
486 // TODO: Do we need to tweak thread priority?
487 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
488 if (err != 0) {
489 pthread_attr_destroy(&attr);
490 return -err;
491 }
492 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
493 if (err != 0) {
494 pthread_attr_destroy(&attr);
495 return -err;
496 }
497 pthread_attr_destroy(&attr);
498
499 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jine3dab2d2018-03-22 16:56:39 -0700500 err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800501 if (err != NO_ERROR) {
Mike Ma28381692018-12-04 15:46:29 -0800502 ALOGE("[%s] reader failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800503 }
504
505 // Done with the read fd. The worker thread closes the write one so
506 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700507 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800508
509 // If the worker side is finished, then return its error (which may overwrite
Mike Ma28381692018-12-04 15:46:29 -0800510 // our possible error -- but it's more interesting anyway). If not, then we timed out.
Joe Onorato1754d742016-11-21 17:51:35 -0800511 {
512 unique_lock<mutex> lock(data->lock);
Mike Ma28381692018-12-04 15:46:29 -0800513 if (data->workerError != NO_ERROR) {
514 err = data->workerError;
515 ALOGE("[%s] worker failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800516 }
Mike Ma28381692018-12-04 15:46:29 -0800517 workerDone = data->workerDone;
Joe Onorato1754d742016-11-21 17:51:35 -0800518 }
Kweku Adams5b763c12018-09-13 15:44:58 -0700519
Mike Ma28381692018-12-04 15:46:29 -0800520 write_section_stats(stats, buffer);
521 if (err != NO_ERROR) {
522 char errMsg[128];
523 snprintf(errMsg, 128, "[%s] failed with error '%s'",
524 this->name.string(), strerror(-err));
525 stats->set_success(false);
526 stats->set_error_msg(errMsg);
Joe Onorato1754d742016-11-21 17:51:35 -0800527 return NO_ERROR;
528 }
Mike Ma28381692018-12-04 15:46:29 -0800529 if (buffer.truncated()) {
530 ALOGW("[%s] too large, truncating", this->name.string());
531 // Do not write a truncated section. It won't pass through the PrivacyBuffer.
532 return NO_ERROR;
533 }
534 if (!workerDone || buffer.timedOut()) {
535 ALOGW("[%s] timed out", this->name.string());
Joe Onorato1754d742016-11-21 17:51:35 -0800536 return NO_ERROR;
537 }
538
539 // Write the data that was collected
Yi Jin3be0b432018-04-20 17:08:11 -0700540 return write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800541}
542
543// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700544CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800545 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800546 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700547 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800548 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800549 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800550 name = "cmd";
551 for (int i = 0; mCommand[i] != NULL; i++) {
552 name += " ";
553 name += mCommand[i];
554 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700555}
Joe Onorato1754d742016-11-21 17:51:35 -0800556
Yi Jinb592e3b2018-02-01 15:17:04 -0800557CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700558 va_list args;
559 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800560 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800561 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800562 name = "cmd";
563 for (int i = 0; mCommand[i] != NULL; i++) {
564 name += " ";
565 name += mCommand[i];
566 }
Joe Onorato1754d742016-11-21 17:51:35 -0800567}
568
Yi Jinb592e3b2018-02-01 15:17:04 -0800569CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800570
Yi Jinb592e3b2018-02-01 15:17:04 -0800571status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700572 FdBuffer buffer;
573 Fpipe cmdPipe;
574 Fpipe ihPipe;
575
576 if (!cmdPipe.init() || !ihPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700577 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700578 return -errno;
579 }
580
Yi Jinc36e91d2018-03-08 11:25:58 -0800581 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700582 if (cmdPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700583 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700584 return -errno;
585 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800586 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700587 if (ihPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700588 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700589 return -errno;
590 }
591
Yi Jin6355d2f2018-03-14 15:18:02 -0700592 cmdPipe.writeFd().reset();
Yi Jine3dab2d2018-03-22 16:56:39 -0700593 status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
Yi Jin98ce8102018-04-12 11:15:39 -0700594 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700595 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700596 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800597 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800598 kill_child(cmdPid);
599 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700600 return readStatus;
601 }
602
Kweku Adamseadd1232018-02-05 16:45:13 -0800603 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800604 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700605 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800606 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700607 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700608 ALOGW("[%s] abnormal child processes, return status: command: %s, incident "
Yi Jinb592e3b2018-02-01 15:17:04 -0800609 "helper: %s",
610 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700611 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
612 }
613
Yi Jin3be0b432018-04-20 17:08:11 -0700614 return write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800615}
616
617// ================================================================================
Kweku Adams3d160912018-05-07 11:26:27 -0700618DumpsysSection::DumpsysSection(int id, bool userdebugAndEngOnly, const char* service, ...)
619 : WorkerThreadSection(id, REMOTE_CALL_TIMEOUT_MS, userdebugAndEngOnly), 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) {
Joe Onorato1754d742016-11-21 17:51:35 -0800644 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
Mike Ma28381692018-12-04 15:46:29 -0800645 return NAME_NOT_FOUND;
Joe Onorato1754d742016-11-21 17:51:35 -0800646 }
647
648 service->dump(pipeWriteFd, mArgs);
649
650 return NO_ERROR;
651}
Yi Jin3c034c92017-12-22 17:36:47 -0800652
653// ================================================================================
654// initialization only once in Section.cpp.
655map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
656
Yi Jinb592e3b2018-02-01 15:17:04 -0800657LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3be0b432018-04-20 17:08:11 -0700658 name = "logcat ";
Yi Jin3c034c92017-12-22 17:36:47 -0800659 name += android_log_id_to_name(logID);
660 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800661 case LOG_ID_EVENTS:
662 case LOG_ID_STATS:
663 case LOG_ID_SECURITY:
664 mBinary = true;
665 break;
666 default:
667 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800668 }
669}
670
Yi Jinb592e3b2018-02-01 15:17:04 -0800671LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800672
Yi Jinb592e3b2018-02-01 15:17:04 -0800673static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800674 while (len > 0) {
675 char c = buf[len - 1];
676 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
677 len--;
678 } else {
679 break;
680 }
681 }
682 return len;
683}
684
685static inline int32_t get4LE(uint8_t const* src) {
686 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
687}
688
Yi Jinb592e3b2018-02-01 15:17:04 -0800689status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800690 // Open log buffer and getting logs since last retrieved time if any.
691 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800692 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
693 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
694 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
695 gLastLogsRetrieved[mLogID], 0),
696 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800697
698 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin3be0b432018-04-20 17:08:11 -0700699 ALOGE("[%s] Can't get logger.", this->name.string());
Yi Jin83fb1d52018-03-16 12:03:53 -0700700 return -1;
Yi Jin3c034c92017-12-22 17:36:47 -0800701 }
702
703 log_msg msg;
704 log_time lastTimestamp(0);
705
706 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800707 while (true) { // keeps reading until logd buffer is fully read.
Yi Jin83fb1d52018-03-16 12:03:53 -0700708 status_t err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800709 // err = 0 - no content, unexpected connection drop or EOF.
710 // err = +ive number - size of retrieved data from logger
711 // err = -ive number, OS supplied error _except_ for -EAGAIN
712 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
713 if (err <= 0) {
714 if (err != -EAGAIN) {
Yi Jin3be0b432018-04-20 17:08:11 -0700715 ALOGW("[%s] fails to read a log_msg.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800716 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700717 // dump previous logs and don't consider this error a failure.
Yi Jin3c034c92017-12-22 17:36:47 -0800718 break;
719 }
720 if (mBinary) {
721 // remove the first uint32 which is tag's index in event log tags
722 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800723 msg.len() - sizeof(uint32_t));
724 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800725 android_log_list_element elem;
726
727 lastTimestamp.tv_sec = msg.entry_v1.sec;
728 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
729
730 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800731 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800732 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
733 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800734 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800735 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
736 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800737 proto.write(BinaryLogEntry::TAG_INDEX,
738 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800739 do {
740 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800741 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800742 switch (elem.type) {
743 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800744 proto.write(BinaryLogEntry::Elem::TYPE,
745 BinaryLogEntry::Elem::EVENT_TYPE_INT);
746 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800747 break;
748 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800749 proto.write(BinaryLogEntry::Elem::TYPE,
750 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
751 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800752 break;
753 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800754 proto.write(BinaryLogEntry::Elem::TYPE,
755 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800756 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
757 break;
758 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800759 proto.write(BinaryLogEntry::Elem::TYPE,
760 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800761 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
762 break;
763 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800764 proto.write(BinaryLogEntry::Elem::TYPE,
765 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800766 break;
767 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800768 proto.write(BinaryLogEntry::Elem::TYPE,
769 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800770 break;
771 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800772 proto.write(BinaryLogEntry::Elem::TYPE,
773 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800774 break;
775 }
776 proto.end(elemToken);
777 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
778 proto.end(token);
779 if (context) {
780 android_log_destroy(&context);
781 }
782 } else {
783 AndroidLogEntry entry;
784 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
785 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700786 ALOGW("[%s] fails to process to an entry.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800787 break;
788 }
789 lastTimestamp.tv_sec = entry.tv_sec;
790 lastTimestamp.tv_nsec = entry.tv_nsec;
791
792 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800793 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800794 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
795 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
796 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
797 proto.write(TextLogEntry::UID, entry.uid);
798 proto.write(TextLogEntry::PID, entry.pid);
799 proto.write(TextLogEntry::TID, entry.tid);
800 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800801 proto.write(TextLogEntry::LOG, entry.message,
802 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800803 proto.end(token);
804 }
805 }
806 gLastLogsRetrieved[mLogID] = lastTimestamp;
Kweku Adams5b763c12018-09-13 15:44:58 -0700807 if (!proto.flush(pipeWriteFd) && errno == EPIPE) {
808 ALOGE("[%s] wrote to a broken pipe\n", this->name.string());
809 return EPIPE;
810 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700811 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800812}
Kweku Adamseadd1232018-02-05 16:45:13 -0800813
814// ================================================================================
815
816TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
817 : WorkerThreadSection(id, timeoutMs), mType(type) {
Yi Jin3be0b432018-04-20 17:08:11 -0700818 name = "tombstone ";
Kweku Adamseadd1232018-02-05 16:45:13 -0800819 name += type;
820}
821
822TombstoneSection::~TombstoneSection() {}
823
824status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
825 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
826 if (proc.get() == nullptr) {
827 ALOGE("opendir /proc failed: %s\n", strerror(errno));
828 return -errno;
829 }
830
831 const std::set<int> hal_pids = get_interesting_hal_pids();
832
833 ProtoOutputStream proto;
834 struct dirent* d;
835 status_t err = NO_ERROR;
836 while ((d = readdir(proc.get()))) {
837 int pid = atoi(d->d_name);
838 if (pid <= 0) {
839 continue;
840 }
841
842 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
843 std::string exe;
844 if (!android::base::Readlink(link_name, &exe)) {
845 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
846 continue;
847 }
848
849 bool is_java_process;
850 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
851 if (mType != "java") continue;
852 // Don't bother dumping backtraces for the zygote.
853 if (IsZygote(pid)) {
854 VLOG("Skipping Zygote");
855 continue;
856 }
857
858 is_java_process = true;
859 } else if (should_dump_native_traces(exe.c_str())) {
860 if (mType != "native") continue;
861 is_java_process = false;
862 } else if (hal_pids.find(pid) != hal_pids.end()) {
863 if (mType != "hal") continue;
864 is_java_process = false;
865 } else {
866 // Probably a native process we don't care about, continue.
867 VLOG("Skipping %d", pid);
868 continue;
869 }
870
871 Fpipe dumpPipe;
872 if (!dumpPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700873 ALOGW("[%s] failed to setup dump pipe", this->name.string());
Kweku Adamseadd1232018-02-05 16:45:13 -0800874 err = -errno;
875 break;
876 }
877
878 const uint64_t start = Nanotime();
879 pid_t child = fork();
880 if (child < 0) {
881 ALOGE("Failed to fork child process");
882 break;
883 } else if (child == 0) {
884 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700885 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800886 const int ret = dump_backtrace_to_file_timeout(
887 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700888 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800889 if (ret == -1) {
890 if (errno == 0) {
891 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
892 } else {
893 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
894 }
895 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700896 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800897 _exit(EXIT_SUCCESS);
898 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700899 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800900 // Parent process.
901 // Read from the pipe concurrently to avoid blocking the child.
902 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700903 err = buffer.readFully(dumpPipe.readFd().get());
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700904 // Wait on the child to avoid it becoming a zombie process.
905 status_t cStatus = wait_child(child);
Kweku Adamseadd1232018-02-05 16:45:13 -0800906 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700907 ALOGW("[%s] failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700908 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800909 break;
910 }
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700911 if (cStatus != NO_ERROR) {
Kweku Adams5b763c12018-09-13 15:44:58 -0700912 ALOGE("[%s] child had an issue: %s\n", this->name.string(), strerror(-cStatus));
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700913 }
Kweku Adamseadd1232018-02-05 16:45:13 -0800914
915 auto dump = std::make_unique<char[]>(buffer.size());
916 auto iterator = buffer.data();
917 int i = 0;
918 while (iterator.hasNext()) {
919 dump[i] = iterator.next();
920 i++;
921 }
Yi Jin6cacbcb2018-03-30 14:04:52 -0700922 uint64_t token = proto.start(android::os::BackTraceProto::TRACES);
Kweku Adamseadd1232018-02-05 16:45:13 -0800923 proto.write(android::os::BackTraceProto::Stack::PID, pid);
924 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
925 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
926 static_cast<long long>(Nanotime() - start));
927 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700928 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800929 }
930
Kweku Adams5b763c12018-09-13 15:44:58 -0700931 if (!proto.flush(pipeWriteFd) && errno == EPIPE) {
932 ALOGE("[%s] wrote to a broken pipe\n", this->name.string());
933 if (err != NO_ERROR) {
934 return EPIPE;
935 }
936 }
937
Kweku Adamseadd1232018-02-05 16:45:13 -0800938 return err;
939}
Yi Jin6cacbcb2018-03-30 14:04:52 -0700940
941} // namespace incidentd
942} // namespace os
Yi Jin98ce8102018-04-12 11:15:39 -0700943} // namespace android