blob: ab4e764d92a403ff4d02c0c220aa7f9100d9a001 [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
Yi Jin6355d2f2018-03-14 15:18:02 -0700280 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
281 if (fd.get() == -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
Yi Jin6355d2f2018-03-14 15:18:02 -0700302 status_t readStatus = buffer.readProcessedDataInStream(
303 &fd, &p2cPipe.writeFd(), &c2pPipe.readFd(), this->timeoutMs, mIsSysfs);
Yi Jin1a11fa12018-02-22 16:44:10 -0800304
Yi Jinb44f7d42017-07-21 12:12:59 -0700305 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800306 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800307 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800308 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700309 return readStatus;
310 }
311
Yi Jinedfd5bb2017-09-06 17:09:11 -0700312 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700313 if (ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800314 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(),
315 strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700316 return ihStatus;
317 }
318
Yi Jinb592e3b2018-02-01 15:17:04 -0800319 VLOG("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
320 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700321 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700322 if (err != NO_ERROR) {
323 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
324 return err;
325 }
326
327 return NO_ERROR;
328}
Yi Jin1a11fa12018-02-22 16:44:10 -0800329// ================================================================================
330GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
331 name = "gzip ";
332 name += filename;
333 va_list args;
334 va_start(args, filename);
335 mFilenames = varargs(filename, args);
336 va_end(args);
337}
Yi Jin0a3406f2017-06-22 19:23:11 -0700338
Yi Jin1a11fa12018-02-22 16:44:10 -0800339GZipSection::~GZipSection() {}
340
341status_t GZipSection::Execute(ReportRequestSet* requests) const {
342 // Reads the files in order, use the first available one.
343 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700344 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800345 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700346 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
347 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800348 break;
349 }
350 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
351 index++; // look at the next file.
352 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700353 VLOG("GZipSection is using file %s, fd=%d", mFilenames[index], fd.get());
354 if (fd.get() == -1) return -1;
Yi Jin1a11fa12018-02-22 16:44:10 -0800355
356 FdBuffer buffer;
357 Fpipe p2cPipe;
358 Fpipe c2pPipe;
359 // initiate pipes to pass data to/from gzip
360 if (!p2cPipe.init() || !c2pPipe.init()) {
361 ALOGW("GZipSection '%s' failed to setup pipes", this->name.string());
362 return -errno;
363 }
364
365 const char* gzipArgs[]{GZIP, NULL};
366 pid_t pid = fork_execute_cmd(GZIP, const_cast<char**>(gzipArgs), &p2cPipe, &c2pPipe);
367 if (pid == -1) {
368 ALOGW("GZipSection '%s' failed to fork", this->name.string());
369 return -errno;
370 }
371 // parent process
372
373 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
374 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
375 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
376 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
377 String8 usedFile(mFilenames[index]);
378 internalBuffer->writeRawVarint32(usedFile.size());
379 for (size_t i = 0; i < usedFile.size(); i++) {
380 internalBuffer->writeRawByte(mFilenames[index][i]);
381 }
382 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
383 WIRE_TYPE_LENGTH_DELIMITED);
384 size_t editPos = internalBuffer->wp()->pos();
385 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
386 size_t dataBeginAt = internalBuffer->wp()->pos();
387 VLOG("GZipSection '%s' editPos=%zd, dataBeginAt=%zd", this->name.string(), editPos,
388 dataBeginAt);
389
Yi Jin6355d2f2018-03-14 15:18:02 -0700390 status_t readStatus =
391 buffer.readProcessedDataInStream(&fd, &p2cPipe.writeFd(), &c2pPipe.readFd(),
392 this->timeoutMs, isSysfs(mFilenames[index]));
Yi Jin1a11fa12018-02-22 16:44:10 -0800393
394 if (readStatus != NO_ERROR || buffer.timedOut()) {
395 ALOGW("GZipSection '%s' failed to read data from gzip: %s, timedout: %s",
396 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
397 kill_child(pid);
398 return readStatus;
399 }
400
401 status_t gzipStatus = wait_child(pid);
402 if (gzipStatus != NO_ERROR) {
403 ALOGW("GZipSection '%s' abnormal child process: %s", this->name.string(),
404 strerror(-gzipStatus));
405 return gzipStatus;
406 }
407 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
408 size_t dataSize = buffer.size() - dataBeginAt;
409 internalBuffer->wp()->rewind()->move(editPos);
410 internalBuffer->writeRawVarint32(dataSize);
411 internalBuffer->copy(dataBeginAt, dataSize);
412 VLOG("GZipSection '%s' wrote %zd bytes in %d ms, dataSize=%zd", this->name.string(),
413 buffer.size(), (int)buffer.durationMs(), dataSize);
414 status_t err = write_report_requests(this->id, buffer, requests);
415 if (err != NO_ERROR) {
416 ALOGW("GZipSection '%s' failed writing: %s", this->name.string(), strerror(-err));
417 return err;
418 }
419
420 return NO_ERROR;
421}
Kweku Adamseadd1232018-02-05 16:45:13 -0800422
Yi Jin0a3406f2017-06-22 19:23:11 -0700423// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800424struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800425 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700426 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800427
428 // Lock protects these fields
429 mutex lock;
430 bool workerDone;
431 status_t workerError;
432
433 WorkerThreadData(const WorkerThreadSection* section);
434 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800435};
436
437WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700438 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800439
Yi Jinb592e3b2018-02-01 15:17:04 -0800440WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800441
442// ================================================================================
Kweku Adamseadd1232018-02-05 16:45:13 -0800443WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs)
444 : Section(id, timeoutMs) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800445
Yi Jinb592e3b2018-02-01 15:17:04 -0800446WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800447
Yi Jinb592e3b2018-02-01 15:17:04 -0800448static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800449 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700450 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800451
452 {
453 unique_lock<mutex> lock(data->lock);
454 data->workerDone = true;
455 data->workerError = err;
456 }
457
Yi Jin6355d2f2018-03-14 15:18:02 -0700458 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800459 data->decStrong(data->section);
460 // data might be gone now. don't use it after this point in this thread.
461 return NULL;
462}
463
Yi Jinb592e3b2018-02-01 15:17:04 -0800464status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800465 status_t err = NO_ERROR;
466 pthread_t thread;
467 pthread_attr_t attr;
468 bool timedOut = false;
469 FdBuffer buffer;
470
471 // Data shared between this thread and the worker thread.
472 sp<WorkerThreadData> data = new WorkerThreadData(this);
473
474 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700475 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800476 return -errno;
477 }
478
479 // The worker thread needs a reference and we can't let the count go to zero
480 // if that thread is slow to start.
481 data->incStrong(this);
482
483 // Create the thread
484 err = pthread_attr_init(&attr);
485 if (err != 0) {
486 return -err;
487 }
488 // TODO: Do we need to tweak thread priority?
489 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
490 if (err != 0) {
491 pthread_attr_destroy(&attr);
492 return -err;
493 }
494 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
495 if (err != 0) {
496 pthread_attr_destroy(&attr);
497 return -err;
498 }
499 pthread_attr_destroy(&attr);
500
501 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jin6355d2f2018-03-14 15:18:02 -0700502 err = buffer.read(&data->pipe.readFd(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800503 if (err != NO_ERROR) {
504 // TODO: Log this error into the incident report.
505 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800506 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800507 }
508
509 // Done with the read fd. The worker thread closes the write one so
510 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700511 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800512
513 // If the worker side is finished, then return its error (which may overwrite
514 // our possible error -- but it's more interesting anyway). If not, then we timed out.
515 {
516 unique_lock<mutex> lock(data->lock);
517 if (!data->workerDone) {
518 // We timed out
519 timedOut = true;
520 } else {
521 if (data->workerError != NO_ERROR) {
522 err = data->workerError;
523 // TODO: Log this error into the incident report.
524 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800525 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800526 }
527 }
528 }
529
530 if (timedOut || buffer.timedOut()) {
531 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
532 return NO_ERROR;
533 }
534
535 if (buffer.truncated()) {
536 // TODO: Log this into the incident report.
537 }
538
539 // TODO: There was an error with the command or buffering. Report that. For now
540 // just exit with a log messasge.
541 if (err != NO_ERROR) {
542 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
Yi Jinb592e3b2018-02-01 15:17:04 -0800543 strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800544 return NO_ERROR;
545 }
546
547 // Write the data that was collected
Yi Jinb592e3b2018-02-01 15:17:04 -0800548 VLOG("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
549 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700550 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800551 if (err != NO_ERROR) {
552 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
553 return err;
554 }
555
556 return NO_ERROR;
557}
558
559// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700560CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800561 : Section(id, timeoutMs) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800562 name = command;
Joe Onorato1754d742016-11-21 17:51:35 -0800563 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700564 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800565 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800566 va_end(args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700567}
Joe Onorato1754d742016-11-21 17:51:35 -0800568
Yi Jinb592e3b2018-02-01 15:17:04 -0800569CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800570 name = command;
Yi Jinb44f7d42017-07-21 12:12:59 -0700571 va_list args;
572 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);
575}
576
Yi Jinb592e3b2018-02-01 15:17:04 -0800577CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800578
Yi Jinb592e3b2018-02-01 15:17:04 -0800579status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700580 FdBuffer buffer;
581 Fpipe cmdPipe;
582 Fpipe ihPipe;
583
584 if (!cmdPipe.init() || !ihPipe.init()) {
585 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
586 return -errno;
587 }
588
589 pid_t cmdPid = fork();
590 if (cmdPid == -1) {
591 ALOGW("CommandSection '%s' failed to fork", this->name.string());
592 return -errno;
593 }
594 // child process to execute the command as root
595 if (cmdPid == 0) {
596 // replace command's stdout with ihPipe's write Fd
Yi Jin6355d2f2018-03-14 15:18:02 -0700597 if (dup2(cmdPipe.writeFd().get(), STDOUT_FILENO) != 1 || !ihPipe.close() ||
598 !cmdPipe.close()) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800599 ALOGW("CommandSection '%s' failed to set up stdout: %s", this->name.string(),
600 strerror(errno));
Yi Jinb44f7d42017-07-21 12:12:59 -0700601 _exit(EXIT_FAILURE);
602 }
Yi Jinb592e3b2018-02-01 15:17:04 -0800603 execvp(this->mCommand[0], (char* const*)this->mCommand);
604 int err = errno; // record command error code
605 ALOGW("CommandSection '%s' failed in executing command: %s", this->name.string(),
606 strerror(errno));
607 _exit(err); // exit with command error code
Yi Jinb44f7d42017-07-21 12:12:59 -0700608 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800609 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700610 if (ihPid == -1) {
611 ALOGW("CommandSection '%s' failed to fork", this->name.string());
612 return -errno;
613 }
614
Yi Jin6355d2f2018-03-14 15:18:02 -0700615 cmdPipe.writeFd().reset();
616 status_t readStatus = buffer.read(&ihPipe.readFd(), this->timeoutMs);
Yi Jinb44f7d42017-07-21 12:12:59 -0700617 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800618 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800619 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800620 kill_child(cmdPid);
621 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700622 return readStatus;
623 }
624
Kweku Adamseadd1232018-02-05 16:45:13 -0800625 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800626 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700627 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800628 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700629 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800630 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident "
631 "helper: %s",
632 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700633 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
634 }
635
Yi Jinb592e3b2018-02-01 15:17:04 -0800636 VLOG("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
637 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700638 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700639 if (err != NO_ERROR) {
640 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
641 return err;
642 }
Joe Onorato1754d742016-11-21 17:51:35 -0800643 return NO_ERROR;
644}
645
646// ================================================================================
647DumpsysSection::DumpsysSection(int id, const char* service, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800648 : WorkerThreadSection(id), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800649 name = "dumpsys ";
650 name += service;
651
652 va_list args;
653 va_start(args, service);
654 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700655 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800656 if (arg == NULL) {
657 break;
658 }
659 mArgs.add(String16(arg));
660 name += " ";
661 name += arg;
662 }
663 va_end(args);
664}
665
Yi Jinb592e3b2018-02-01 15:17:04 -0800666DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800667
Yi Jinb592e3b2018-02-01 15:17:04 -0800668status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800669 // checkService won't wait for the service to show up like getService will.
670 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700671
Joe Onorato1754d742016-11-21 17:51:35 -0800672 if (service == NULL) {
673 // Returning an error interrupts the entire incident report, so just
674 // log the failure.
675 // TODO: have a meta record inside the report that would log this
676 // failure inside the report, because the fact that we can't find
677 // the service is good data in and of itself. This is running in
678 // another thread so lock that carefully...
679 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
680 return NO_ERROR;
681 }
682
683 service->dump(pipeWriteFd, mArgs);
684
685 return NO_ERROR;
686}
Yi Jin3c034c92017-12-22 17:36:47 -0800687
688// ================================================================================
689// initialization only once in Section.cpp.
690map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
691
Yi Jinb592e3b2018-02-01 15:17:04 -0800692LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3c034c92017-12-22 17:36:47 -0800693 name += "logcat ";
694 name += android_log_id_to_name(logID);
695 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800696 case LOG_ID_EVENTS:
697 case LOG_ID_STATS:
698 case LOG_ID_SECURITY:
699 mBinary = true;
700 break;
701 default:
702 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800703 }
704}
705
Yi Jinb592e3b2018-02-01 15:17:04 -0800706LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800707
Yi Jinb592e3b2018-02-01 15:17:04 -0800708static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800709 while (len > 0) {
710 char c = buf[len - 1];
711 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
712 len--;
713 } else {
714 break;
715 }
716 }
717 return len;
718}
719
720static inline int32_t get4LE(uint8_t const* src) {
721 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
722}
723
Yi Jinb592e3b2018-02-01 15:17:04 -0800724status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800725 // Open log buffer and getting logs since last retrieved time if any.
726 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800727 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
728 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
729 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
730 gLastLogsRetrieved[mLogID], 0),
731 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800732
733 if (android_logger_open(loggers.get(), mLogID) == NULL) {
734 ALOGW("LogSection %s: Can't get logger.", this->name.string());
Kweku Adamseadd1232018-02-05 16:45:13 -0800735 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800736 }
737
738 log_msg msg;
739 log_time lastTimestamp(0);
740
Kweku Adamseadd1232018-02-05 16:45:13 -0800741 status_t err = NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800742 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800743 while (true) { // keeps reading until logd buffer is fully read.
Kweku Adamseadd1232018-02-05 16:45:13 -0800744 err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800745 // err = 0 - no content, unexpected connection drop or EOF.
746 // err = +ive number - size of retrieved data from logger
747 // err = -ive number, OS supplied error _except_ for -EAGAIN
748 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
749 if (err <= 0) {
750 if (err != -EAGAIN) {
751 ALOGE("LogSection %s: fails to read a log_msg.\n", this->name.string());
752 }
753 break;
754 }
755 if (mBinary) {
756 // remove the first uint32 which is tag's index in event log tags
757 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800758 msg.len() - sizeof(uint32_t));
759 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800760 android_log_list_element elem;
761
762 lastTimestamp.tv_sec = msg.entry_v1.sec;
763 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
764
765 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800766 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800767 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
768 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800769 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800770 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
771 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800772 proto.write(BinaryLogEntry::TAG_INDEX,
773 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800774 do {
775 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800776 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800777 switch (elem.type) {
778 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800779 proto.write(BinaryLogEntry::Elem::TYPE,
780 BinaryLogEntry::Elem::EVENT_TYPE_INT);
781 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800782 break;
783 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800784 proto.write(BinaryLogEntry::Elem::TYPE,
785 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
786 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800787 break;
788 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800789 proto.write(BinaryLogEntry::Elem::TYPE,
790 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800791 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
792 break;
793 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800794 proto.write(BinaryLogEntry::Elem::TYPE,
795 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800796 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
797 break;
798 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800799 proto.write(BinaryLogEntry::Elem::TYPE,
800 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800801 break;
802 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800803 proto.write(BinaryLogEntry::Elem::TYPE,
804 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800805 break;
806 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800807 proto.write(BinaryLogEntry::Elem::TYPE,
808 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800809 break;
810 }
811 proto.end(elemToken);
812 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
813 proto.end(token);
814 if (context) {
815 android_log_destroy(&context);
816 }
817 } else {
818 AndroidLogEntry entry;
819 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
820 if (err != NO_ERROR) {
821 ALOGE("LogSection %s: fails to process to an entry.\n", this->name.string());
822 break;
823 }
824 lastTimestamp.tv_sec = entry.tv_sec;
825 lastTimestamp.tv_nsec = entry.tv_nsec;
826
827 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800828 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800829 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
830 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
831 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
832 proto.write(TextLogEntry::UID, entry.uid);
833 proto.write(TextLogEntry::PID, entry.pid);
834 proto.write(TextLogEntry::TID, entry.tid);
835 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800836 proto.write(TextLogEntry::LOG, entry.message,
837 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800838 proto.end(token);
839 }
840 }
841 gLastLogsRetrieved[mLogID] = lastTimestamp;
842 proto.flush(pipeWriteFd);
843 return err;
844}
Kweku Adamseadd1232018-02-05 16:45:13 -0800845
846// ================================================================================
847
848TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
849 : WorkerThreadSection(id, timeoutMs), mType(type) {
850 name += "tombstone ";
851 name += type;
852}
853
854TombstoneSection::~TombstoneSection() {}
855
856status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
857 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
858 if (proc.get() == nullptr) {
859 ALOGE("opendir /proc failed: %s\n", strerror(errno));
860 return -errno;
861 }
862
863 const std::set<int> hal_pids = get_interesting_hal_pids();
864
865 ProtoOutputStream proto;
866 struct dirent* d;
867 status_t err = NO_ERROR;
868 while ((d = readdir(proc.get()))) {
869 int pid = atoi(d->d_name);
870 if (pid <= 0) {
871 continue;
872 }
873
874 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
875 std::string exe;
876 if (!android::base::Readlink(link_name, &exe)) {
877 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
878 continue;
879 }
880
881 bool is_java_process;
882 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
883 if (mType != "java") continue;
884 // Don't bother dumping backtraces for the zygote.
885 if (IsZygote(pid)) {
886 VLOG("Skipping Zygote");
887 continue;
888 }
889
890 is_java_process = true;
891 } else if (should_dump_native_traces(exe.c_str())) {
892 if (mType != "native") continue;
893 is_java_process = false;
894 } else if (hal_pids.find(pid) != hal_pids.end()) {
895 if (mType != "hal") continue;
896 is_java_process = false;
897 } else {
898 // Probably a native process we don't care about, continue.
899 VLOG("Skipping %d", pid);
900 continue;
901 }
902
903 Fpipe dumpPipe;
904 if (!dumpPipe.init()) {
905 ALOGW("TombstoneSection '%s' failed to setup dump pipe", this->name.string());
906 err = -errno;
907 break;
908 }
909
910 const uint64_t start = Nanotime();
911 pid_t child = fork();
912 if (child < 0) {
913 ALOGE("Failed to fork child process");
914 break;
915 } else if (child == 0) {
916 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700917 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800918 const int ret = dump_backtrace_to_file_timeout(
919 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700920 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800921 if (ret == -1) {
922 if (errno == 0) {
923 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
924 } else {
925 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
926 }
927 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700928 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800929 _exit(EXIT_SUCCESS);
930 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700931 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800932 // Parent process.
933 // Read from the pipe concurrently to avoid blocking the child.
934 FdBuffer buffer;
Yi Jin6355d2f2018-03-14 15:18:02 -0700935 err = buffer.readFully(&dumpPipe.readFd());
Kweku Adamseadd1232018-02-05 16:45:13 -0800936 if (err != NO_ERROR) {
937 ALOGW("TombstoneSection '%s' failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700938 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800939 break;
940 }
941
942 auto dump = std::make_unique<char[]>(buffer.size());
943 auto iterator = buffer.data();
944 int i = 0;
945 while (iterator.hasNext()) {
946 dump[i] = iterator.next();
947 i++;
948 }
949 long long token = proto.start(android::os::BackTraceProto::TRACES);
950 proto.write(android::os::BackTraceProto::Stack::PID, pid);
951 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
952 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
953 static_cast<long long>(Nanotime() - start));
954 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700955 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800956 }
957
958 proto.flush(pipeWriteFd);
959 return err;
960}