blob: 5cde5a94e2dd69ad164c67186b49a09379e3aa2b [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#include <wait.h>
24
Yi Jin3c034c92017-12-22 17:36:47 -080025#include <mutex>
Kweku Adamseadd1232018-02-05 16:45:13 -080026#include <set>
Joe Onorato1754d742016-11-21 17:51:35 -080027
Yi Jinb592e3b2018-02-01 15:17:04 -080028#include <android-base/file.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080029#include <android-base/stringprintf.h>
Yi Jinc23fad22017-09-15 17:24:59 -070030#include <android/util/protobuf.h>
Joe Onorato1754d742016-11-21 17:51:35 -080031#include <binder/IServiceManager.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080032#include <debuggerd/client.h>
33#include <dumputils/dump_utils.h>
Yi Jin3c034c92017-12-22 17:36:47 -080034#include <log/log_event_list.h>
Yi Jin3c034c92017-12-22 17:36:47 -080035#include <log/log_read.h>
Yi Jinb592e3b2018-02-01 15:17:04 -080036#include <log/logprint.h>
Yi Jin3c034c92017-12-22 17:36:47 -080037#include <private/android_logger.h>
38
39#include "FdBuffer.h"
Yi Jin3c034c92017-12-22 17:36:47 -080040#include "Privacy.h"
41#include "PrivacyBuffer.h"
Kweku Adamseadd1232018-02-05 16:45:13 -080042#include "frameworks/base/core/proto/android/os/backtrace.proto.h"
Yi Jin1a11fa12018-02-22 16:44:10 -080043#include "frameworks/base/core/proto/android/os/data.proto.h"
Yi Jinb592e3b2018-02-01 15:17:04 -080044#include "frameworks/base/core/proto/android/util/log.proto.h"
45#include "incidentd_util.h"
Joe Onorato1754d742016-11-21 17:51:35 -080046
Yi Jinb592e3b2018-02-01 15:17:04 -080047using namespace android::base;
Yi Jinc23fad22017-09-15 17:24:59 -070048using namespace android::util;
Joe Onorato1754d742016-11-21 17:51:35 -080049using namespace std;
50
Yi Jinc23fad22017-09-15 17:24:59 -070051// special section ids
52const int FIELD_ID_INCIDENT_HEADER = 1;
Yi Jin329130b2018-02-09 16:47:47 -080053const int FIELD_ID_INCIDENT_METADATA = 2;
Yi Jinc23fad22017-09-15 17:24:59 -070054
55// incident section parameters
Yi Jinb592e3b2018-02-01 15:17:04 -080056const int WAIT_MAX = 5;
Yi Jinb44f7d42017-07-21 12:12:59 -070057const struct timespec WAIT_INTERVAL_NS = {0, 200 * 1000 * 1000};
Yi Jin3c034c92017-12-22 17:36:47 -080058const char INCIDENT_HELPER[] = "/system/bin/incident_helper";
Yi Jin1a11fa12018-02-22 16:44:10 -080059const char GZIP[] = "/system/bin/gzip";
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 Jin1a11fa12018-02-22 16:44:10 -080063 return fork_execute_cmd(INCIDENT_HELPER, const_cast<char**>(ihArgs), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -070064}
65
Yi Jin99c248f2017-08-25 18:11:58 -070066// ================================================================================
Yi Jin4bab3a12018-01-10 16:50:59 -080067static status_t statusCode(int status) {
68 if (WIFSIGNALED(status)) {
Yi Jinb592e3b2018-02-01 15:17:04 -080069 VLOG("return by signal: %s", strerror(WTERMSIG(status)));
70 return -WTERMSIG(status);
Yi Jin4bab3a12018-01-10 16:50:59 -080071 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Yi Jinb592e3b2018-02-01 15:17:04 -080072 VLOG("return by exit: %s", strerror(WEXITSTATUS(status)));
73 return -WEXITSTATUS(status);
Yi Jin4bab3a12018-01-10 16:50:59 -080074 }
75 return NO_ERROR;
76}
77
Yi Jinedfd5bb2017-09-06 17:09:11 -070078static status_t kill_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -070079 int status;
Yi Jinb592e3b2018-02-01 15:17:04 -080080 VLOG("try to kill child process %d", pid);
Yi Jinb44f7d42017-07-21 12:12:59 -070081 kill(pid, SIGKILL);
82 if (waitpid(pid, &status, 0) == -1) return -1;
Yi Jin4bab3a12018-01-10 16:50:59 -080083 return statusCode(status);
Yi Jinb44f7d42017-07-21 12:12:59 -070084}
85
Yi Jinedfd5bb2017-09-06 17:09:11 -070086static status_t wait_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -070087 int status;
88 bool died = false;
89 // wait for child to report status up to 1 seconds
Yi Jinb592e3b2018-02-01 15:17:04 -080090 for (int loop = 0; !died && loop < WAIT_MAX; loop++) {
Yi Jinb44f7d42017-07-21 12:12:59 -070091 if (waitpid(pid, &status, WNOHANG) == pid) died = true;
92 // sleep for 0.2 second
93 nanosleep(&WAIT_INTERVAL_NS, NULL);
94 }
Yi Jinedfd5bb2017-09-06 17:09:11 -070095 if (!died) return kill_child(pid);
Yi Jin4bab3a12018-01-10 16:50:59 -080096 return statusCode(status);
Yi Jinb44f7d42017-07-21 12:12:59 -070097}
Joe Onorato1754d742016-11-21 17:51:35 -080098// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -080099static status_t write_section_header(int fd, int sectionId, size_t size) {
Yi Jin99c248f2017-08-25 18:11:58 -0700100 uint8_t buf[20];
Yi Jinb592e3b2018-02-01 15:17:04 -0800101 uint8_t* p = write_length_delimited_tag_header(buf, sectionId, size);
102 return WriteFully(fd, buf, p - buf) ? NO_ERROR : -errno;
Yi Jin99c248f2017-08-25 18:11:58 -0700103}
104
Kweku Adamseadd1232018-02-05 16:45:13 -0800105// Reads data from FdBuffer and writes it to the requests file descriptor.
Yi Jinb592e3b2018-02-01 15:17:04 -0800106static status_t write_report_requests(const int id, const FdBuffer& buffer,
107 ReportRequestSet* requests) {
Yi Jin0f047162017-09-05 13:44:22 -0700108 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -0700109 EncodedBuffer::iterator data = buffer.data();
110 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -0700111 int writeable = 0;
Yi Jin86dce412018-03-07 11:36:57 -0800112 IncidentMetadata::SectionStats* stats = requests->sectionStats(id);
Yi Jin329130b2018-02-09 16:47:47 -0800113
114 stats->set_dump_size_bytes(data.size());
115 stats->set_dump_duration_ms(buffer.durationMs());
116 stats->set_timed_out(buffer.timedOut());
117 stats->set_is_truncated(buffer.truncated());
Yi Jin99c248f2017-08-25 18:11:58 -0700118
Yi Jin0f047162017-09-05 13:44:22 -0700119 // The streaming ones, group requests by spec in order to save unnecessary strip operations
120 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -0800121 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -0700122 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -0700123 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -0700124 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -0700125 }
Yi Jin3ec5cc72018-01-26 13:42:43 -0800126 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -0700127 requestsBySpec[spec].push_back(request);
128 }
129
Yi Jin3ec5cc72018-01-26 13:42:43 -0800130 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -0700131 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700132 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800133 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700134 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700135
Yi Jin3ec5cc72018-01-26 13:42:43 -0800136 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700137 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700138 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800139 if (err != NO_ERROR) {
140 request->err = err;
141 continue;
142 }
Yi Jinc23fad22017-09-15 17:24:59 -0700143 err = privacyBuffer.flush(request->fd);
Yi Jinb592e3b2018-02-01 15:17:04 -0800144 if (err != NO_ERROR) {
145 request->err = err;
146 continue;
147 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700148 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800149 VLOG("Section %d flushed %zu bytes to fd %d with spec %d", id, privacyBuffer.size(),
150 request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700151 }
Yi Jinc23fad22017-09-15 17:24:59 -0700152 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700153 }
154
155 // The dropbox file
156 if (requests->mainFd() >= 0) {
Yi Jin329130b2018-02-09 16:47:47 -0800157 PrivacySpec spec = PrivacySpec::new_spec(requests->mainDest());
Yi Jin3ec5cc72018-01-26 13:42:43 -0800158 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800159 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700160 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700161
Yi Jinc23fad22017-09-15 17:24:59 -0700162 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800163 if (err != NO_ERROR) {
164 requests->setMainFd(-1);
165 goto DONE;
166 }
Yi Jinc23fad22017-09-15 17:24:59 -0700167 err = privacyBuffer.flush(requests->mainFd());
Yi Jinb592e3b2018-02-01 15:17:04 -0800168 if (err != NO_ERROR) {
169 requests->setMainFd(-1);
170 goto DONE;
171 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700172 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800173 VLOG("Section %d flushed %zu bytes to dropbox %d with spec %d", id, privacyBuffer.size(),
174 requests->mainFd(), spec.dest);
Yi Jin329130b2018-02-09 16:47:47 -0800175 stats->set_report_size_bytes(privacyBuffer.size());
Yi Jin99c248f2017-08-25 18:11:58 -0700176 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700177
178DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700179 // only returns error if there is no fd to write to.
180 return writeable > 0 ? NO_ERROR : err;
181}
182
183// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800184Section::Section(int i, const int64_t timeoutMs) : id(i), timeoutMs(timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800185
Yi Jinb592e3b2018-02-01 15:17:04 -0800186Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800187
Joe Onorato1754d742016-11-21 17:51:35 -0800188// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800189HeaderSection::HeaderSection() : Section(FIELD_ID_INCIDENT_HEADER, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700190
Yi Jinb592e3b2018-02-01 15:17:04 -0800191HeaderSection::~HeaderSection() {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700192
Yi Jinb592e3b2018-02-01 15:17:04 -0800193status_t HeaderSection::Execute(ReportRequestSet* requests) const {
194 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700195 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800196 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700197
Yi Jinb592e3b2018-02-01 15:17:04 -0800198 for (vector<vector<uint8_t>>::const_iterator buf = headers.begin(); buf != headers.end();
199 buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700200 if (buf->empty()) continue;
201
202 // So the idea is only requests with negative fd are written to dropbox file.
203 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800204 write_section_header(fd, id, buf->size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800205 WriteFully(fd, (uint8_t const*)buf->data(), buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700206 // If there was an error now, there will be an error later and we will remove
207 // it from the list then.
208 }
209 }
210 return NO_ERROR;
211}
Yi Jin329130b2018-02-09 16:47:47 -0800212// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800213MetadataSection::MetadataSection() : Section(FIELD_ID_INCIDENT_METADATA, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700214
Yi Jinb592e3b2018-02-01 15:17:04 -0800215MetadataSection::~MetadataSection() {}
Yi Jin329130b2018-02-09 16:47:47 -0800216
Yi Jinb592e3b2018-02-01 15:17:04 -0800217status_t MetadataSection::Execute(ReportRequestSet* requests) const {
Yi Jin86dce412018-03-07 11:36:57 -0800218 ProtoOutputStream proto;
219 IncidentMetadata metadata = requests->metadata();
220 proto.write(FIELD_TYPE_ENUM | IncidentMetadata::kDestFieldNumber, metadata.dest());
221 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::kRequestSizeFieldNumber,
222 metadata.request_size());
223 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::kUseDropboxFieldNumber, metadata.use_dropbox());
224 for (auto iter = requests->allSectionStats().begin(); iter != requests->allSectionStats().end();
225 iter++) {
226 IncidentMetadata::SectionStats stats = iter->second;
227 uint64_t token = proto.start(FIELD_TYPE_MESSAGE | IncidentMetadata::kSectionsFieldNumber);
228 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kIdFieldNumber, stats.id());
229 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kSuccessFieldNumber,
230 stats.success());
231 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kReportSizeBytesFieldNumber,
232 stats.report_size_bytes());
233 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kExecDurationMsFieldNumber,
234 stats.exec_duration_ms());
235 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kDumpSizeBytesFieldNumber,
236 stats.dump_size_bytes());
237 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kDumpDurationMsFieldNumber,
238 stats.dump_duration_ms());
239 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kTimedOutFieldNumber,
240 stats.timed_out());
241 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kIsTruncatedFieldNumber,
242 stats.is_truncated());
243 proto.end(token);
244 }
245
Yi Jinb592e3b2018-02-01 15:17:04 -0800246 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jin329130b2018-02-09 16:47:47 -0800247 const sp<ReportRequest> request = *it;
Yi Jin86dce412018-03-07 11:36:57 -0800248 if (request->fd < 0 || request->err != NO_ERROR) {
Yi Jin329130b2018-02-09 16:47:47 -0800249 continue;
250 }
Yi Jin86dce412018-03-07 11:36:57 -0800251 write_section_header(request->fd, id, proto.size());
252 if (!proto.flush(request->fd)) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800253 ALOGW("Failed to write metadata to fd %d", request->fd);
254 // we don't fail if we can't write to a single request's fd.
255 }
Yi Jin329130b2018-02-09 16:47:47 -0800256 }
Yi Jin86dce412018-03-07 11:36:57 -0800257 if (requests->mainFd() >= 0) {
258 write_section_header(requests->mainFd(), id, proto.size());
259 if (!proto.flush(requests->mainFd())) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800260 ALOGW("Failed to write metadata to dropbox fd %d", requests->mainFd());
261 return -1;
262 }
Yi Jin329130b2018-02-09 16:47:47 -0800263 }
264 return NO_ERROR;
265}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700266// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -0800267static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
268
Yi Jinb44f7d42017-07-21 12:12:59 -0700269FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Yi Jinb592e3b2018-02-01 15:17:04 -0800270 : Section(id, timeoutMs), mFilename(filename) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700271 name = filename;
Yi Jin1a11fa12018-02-22 16:44:10 -0800272 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -0700273}
274
275FileSection::~FileSection() {}
276
Yi Jinb592e3b2018-02-01 15:17:04 -0800277status_t FileSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700278 // read from mFilename first, make sure the file is available
279 // add O_CLOEXEC to make sure it is closed when exec incident helper
George Burgess IV6f9735b2017-08-03 16:08:29 -0700280 int fd = open(mFilename, O_RDONLY | O_CLOEXEC);
Yi Jin0a3406f2017-06-22 19:23:11 -0700281 if (fd == -1) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800282 ALOGW("FileSection '%s' failed to open file", this->name.string());
283 return -errno;
Yi Jin0a3406f2017-06-22 19:23:11 -0700284 }
285
Yi Jinb44f7d42017-07-21 12:12:59 -0700286 FdBuffer buffer;
287 Fpipe p2cPipe;
288 Fpipe c2pPipe;
289 // initiate pipes to pass data to/from incident_helper
290 if (!p2cPipe.init() || !c2pPipe.init()) {
291 ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700292 return -errno;
293 }
294
Yi Jin1a11fa12018-02-22 16:44:10 -0800295 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700296 if (pid == -1) {
297 ALOGW("FileSection '%s' failed to fork", this->name.string());
298 return -errno;
299 }
300
301 // parent process
302 status_t readStatus = buffer.readProcessedDataInStream(fd, p2cPipe.writeFd(), c2pPipe.readFd(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800303 this->timeoutMs, mIsSysfs);
Yi Jin1a11fa12018-02-22 16:44:10 -0800304 close(fd); // close the fd anyway.
305
Yi Jinb44f7d42017-07-21 12:12:59 -0700306 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800307 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800308 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800309 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700310 return readStatus;
311 }
312
Yi Jinedfd5bb2017-09-06 17:09:11 -0700313 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700314 if (ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800315 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(),
316 strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700317 return ihStatus;
318 }
319
Yi Jinb592e3b2018-02-01 15:17:04 -0800320 VLOG("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
321 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700322 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700323 if (err != NO_ERROR) {
324 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
325 return err;
326 }
327
328 return NO_ERROR;
329}
Yi Jin1a11fa12018-02-22 16:44:10 -0800330// ================================================================================
331GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
332 name = "gzip ";
333 name += filename;
334 va_list args;
335 va_start(args, filename);
336 mFilenames = varargs(filename, args);
337 va_end(args);
338}
Yi Jin0a3406f2017-06-22 19:23:11 -0700339
Yi Jin1a11fa12018-02-22 16:44:10 -0800340GZipSection::~GZipSection() {}
341
342status_t GZipSection::Execute(ReportRequestSet* requests) const {
343 // Reads the files in order, use the first available one.
344 int index = 0;
345 int fd = -1;
346 while (mFilenames[index] != NULL) {
347 fd = open(mFilenames[index], O_RDONLY | O_CLOEXEC);
348 if (fd != -1) {
349 break;
350 }
351 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
352 index++; // look at the next file.
353 }
354 VLOG("GZipSection is using file %s, fd=%d", mFilenames[index], fd);
355 if (fd == -1) return -1;
356
357 FdBuffer buffer;
358 Fpipe p2cPipe;
359 Fpipe c2pPipe;
360 // initiate pipes to pass data to/from gzip
361 if (!p2cPipe.init() || !c2pPipe.init()) {
362 ALOGW("GZipSection '%s' failed to setup pipes", this->name.string());
363 return -errno;
364 }
365
366 const char* gzipArgs[]{GZIP, NULL};
367 pid_t pid = fork_execute_cmd(GZIP, const_cast<char**>(gzipArgs), &p2cPipe, &c2pPipe);
368 if (pid == -1) {
369 ALOGW("GZipSection '%s' failed to fork", this->name.string());
370 return -errno;
371 }
372 // parent process
373
374 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
375 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
376 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
377 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
378 String8 usedFile(mFilenames[index]);
379 internalBuffer->writeRawVarint32(usedFile.size());
380 for (size_t i = 0; i < usedFile.size(); i++) {
381 internalBuffer->writeRawByte(mFilenames[index][i]);
382 }
383 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
384 WIRE_TYPE_LENGTH_DELIMITED);
385 size_t editPos = internalBuffer->wp()->pos();
386 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
387 size_t dataBeginAt = internalBuffer->wp()->pos();
388 VLOG("GZipSection '%s' editPos=%zd, dataBeginAt=%zd", this->name.string(), editPos,
389 dataBeginAt);
390
391 status_t readStatus = buffer.readProcessedDataInStream(
392 fd, p2cPipe.writeFd(), c2pPipe.readFd(), this->timeoutMs, isSysfs(mFilenames[index]));
393 close(fd); // close the fd anyway.
394
395 if (readStatus != NO_ERROR || buffer.timedOut()) {
396 ALOGW("GZipSection '%s' failed to read data from gzip: %s, timedout: %s",
397 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
398 kill_child(pid);
399 return readStatus;
400 }
401
402 status_t gzipStatus = wait_child(pid);
403 if (gzipStatus != NO_ERROR) {
404 ALOGW("GZipSection '%s' abnormal child process: %s", this->name.string(),
405 strerror(-gzipStatus));
406 return gzipStatus;
407 }
408 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
409 size_t dataSize = buffer.size() - dataBeginAt;
410 internalBuffer->wp()->rewind()->move(editPos);
411 internalBuffer->writeRawVarint32(dataSize);
412 internalBuffer->copy(dataBeginAt, dataSize);
413 VLOG("GZipSection '%s' wrote %zd bytes in %d ms, dataSize=%zd", this->name.string(),
414 buffer.size(), (int)buffer.durationMs(), dataSize);
415 status_t err = write_report_requests(this->id, buffer, requests);
416 if (err != NO_ERROR) {
417 ALOGW("GZipSection '%s' failed writing: %s", this->name.string(), strerror(-err));
418 return err;
419 }
420
421 return NO_ERROR;
422}
Kweku Adamseadd1232018-02-05 16:45:13 -0800423
Yi Jin0a3406f2017-06-22 19:23:11 -0700424// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800425struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800426 const WorkerThreadSection* section;
427 int fds[2];
428
429 // Lock protects these fields
430 mutex lock;
431 bool workerDone;
432 status_t workerError;
433
434 WorkerThreadData(const WorkerThreadSection* section);
435 virtual ~WorkerThreadData();
436
437 int readFd() { return fds[0]; }
438 int writeFd() { return fds[1]; }
439};
440
441WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jinb592e3b2018-02-01 15:17:04 -0800442 : section(sec), workerDone(false), workerError(NO_ERROR) {
Joe Onorato1754d742016-11-21 17:51:35 -0800443 fds[0] = -1;
444 fds[1] = -1;
445}
446
Yi Jinb592e3b2018-02-01 15:17:04 -0800447WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800448
449// ================================================================================
Kweku Adamseadd1232018-02-05 16:45:13 -0800450WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
451 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800452
Yi Jinb592e3b2018-02-01 15:17:04 -0800453WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800454
Yi Jinb592e3b2018-02-01 15:17:04 -0800455static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800456 WorkerThreadData* data = (WorkerThreadData*)cookie;
457 status_t err = data->section->BlockingCall(data->writeFd());
458
459 {
460 unique_lock<mutex> lock(data->lock);
461 data->workerDone = true;
462 data->workerError = err;
463 }
464
465 close(data->writeFd());
466 data->decStrong(data->section);
467 // data might be gone now. don't use it after this point in this thread.
468 return NULL;
469}
470
Yi Jinb592e3b2018-02-01 15:17:04 -0800471status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800472 status_t err = NO_ERROR;
473 pthread_t thread;
474 pthread_attr_t attr;
475 bool timedOut = false;
476 FdBuffer buffer;
477
478 // Data shared between this thread and the worker thread.
479 sp<WorkerThreadData> data = new WorkerThreadData(this);
480
481 // Create the pipe
482 err = pipe(data->fds);
483 if (err != 0) {
484 return -errno;
485 }
486
487 // The worker thread needs a reference and we can't let the count go to zero
488 // if that thread is slow to start.
489 data->incStrong(this);
490
491 // Create the thread
492 err = pthread_attr_init(&attr);
493 if (err != 0) {
494 return -err;
495 }
496 // TODO: Do we need to tweak thread priority?
497 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
498 if (err != 0) {
499 pthread_attr_destroy(&attr);
500 return -err;
501 }
502 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
503 if (err != 0) {
504 pthread_attr_destroy(&attr);
505 return -err;
506 }
507 pthread_attr_destroy(&attr);
508
509 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jinb44f7d42017-07-21 12:12:59 -0700510 err = buffer.read(data->readFd(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800511 if (err != NO_ERROR) {
512 // TODO: Log this error into the incident report.
513 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800514 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800515 }
516
517 // Done with the read fd. The worker thread closes the write one so
518 // we never race and get here first.
519 close(data->readFd());
520
521 // If the worker side is finished, then return its error (which may overwrite
522 // our possible error -- but it's more interesting anyway). If not, then we timed out.
523 {
524 unique_lock<mutex> lock(data->lock);
525 if (!data->workerDone) {
526 // We timed out
527 timedOut = true;
528 } else {
529 if (data->workerError != NO_ERROR) {
530 err = data->workerError;
531 // TODO: Log this error into the incident report.
532 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800533 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800534 }
535 }
536 }
537
538 if (timedOut || buffer.timedOut()) {
539 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
540 return NO_ERROR;
541 }
542
543 if (buffer.truncated()) {
544 // TODO: Log this into the incident report.
545 }
546
547 // TODO: There was an error with the command or buffering. Report that. For now
548 // just exit with a log messasge.
549 if (err != NO_ERROR) {
550 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800551 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800552 return NO_ERROR;
553 }
554
555 // Write the data that was collected
Yi Jinb592e3b2018-02-01 15:17:04 -0800556 VLOG("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
557 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700558 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800559 if (err != NO_ERROR) {
560 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
561 return err;
562 }
563
564 return NO_ERROR;
565}
566
567// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700568CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800569 : Section(id, timeoutMs) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800570 name = command;
Joe Onorato1754d742016-11-21 17:51:35 -0800571 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700572 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800573 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800574 va_end(args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700575}
Joe Onorato1754d742016-11-21 17:51:35 -0800576
Yi Jinb592e3b2018-02-01 15:17:04 -0800577CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800578 name = command;
Yi Jinb44f7d42017-07-21 12:12:59 -0700579 va_list args;
580 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800581 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800582 va_end(args);
583}
584
Yi Jinb592e3b2018-02-01 15:17:04 -0800585CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800586
Yi Jinb592e3b2018-02-01 15:17:04 -0800587status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700588 FdBuffer buffer;
589 Fpipe cmdPipe;
590 Fpipe ihPipe;
591
592 if (!cmdPipe.init() || !ihPipe.init()) {
593 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
594 return -errno;
595 }
596
597 pid_t cmdPid = fork();
598 if (cmdPid == -1) {
599 ALOGW("CommandSection '%s' failed to fork", this->name.string());
600 return -errno;
601 }
602 // child process to execute the command as root
603 if (cmdPid == 0) {
604 // replace command's stdout with ihPipe's write Fd
605 if (dup2(cmdPipe.writeFd(), STDOUT_FILENO) != 1 || !ihPipe.close() || !cmdPipe.close()) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800606 ALOGW("CommandSection '%s' failed to set up stdout: %s", this->name.string(),
607 strerror(errno));
Yi Jinb44f7d42017-07-21 12:12:59 -0700608 _exit(EXIT_FAILURE);
609 }
Yi Jinb592e3b2018-02-01 15:17:04 -0800610 execvp(this->mCommand[0], (char* const*)this->mCommand);
611 int err = errno; // record command error code
612 ALOGW("CommandSection '%s' failed in executing command: %s", this->name.string(),
613 strerror(errno));
614 _exit(err); // exit with command error code
Yi Jinb44f7d42017-07-21 12:12:59 -0700615 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800616 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700617 if (ihPid == -1) {
618 ALOGW("CommandSection '%s' failed to fork", this->name.string());
619 return -errno;
620 }
621
622 close(cmdPipe.writeFd());
623 status_t readStatus = buffer.read(ihPipe.readFd(), this->timeoutMs);
624 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800625 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800626 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800627 kill_child(cmdPid);
628 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700629 return readStatus;
630 }
631
Kweku Adamseadd1232018-02-05 16:45:13 -0800632 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800633 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700634 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800635 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700636 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800637 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident "
638 "helper: %s",
639 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700640 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
641 }
642
Yi Jinb592e3b2018-02-01 15:17:04 -0800643 VLOG("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
644 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700645 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700646 if (err != NO_ERROR) {
647 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
648 return err;
649 }
Joe Onorato1754d742016-11-21 17:51:35 -0800650 return NO_ERROR;
651}
652
653// ================================================================================
654DumpsysSection::DumpsysSection(int id, const char* service, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800655 : WorkerThreadSection(id), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800656 name = "dumpsys ";
657 name += service;
658
659 va_list args;
660 va_start(args, service);
661 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700662 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800663 if (arg == NULL) {
664 break;
665 }
666 mArgs.add(String16(arg));
667 name += " ";
668 name += arg;
669 }
670 va_end(args);
671}
672
Yi Jinb592e3b2018-02-01 15:17:04 -0800673DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800674
Yi Jinb592e3b2018-02-01 15:17:04 -0800675status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800676 // checkService won't wait for the service to show up like getService will.
677 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700678
Joe Onorato1754d742016-11-21 17:51:35 -0800679 if (service == NULL) {
680 // Returning an error interrupts the entire incident report, so just
681 // log the failure.
682 // TODO: have a meta record inside the report that would log this
683 // failure inside the report, because the fact that we can't find
684 // the service is good data in and of itself. This is running in
685 // another thread so lock that carefully...
686 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
687 return NO_ERROR;
688 }
689
690 service->dump(pipeWriteFd, mArgs);
691
692 return NO_ERROR;
693}
Yi Jin3c034c92017-12-22 17:36:47 -0800694
695// ================================================================================
696// initialization only once in Section.cpp.
697map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
698
Yi Jinb592e3b2018-02-01 15:17:04 -0800699LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3c034c92017-12-22 17:36:47 -0800700 name += "logcat ";
701 name += android_log_id_to_name(logID);
702 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800703 case LOG_ID_EVENTS:
704 case LOG_ID_STATS:
705 case LOG_ID_SECURITY:
706 mBinary = true;
707 break;
708 default:
709 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800710 }
711}
712
Yi Jinb592e3b2018-02-01 15:17:04 -0800713LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800714
Yi Jinb592e3b2018-02-01 15:17:04 -0800715static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800716 while (len > 0) {
717 char c = buf[len - 1];
718 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
719 len--;
720 } else {
721 break;
722 }
723 }
724 return len;
725}
726
727static inline int32_t get4LE(uint8_t const* src) {
728 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
729}
730
Yi Jinb592e3b2018-02-01 15:17:04 -0800731status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800732 // Open log buffer and getting logs since last retrieved time if any.
733 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800734 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
735 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
736 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
737 gLastLogsRetrieved[mLogID], 0),
738 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800739
740 if (android_logger_open(loggers.get(), mLogID) == NULL) {
741 ALOGW("LogSection %s: Can't get logger.", this->name.string());
Kweku Adamseadd1232018-02-05 16:45:13 -0800742 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800743 }
744
745 log_msg msg;
746 log_time lastTimestamp(0);
747
Kweku Adamseadd1232018-02-05 16:45:13 -0800748 status_t err = NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800749 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800750 while (true) { // keeps reading until logd buffer is fully read.
Kweku Adamseadd1232018-02-05 16:45:13 -0800751 err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800752 // err = 0 - no content, unexpected connection drop or EOF.
753 // err = +ive number - size of retrieved data from logger
754 // err = -ive number, OS supplied error _except_ for -EAGAIN
755 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
756 if (err <= 0) {
757 if (err != -EAGAIN) {
758 ALOGE("LogSection %s: fails to read a log_msg.\n", this->name.string());
759 }
760 break;
761 }
762 if (mBinary) {
763 // remove the first uint32 which is tag's index in event log tags
764 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800765 msg.len() - sizeof(uint32_t));
766 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800767 android_log_list_element elem;
768
769 lastTimestamp.tv_sec = msg.entry_v1.sec;
770 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
771
772 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800773 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800774 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
775 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800776 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800777 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
778 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800779 proto.write(BinaryLogEntry::TAG_INDEX,
780 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800781 do {
782 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800783 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800784 switch (elem.type) {
785 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800786 proto.write(BinaryLogEntry::Elem::TYPE,
787 BinaryLogEntry::Elem::EVENT_TYPE_INT);
788 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800789 break;
790 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800791 proto.write(BinaryLogEntry::Elem::TYPE,
792 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
793 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800794 break;
795 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800796 proto.write(BinaryLogEntry::Elem::TYPE,
797 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800798 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
799 break;
800 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800801 proto.write(BinaryLogEntry::Elem::TYPE,
802 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800803 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
804 break;
805 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800806 proto.write(BinaryLogEntry::Elem::TYPE,
807 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800808 break;
809 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800810 proto.write(BinaryLogEntry::Elem::TYPE,
811 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800812 break;
813 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800814 proto.write(BinaryLogEntry::Elem::TYPE,
815 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800816 break;
817 }
818 proto.end(elemToken);
819 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
820 proto.end(token);
821 if (context) {
822 android_log_destroy(&context);
823 }
824 } else {
825 AndroidLogEntry entry;
826 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
827 if (err != NO_ERROR) {
828 ALOGE("LogSection %s: fails to process to an entry.\n", this->name.string());
829 break;
830 }
831 lastTimestamp.tv_sec = entry.tv_sec;
832 lastTimestamp.tv_nsec = entry.tv_nsec;
833
834 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800835 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800836 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
837 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
838 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
839 proto.write(TextLogEntry::UID, entry.uid);
840 proto.write(TextLogEntry::PID, entry.pid);
841 proto.write(TextLogEntry::TID, entry.tid);
842 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800843 proto.write(TextLogEntry::LOG, entry.message,
844 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800845 proto.end(token);
846 }
847 }
848 gLastLogsRetrieved[mLogID] = lastTimestamp;
849 proto.flush(pipeWriteFd);
850 return err;
851}
Kweku Adamseadd1232018-02-05 16:45:13 -0800852
853// ================================================================================
854
855TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
856 : WorkerThreadSection(id, timeoutMs), mType(type) {
857 name += "tombstone ";
858 name += type;
859}
860
861TombstoneSection::~TombstoneSection() {}
862
863status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
864 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
865 if (proc.get() == nullptr) {
866 ALOGE("opendir /proc failed: %s\n", strerror(errno));
867 return -errno;
868 }
869
870 const std::set<int> hal_pids = get_interesting_hal_pids();
871
872 ProtoOutputStream proto;
873 struct dirent* d;
874 status_t err = NO_ERROR;
875 while ((d = readdir(proc.get()))) {
876 int pid = atoi(d->d_name);
877 if (pid <= 0) {
878 continue;
879 }
880
881 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
882 std::string exe;
883 if (!android::base::Readlink(link_name, &exe)) {
884 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
885 continue;
886 }
887
888 bool is_java_process;
889 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
890 if (mType != "java") continue;
891 // Don't bother dumping backtraces for the zygote.
892 if (IsZygote(pid)) {
893 VLOG("Skipping Zygote");
894 continue;
895 }
896
897 is_java_process = true;
898 } else if (should_dump_native_traces(exe.c_str())) {
899 if (mType != "native") continue;
900 is_java_process = false;
901 } else if (hal_pids.find(pid) != hal_pids.end()) {
902 if (mType != "hal") continue;
903 is_java_process = false;
904 } else {
905 // Probably a native process we don't care about, continue.
906 VLOG("Skipping %d", pid);
907 continue;
908 }
909
910 Fpipe dumpPipe;
911 if (!dumpPipe.init()) {
912 ALOGW("TombstoneSection '%s' failed to setup dump pipe", this->name.string());
913 err = -errno;
914 break;
915 }
916
917 const uint64_t start = Nanotime();
918 pid_t child = fork();
919 if (child < 0) {
920 ALOGE("Failed to fork child process");
921 break;
922 } else if (child == 0) {
923 // This is the child process.
924 close(dumpPipe.readFd());
925 const int ret = dump_backtrace_to_file_timeout(
926 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
927 is_java_process ? 5 : 20, dumpPipe.writeFd());
928 if (ret == -1) {
929 if (errno == 0) {
930 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
931 } else {
932 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
933 }
934 }
935 if (close(dumpPipe.writeFd()) != 0) {
936 ALOGW("TombstoneSection '%s' failed to close dump pipe writeFd: %d",
937 this->name.string(), errno);
938 _exit(EXIT_FAILURE);
939 }
940
941 _exit(EXIT_SUCCESS);
942 }
943 close(dumpPipe.writeFd());
944 // Parent process.
945 // Read from the pipe concurrently to avoid blocking the child.
946 FdBuffer buffer;
947 err = buffer.readFully(dumpPipe.readFd());
948 if (err != NO_ERROR) {
949 ALOGW("TombstoneSection '%s' failed to read stack dump: %d", this->name.string(), err);
950 if (close(dumpPipe.readFd()) != 0) {
951 ALOGW("TombstoneSection '%s' failed to close dump pipe readFd: %s",
952 this->name.string(), strerror(errno));
953 }
954 break;
955 }
956
957 auto dump = std::make_unique<char[]>(buffer.size());
958 auto iterator = buffer.data();
959 int i = 0;
960 while (iterator.hasNext()) {
961 dump[i] = iterator.next();
962 i++;
963 }
964 long long token = proto.start(android::os::BackTraceProto::TRACES);
965 proto.write(android::os::BackTraceProto::Stack::PID, pid);
966 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
967 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
968 static_cast<long long>(Nanotime() - start));
969 proto.end(token);
970
971 if (close(dumpPipe.readFd()) != 0) {
972 ALOGW("TombstoneSection '%s' failed to close dump pipe readFd: %d", this->name.string(),
973 errno);
974 err = -errno;
975 break;
976 }
977 }
978
979 proto.flush(pipeWriteFd);
980 return err;
981}