blob: 45d628100bce69450b34d607582b589810c5269c [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
Kweku Adamseadd1232018-02-05 16:45:13 -080073// Reads data from FdBuffer and writes it to the requests file descriptor.
Yi Jinb592e3b2018-02-01 15:17:04 -080074static status_t write_report_requests(const int id, const FdBuffer& buffer,
75 ReportRequestSet* requests) {
Yi Jin0f047162017-09-05 13:44:22 -070076 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -070077 EncodedBuffer::iterator data = buffer.data();
78 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -070079 int writeable = 0;
Yi Jin86dce412018-03-07 11:36:57 -080080 IncidentMetadata::SectionStats* stats = requests->sectionStats(id);
Yi Jin329130b2018-02-09 16:47:47 -080081
82 stats->set_dump_size_bytes(data.size());
83 stats->set_dump_duration_ms(buffer.durationMs());
84 stats->set_timed_out(buffer.timedOut());
85 stats->set_is_truncated(buffer.truncated());
Yi Jin99c248f2017-08-25 18:11:58 -070086
Yi Jin0f047162017-09-05 13:44:22 -070087 // The streaming ones, group requests by spec in order to save unnecessary strip operations
88 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -080089 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -070090 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -070091 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -070092 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -070093 }
Yi Jin3ec5cc72018-01-26 13:42:43 -080094 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -070095 requestsBySpec[spec].push_back(request);
96 }
97
Yi Jin3ec5cc72018-01-26 13:42:43 -080098 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -070099 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700100 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800101 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700102 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700103
Yi Jin3ec5cc72018-01-26 13:42:43 -0800104 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700105 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700106 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800107 if (err != NO_ERROR) {
108 request->err = err;
109 continue;
110 }
Yi Jinc23fad22017-09-15 17:24:59 -0700111 err = privacyBuffer.flush(request->fd);
Yi Jinb592e3b2018-02-01 15:17:04 -0800112 if (err != NO_ERROR) {
113 request->err = err;
114 continue;
115 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700116 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800117 VLOG("Section %d flushed %zu bytes to fd %d with spec %d", id, privacyBuffer.size(),
118 request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700119 }
Yi Jinc23fad22017-09-15 17:24:59 -0700120 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700121 }
122
123 // The dropbox file
124 if (requests->mainFd() >= 0) {
Yi Jin329130b2018-02-09 16:47:47 -0800125 PrivacySpec spec = PrivacySpec::new_spec(requests->mainDest());
Yi Jin3ec5cc72018-01-26 13:42:43 -0800126 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800127 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700128 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700129
Yi Jinc23fad22017-09-15 17:24:59 -0700130 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800131 if (err != NO_ERROR) {
132 requests->setMainFd(-1);
133 goto DONE;
134 }
Yi Jinc23fad22017-09-15 17:24:59 -0700135 err = privacyBuffer.flush(requests->mainFd());
Yi Jinb592e3b2018-02-01 15:17:04 -0800136 if (err != NO_ERROR) {
137 requests->setMainFd(-1);
138 goto DONE;
139 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700140 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800141 VLOG("Section %d flushed %zu bytes to dropbox %d with spec %d", id, privacyBuffer.size(),
142 requests->mainFd(), spec.dest);
Yi Jin329130b2018-02-09 16:47:47 -0800143 stats->set_report_size_bytes(privacyBuffer.size());
Yi Jin99c248f2017-08-25 18:11:58 -0700144 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700145
146DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700147 // only returns error if there is no fd to write to.
148 return writeable > 0 ? NO_ERROR : err;
149}
150
151// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800152Section::Section(int i, const int64_t timeoutMs) : id(i), timeoutMs(timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800153
Yi Jinb592e3b2018-02-01 15:17:04 -0800154Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800155
Joe Onorato1754d742016-11-21 17:51:35 -0800156// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800157HeaderSection::HeaderSection() : Section(FIELD_ID_INCIDENT_HEADER, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700158
Yi Jinb592e3b2018-02-01 15:17:04 -0800159HeaderSection::~HeaderSection() {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700160
Yi Jinb592e3b2018-02-01 15:17:04 -0800161status_t HeaderSection::Execute(ReportRequestSet* requests) const {
162 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700163 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800164 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700165
Yi Jinb592e3b2018-02-01 15:17:04 -0800166 for (vector<vector<uint8_t>>::const_iterator buf = headers.begin(); buf != headers.end();
167 buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700168 if (buf->empty()) continue;
169
170 // So the idea is only requests with negative fd are written to dropbox file.
171 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800172 write_section_header(fd, id, buf->size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800173 WriteFully(fd, (uint8_t const*)buf->data(), buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700174 // If there was an error now, there will be an error later and we will remove
175 // it from the list then.
176 }
177 }
178 return NO_ERROR;
179}
Yi Jin329130b2018-02-09 16:47:47 -0800180// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800181MetadataSection::MetadataSection() : Section(FIELD_ID_INCIDENT_METADATA, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700182
Yi Jinb592e3b2018-02-01 15:17:04 -0800183MetadataSection::~MetadataSection() {}
Yi Jin329130b2018-02-09 16:47:47 -0800184
Yi Jinb592e3b2018-02-01 15:17:04 -0800185status_t MetadataSection::Execute(ReportRequestSet* requests) const {
Yi Jin86dce412018-03-07 11:36:57 -0800186 ProtoOutputStream proto;
187 IncidentMetadata metadata = requests->metadata();
188 proto.write(FIELD_TYPE_ENUM | IncidentMetadata::kDestFieldNumber, metadata.dest());
189 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::kRequestSizeFieldNumber,
190 metadata.request_size());
191 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::kUseDropboxFieldNumber, metadata.use_dropbox());
192 for (auto iter = requests->allSectionStats().begin(); iter != requests->allSectionStats().end();
193 iter++) {
194 IncidentMetadata::SectionStats stats = iter->second;
195 uint64_t token = proto.start(FIELD_TYPE_MESSAGE | IncidentMetadata::kSectionsFieldNumber);
196 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kIdFieldNumber, stats.id());
197 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kSuccessFieldNumber,
198 stats.success());
199 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kReportSizeBytesFieldNumber,
200 stats.report_size_bytes());
201 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kExecDurationMsFieldNumber,
202 stats.exec_duration_ms());
203 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kDumpSizeBytesFieldNumber,
204 stats.dump_size_bytes());
205 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kDumpDurationMsFieldNumber,
206 stats.dump_duration_ms());
207 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kTimedOutFieldNumber,
208 stats.timed_out());
209 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kIsTruncatedFieldNumber,
210 stats.is_truncated());
211 proto.end(token);
212 }
213
Yi Jinb592e3b2018-02-01 15:17:04 -0800214 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jin329130b2018-02-09 16:47:47 -0800215 const sp<ReportRequest> request = *it;
Yi Jin86dce412018-03-07 11:36:57 -0800216 if (request->fd < 0 || request->err != NO_ERROR) {
Yi Jin329130b2018-02-09 16:47:47 -0800217 continue;
218 }
Yi Jin86dce412018-03-07 11:36:57 -0800219 write_section_header(request->fd, id, proto.size());
220 if (!proto.flush(request->fd)) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800221 ALOGW("Failed to write metadata to fd %d", request->fd);
222 // we don't fail if we can't write to a single request's fd.
223 }
Yi Jin329130b2018-02-09 16:47:47 -0800224 }
Yi Jin86dce412018-03-07 11:36:57 -0800225 if (requests->mainFd() >= 0) {
226 write_section_header(requests->mainFd(), id, proto.size());
227 if (!proto.flush(requests->mainFd())) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800228 ALOGW("Failed to write metadata to dropbox fd %d", requests->mainFd());
229 return -1;
230 }
Yi Jin329130b2018-02-09 16:47:47 -0800231 }
232 return NO_ERROR;
233}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700234// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -0800235static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
236
Yi Jinb44f7d42017-07-21 12:12:59 -0700237FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Yi Jinb592e3b2018-02-01 15:17:04 -0800238 : Section(id, timeoutMs), mFilename(filename) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700239 name = filename;
Yi Jin1a11fa12018-02-22 16:44:10 -0800240 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -0700241}
242
243FileSection::~FileSection() {}
244
Yi Jinb592e3b2018-02-01 15:17:04 -0800245status_t FileSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700246 // read from mFilename first, make sure the file is available
247 // add O_CLOEXEC to make sure it is closed when exec incident helper
Yi Jin6355d2f2018-03-14 15:18:02 -0700248 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
249 if (fd.get() == -1) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800250 ALOGW("FileSection '%s' failed to open file", this->name.string());
251 return -errno;
Yi Jin0a3406f2017-06-22 19:23:11 -0700252 }
253
Yi Jinb44f7d42017-07-21 12:12:59 -0700254 FdBuffer buffer;
255 Fpipe p2cPipe;
256 Fpipe c2pPipe;
257 // initiate pipes to pass data to/from incident_helper
258 if (!p2cPipe.init() || !c2pPipe.init()) {
259 ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700260 return -errno;
261 }
262
Yi Jin1a11fa12018-02-22 16:44:10 -0800263 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700264 if (pid == -1) {
265 ALOGW("FileSection '%s' failed to fork", this->name.string());
266 return -errno;
267 }
268
269 // parent process
Yi Jine3dab2d2018-03-22 16:56:39 -0700270 status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
271 std::move(c2pPipe.readFd()),
272 this->timeoutMs, mIsSysfs);
Yi Jin1a11fa12018-02-22 16:44:10 -0800273
Yi Jinb44f7d42017-07-21 12:12:59 -0700274 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800275 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800276 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800277 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700278 return readStatus;
279 }
280
Yi Jinedfd5bb2017-09-06 17:09:11 -0700281 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700282 if (ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800283 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(),
284 strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700285 return ihStatus;
286 }
287
Yi Jinb592e3b2018-02-01 15:17:04 -0800288 VLOG("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
289 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700290 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700291 if (err != NO_ERROR) {
292 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
293 return err;
294 }
295
296 return NO_ERROR;
297}
Yi Jin1a11fa12018-02-22 16:44:10 -0800298// ================================================================================
299GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800300 va_list args;
301 va_start(args, filename);
302 mFilenames = varargs(filename, args);
303 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800304 name = "gzip";
305 for (int i = 0; mFilenames[i] != NULL; i++) {
306 name += " ";
307 name += mFilenames[i];
308 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800309}
Yi Jin0a3406f2017-06-22 19:23:11 -0700310
Yi Jin1a11fa12018-02-22 16:44:10 -0800311GZipSection::~GZipSection() {}
312
313status_t GZipSection::Execute(ReportRequestSet* requests) const {
314 // Reads the files in order, use the first available one.
315 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700316 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800317 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700318 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
319 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800320 break;
321 }
322 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
323 index++; // look at the next file.
324 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700325 VLOG("GZipSection is using file %s, fd=%d", mFilenames[index], fd.get());
Yi Jinc858e272018-03-28 15:32:50 -0700326 if (fd.get() == -1) {
Yi Jin6cacbcb2018-03-30 14:04:52 -0700327 ALOGW("GZipSection %s can't open all the files", this->name.string());
328 return NO_ERROR; // e.g. LAST_KMSG will reach here in user build.
Yi Jinc858e272018-03-28 15:32:50 -0700329 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800330 FdBuffer buffer;
331 Fpipe p2cPipe;
332 Fpipe c2pPipe;
333 // initiate pipes to pass data to/from gzip
334 if (!p2cPipe.init() || !c2pPipe.init()) {
335 ALOGW("GZipSection '%s' failed to setup pipes", this->name.string());
336 return -errno;
337 }
338
Yi Jinc36e91d2018-03-08 11:25:58 -0800339 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800340 if (pid == -1) {
341 ALOGW("GZipSection '%s' failed to fork", this->name.string());
342 return -errno;
343 }
344 // parent process
345
346 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
347 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
348 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
349 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700350 size_t fileLen = strlen(mFilenames[index]);
351 internalBuffer->writeRawVarint32(fileLen);
352 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800353 internalBuffer->writeRawByte(mFilenames[index][i]);
354 }
355 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
356 WIRE_TYPE_LENGTH_DELIMITED);
357 size_t editPos = internalBuffer->wp()->pos();
358 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
359 size_t dataBeginAt = internalBuffer->wp()->pos();
360 VLOG("GZipSection '%s' editPos=%zd, dataBeginAt=%zd", this->name.string(), editPos,
361 dataBeginAt);
362
Yi Jine3dab2d2018-03-22 16:56:39 -0700363 status_t readStatus = buffer.readProcessedDataInStream(
364 fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
365 isSysfs(mFilenames[index]));
Yi Jin1a11fa12018-02-22 16:44:10 -0800366
367 if (readStatus != NO_ERROR || buffer.timedOut()) {
368 ALOGW("GZipSection '%s' failed to read data from gzip: %s, timedout: %s",
369 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
370 kill_child(pid);
371 return readStatus;
372 }
373
374 status_t gzipStatus = wait_child(pid);
375 if (gzipStatus != NO_ERROR) {
376 ALOGW("GZipSection '%s' abnormal child process: %s", this->name.string(),
377 strerror(-gzipStatus));
378 return gzipStatus;
379 }
380 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
381 size_t dataSize = buffer.size() - dataBeginAt;
382 internalBuffer->wp()->rewind()->move(editPos);
383 internalBuffer->writeRawVarint32(dataSize);
384 internalBuffer->copy(dataBeginAt, dataSize);
385 VLOG("GZipSection '%s' wrote %zd bytes in %d ms, dataSize=%zd", this->name.string(),
386 buffer.size(), (int)buffer.durationMs(), dataSize);
387 status_t err = write_report_requests(this->id, buffer, requests);
388 if (err != NO_ERROR) {
389 ALOGW("GZipSection '%s' failed writing: %s", this->name.string(), strerror(-err));
390 return err;
391 }
392
393 return NO_ERROR;
394}
Kweku Adamseadd1232018-02-05 16:45:13 -0800395
Yi Jin0a3406f2017-06-22 19:23:11 -0700396// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800397struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800398 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700399 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800400
401 // Lock protects these fields
402 mutex lock;
403 bool workerDone;
404 status_t workerError;
405
406 WorkerThreadData(const WorkerThreadSection* section);
407 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800408};
409
410WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700411 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800412
Yi Jinb592e3b2018-02-01 15:17:04 -0800413WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800414
415// ================================================================================
Kweku Adamseadd1232018-02-05 16:45:13 -0800416WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
417 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800418
Yi Jinb592e3b2018-02-01 15:17:04 -0800419WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800420
Yi Jinb592e3b2018-02-01 15:17:04 -0800421static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800422 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700423 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800424
425 {
426 unique_lock<mutex> lock(data->lock);
427 data->workerDone = true;
428 data->workerError = err;
429 }
430
Yi Jin6355d2f2018-03-14 15:18:02 -0700431 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800432 data->decStrong(data->section);
433 // data might be gone now. don't use it after this point in this thread.
434 return NULL;
435}
436
Yi Jinb592e3b2018-02-01 15:17:04 -0800437status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800438 status_t err = NO_ERROR;
439 pthread_t thread;
440 pthread_attr_t attr;
441 bool timedOut = false;
442 FdBuffer buffer;
443
444 // Data shared between this thread and the worker thread.
445 sp<WorkerThreadData> data = new WorkerThreadData(this);
446
447 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700448 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800449 return -errno;
450 }
451
452 // The worker thread needs a reference and we can't let the count go to zero
453 // if that thread is slow to start.
454 data->incStrong(this);
455
456 // Create the thread
457 err = pthread_attr_init(&attr);
458 if (err != 0) {
459 return -err;
460 }
461 // TODO: Do we need to tweak thread priority?
462 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
463 if (err != 0) {
464 pthread_attr_destroy(&attr);
465 return -err;
466 }
467 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
468 if (err != 0) {
469 pthread_attr_destroy(&attr);
470 return -err;
471 }
472 pthread_attr_destroy(&attr);
473
474 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jine3dab2d2018-03-22 16:56:39 -0700475 err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800476 if (err != NO_ERROR) {
477 // TODO: Log this error into the incident report.
478 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800479 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800480 }
481
482 // Done with the read fd. The worker thread closes the write one so
483 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700484 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800485
486 // If the worker side is finished, then return its error (which may overwrite
487 // our possible error -- but it's more interesting anyway). If not, then we timed out.
488 {
489 unique_lock<mutex> lock(data->lock);
490 if (!data->workerDone) {
491 // We timed out
492 timedOut = true;
493 } else {
494 if (data->workerError != NO_ERROR) {
495 err = data->workerError;
496 // TODO: Log this error into the incident report.
497 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800498 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800499 }
500 }
501 }
502
503 if (timedOut || buffer.timedOut()) {
504 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
505 return NO_ERROR;
506 }
507
508 if (buffer.truncated()) {
509 // TODO: Log this into the incident report.
510 }
511
512 // TODO: There was an error with the command or buffering. Report that. For now
513 // just exit with a log messasge.
514 if (err != NO_ERROR) {
515 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800516 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800517 return NO_ERROR;
518 }
519
520 // Write the data that was collected
Yi Jinb592e3b2018-02-01 15:17:04 -0800521 VLOG("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
522 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700523 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800524 if (err != NO_ERROR) {
525 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
526 return err;
527 }
528
529 return NO_ERROR;
530}
531
532// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700533CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800534 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800535 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700536 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800537 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800538 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800539 name = "cmd";
540 for (int i = 0; mCommand[i] != NULL; i++) {
541 name += " ";
542 name += mCommand[i];
543 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700544}
Joe Onorato1754d742016-11-21 17:51:35 -0800545
Yi Jinb592e3b2018-02-01 15:17:04 -0800546CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700547 va_list args;
548 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800549 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800550 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800551 name = "cmd";
552 for (int i = 0; mCommand[i] != NULL; i++) {
553 name += " ";
554 name += mCommand[i];
555 }
Joe Onorato1754d742016-11-21 17:51:35 -0800556}
557
Yi Jinb592e3b2018-02-01 15:17:04 -0800558CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800559
Yi Jinb592e3b2018-02-01 15:17:04 -0800560status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700561 FdBuffer buffer;
562 Fpipe cmdPipe;
563 Fpipe ihPipe;
564
565 if (!cmdPipe.init() || !ihPipe.init()) {
566 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
567 return -errno;
568 }
569
Yi Jinc36e91d2018-03-08 11:25:58 -0800570 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700571 if (cmdPid == -1) {
572 ALOGW("CommandSection '%s' failed to fork", this->name.string());
573 return -errno;
574 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800575 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700576 if (ihPid == -1) {
577 ALOGW("CommandSection '%s' failed to fork", this->name.string());
578 return -errno;
579 }
580
Yi Jin6355d2f2018-03-14 15:18:02 -0700581 cmdPipe.writeFd().reset();
Yi Jine3dab2d2018-03-22 16:56:39 -0700582 status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
Yi Jinb44f7d42017-07-21 12:12:59 -0700583 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800584 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800585 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800586 kill_child(cmdPid);
587 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700588 return readStatus;
589 }
590
Kweku Adamseadd1232018-02-05 16:45:13 -0800591 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800592 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700593 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800594 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700595 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800596 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident "
597 "helper: %s",
598 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700599 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
600 }
601
Yi Jinb592e3b2018-02-01 15:17:04 -0800602 VLOG("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
603 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700604 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700605 if (err != NO_ERROR) {
606 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
607 return err;
608 }
Joe Onorato1754d742016-11-21 17:51:35 -0800609 return NO_ERROR;
610}
611
612// ================================================================================
613DumpsysSection::DumpsysSection(int id, const char* service, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800614 : WorkerThreadSection(id), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800615 name = "dumpsys ";
616 name += service;
617
618 va_list args;
619 va_start(args, service);
620 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700621 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800622 if (arg == NULL) {
623 break;
624 }
625 mArgs.add(String16(arg));
626 name += " ";
627 name += arg;
628 }
629 va_end(args);
630}
631
Yi Jinb592e3b2018-02-01 15:17:04 -0800632DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800633
Yi Jinb592e3b2018-02-01 15:17:04 -0800634status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800635 // checkService won't wait for the service to show up like getService will.
636 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700637
Joe Onorato1754d742016-11-21 17:51:35 -0800638 if (service == NULL) {
639 // Returning an error interrupts the entire incident report, so just
640 // log the failure.
641 // TODO: have a meta record inside the report that would log this
642 // failure inside the report, because the fact that we can't find
643 // the service is good data in and of itself. This is running in
644 // another thread so lock that carefully...
645 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
646 return NO_ERROR;
647 }
648
649 service->dump(pipeWriteFd, mArgs);
650
651 return NO_ERROR;
652}
Yi Jin3c034c92017-12-22 17:36:47 -0800653
654// ================================================================================
655// initialization only once in Section.cpp.
656map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
657
Yi Jinb592e3b2018-02-01 15:17:04 -0800658LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3c034c92017-12-22 17:36:47 -0800659 name += "logcat ";
660 name += android_log_id_to_name(logID);
661 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800662 case LOG_ID_EVENTS:
663 case LOG_ID_STATS:
664 case LOG_ID_SECURITY:
665 mBinary = true;
666 break;
667 default:
668 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800669 }
670}
671
Yi Jinb592e3b2018-02-01 15:17:04 -0800672LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800673
Yi Jinb592e3b2018-02-01 15:17:04 -0800674static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800675 while (len > 0) {
676 char c = buf[len - 1];
677 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
678 len--;
679 } else {
680 break;
681 }
682 }
683 return len;
684}
685
686static inline int32_t get4LE(uint8_t const* src) {
687 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
688}
689
Yi Jinb592e3b2018-02-01 15:17:04 -0800690status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800691 // Open log buffer and getting logs since last retrieved time if any.
692 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800693 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
694 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
695 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
696 gLastLogsRetrieved[mLogID], 0),
697 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800698
699 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700700 ALOGE("LogSection %s: Can't get logger.", this->name.string());
701 return -1;
Yi Jin3c034c92017-12-22 17:36:47 -0800702 }
703
704 log_msg msg;
705 log_time lastTimestamp(0);
706
707 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800708 while (true) { // keeps reading until logd buffer is fully read.
Yi Jin83fb1d52018-03-16 12:03:53 -0700709 status_t err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800710 // err = 0 - no content, unexpected connection drop or EOF.
711 // err = +ive number - size of retrieved data from logger
712 // err = -ive number, OS supplied error _except_ for -EAGAIN
713 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
714 if (err <= 0) {
715 if (err != -EAGAIN) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700716 ALOGW("LogSection %s: fails to read a log_msg.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800717 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700718 // dump previous logs and don't consider this error a failure.
Yi Jin3c034c92017-12-22 17:36:47 -0800719 break;
720 }
721 if (mBinary) {
722 // remove the first uint32 which is tag's index in event log tags
723 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800724 msg.len() - sizeof(uint32_t));
725 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800726 android_log_list_element elem;
727
728 lastTimestamp.tv_sec = msg.entry_v1.sec;
729 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
730
731 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800732 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800733 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
734 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800735 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800736 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
737 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800738 proto.write(BinaryLogEntry::TAG_INDEX,
739 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800740 do {
741 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800742 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800743 switch (elem.type) {
744 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800745 proto.write(BinaryLogEntry::Elem::TYPE,
746 BinaryLogEntry::Elem::EVENT_TYPE_INT);
747 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800748 break;
749 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800750 proto.write(BinaryLogEntry::Elem::TYPE,
751 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
752 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800753 break;
754 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800755 proto.write(BinaryLogEntry::Elem::TYPE,
756 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800757 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
758 break;
759 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800760 proto.write(BinaryLogEntry::Elem::TYPE,
761 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800762 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
763 break;
764 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800765 proto.write(BinaryLogEntry::Elem::TYPE,
766 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800767 break;
768 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800769 proto.write(BinaryLogEntry::Elem::TYPE,
770 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800771 break;
772 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800773 proto.write(BinaryLogEntry::Elem::TYPE,
774 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800775 break;
776 }
777 proto.end(elemToken);
778 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
779 proto.end(token);
780 if (context) {
781 android_log_destroy(&context);
782 }
783 } else {
784 AndroidLogEntry entry;
785 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
786 if (err != NO_ERROR) {
Yi Jin83fb1d52018-03-16 12:03:53 -0700787 ALOGW("LogSection %s: fails to process to an entry.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800788 break;
789 }
790 lastTimestamp.tv_sec = entry.tv_sec;
791 lastTimestamp.tv_nsec = entry.tv_nsec;
792
793 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800794 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800795 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
796 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
797 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
798 proto.write(TextLogEntry::UID, entry.uid);
799 proto.write(TextLogEntry::PID, entry.pid);
800 proto.write(TextLogEntry::TID, entry.tid);
801 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800802 proto.write(TextLogEntry::LOG, entry.message,
803 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800804 proto.end(token);
805 }
806 }
807 gLastLogsRetrieved[mLogID] = lastTimestamp;
808 proto.flush(pipeWriteFd);
Yi Jin83fb1d52018-03-16 12:03:53 -0700809 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800810}
Kweku Adamseadd1232018-02-05 16:45:13 -0800811
812// ================================================================================
813
814TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
815 : WorkerThreadSection(id, timeoutMs), mType(type) {
816 name += "tombstone ";
817 name += type;
818}
819
820TombstoneSection::~TombstoneSection() {}
821
822status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
823 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
824 if (proc.get() == nullptr) {
825 ALOGE("opendir /proc failed: %s\n", strerror(errno));
826 return -errno;
827 }
828
829 const std::set<int> hal_pids = get_interesting_hal_pids();
830
831 ProtoOutputStream proto;
832 struct dirent* d;
833 status_t err = NO_ERROR;
834 while ((d = readdir(proc.get()))) {
835 int pid = atoi(d->d_name);
836 if (pid <= 0) {
837 continue;
838 }
839
840 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
841 std::string exe;
842 if (!android::base::Readlink(link_name, &exe)) {
843 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
844 continue;
845 }
846
847 bool is_java_process;
848 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
849 if (mType != "java") continue;
850 // Don't bother dumping backtraces for the zygote.
851 if (IsZygote(pid)) {
852 VLOG("Skipping Zygote");
853 continue;
854 }
855
856 is_java_process = true;
857 } else if (should_dump_native_traces(exe.c_str())) {
858 if (mType != "native") continue;
859 is_java_process = false;
860 } else if (hal_pids.find(pid) != hal_pids.end()) {
861 if (mType != "hal") continue;
862 is_java_process = false;
863 } else {
864 // Probably a native process we don't care about, continue.
865 VLOG("Skipping %d", pid);
866 continue;
867 }
868
869 Fpipe dumpPipe;
870 if (!dumpPipe.init()) {
871 ALOGW("TombstoneSection '%s' failed to setup dump pipe", this->name.string());
872 err = -errno;
873 break;
874 }
875
876 const uint64_t start = Nanotime();
877 pid_t child = fork();
878 if (child < 0) {
879 ALOGE("Failed to fork child process");
880 break;
881 } else if (child == 0) {
882 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700883 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800884 const int ret = dump_backtrace_to_file_timeout(
885 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700886 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800887 if (ret == -1) {
888 if (errno == 0) {
889 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
890 } else {
891 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
892 }
893 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700894 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800895 _exit(EXIT_SUCCESS);
896 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700897 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800898 // Parent process.
899 // Read from the pipe concurrently to avoid blocking the child.
900 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700901 err = buffer.readFully(dumpPipe.readFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800902 if (err != NO_ERROR) {
903 ALOGW("TombstoneSection '%s' failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700904 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800905 break;
906 }
907
908 auto dump = std::make_unique<char[]>(buffer.size());
909 auto iterator = buffer.data();
910 int i = 0;
911 while (iterator.hasNext()) {
912 dump[i] = iterator.next();
913 i++;
914 }
Yi Jin6cacbcb2018-03-30 14:04:52 -0700915 uint64_t token = proto.start(android::os::BackTraceProto::TRACES);
Kweku Adamseadd1232018-02-05 16:45:13 -0800916 proto.write(android::os::BackTraceProto::Stack::PID, pid);
917 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
918 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
919 static_cast<long long>(Nanotime() - start));
920 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700921 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800922 }
923
924 proto.flush(pipeWriteFd);
925 return err;
926}
Yi Jin6cacbcb2018-03-30 14:04:52 -0700927
928} // namespace incidentd
929} // namespace os
930} // namespace android