blob: 87799b38906c47876cd39b8417c574739be72ba7 [file] [log] [blame]
Joe Onorato1754d742016-11-21 17:51:35 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Yi Jin4e843102018-02-14 15:36:18 -080016#define DEBUG false
Yi Jinb592e3b2018-02-01 15:17:04 -080017#include "Log.h"
Joe Onorato1754d742016-11-21 17:51:35 -080018
19#include "Section.h"
Yi Jin99c248f2017-08-25 18:11:58 -070020
Kweku Adamseadd1232018-02-05 16:45:13 -080021#include <dirent.h>
22#include <errno.h>
Yi Jin3c034c92017-12-22 17:36:47 -080023
Yi Jin3c034c92017-12-22 17:36:47 -080024#include <mutex>
Kweku Adamseadd1232018-02-05 16:45:13 -080025#include <set>
Joe Onorato1754d742016-11-21 17:51:35 -080026
Yi Jinb592e3b2018-02-01 15:17:04 -080027#include <android-base/file.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080028#include <android-base/stringprintf.h>
Yi Jinc23fad22017-09-15 17:24:59 -070029#include <android/util/protobuf.h>
Joe Onorato1754d742016-11-21 17:51:35 -080030#include <binder/IServiceManager.h>
Kweku Adamseadd1232018-02-05 16:45:13 -080031#include <debuggerd/client.h>
32#include <dumputils/dump_utils.h>
Yi Jin3c034c92017-12-22 17:36:47 -080033#include <log/log_event_list.h>
Yi Jin3c034c92017-12-22 17:36:47 -080034#include <log/log_read.h>
Yi Jinb592e3b2018-02-01 15:17:04 -080035#include <log/logprint.h>
Yi Jin3c034c92017-12-22 17:36:47 -080036#include <private/android_logger.h>
37
38#include "FdBuffer.h"
Yi Jin3c034c92017-12-22 17:36:47 -080039#include "Privacy.h"
40#include "PrivacyBuffer.h"
Kweku Adamseadd1232018-02-05 16:45:13 -080041#include "frameworks/base/core/proto/android/os/backtrace.proto.h"
Yi Jin1a11fa12018-02-22 16:44:10 -080042#include "frameworks/base/core/proto/android/os/data.proto.h"
Yi Jinb592e3b2018-02-01 15:17:04 -080043#include "frameworks/base/core/proto/android/util/log.proto.h"
44#include "incidentd_util.h"
Joe Onorato1754d742016-11-21 17:51:35 -080045
Yi Jin6cacbcb2018-03-30 14:04:52 -070046namespace android {
47namespace os {
48namespace incidentd {
49
Yi Jinb592e3b2018-02-01 15:17:04 -080050using namespace android::base;
Yi Jinc23fad22017-09-15 17:24:59 -070051using namespace android::util;
Joe Onorato1754d742016-11-21 17:51:35 -080052
Yi Jinc23fad22017-09-15 17:24:59 -070053// special section ids
54const int FIELD_ID_INCIDENT_HEADER = 1;
Yi Jin329130b2018-02-09 16:47:47 -080055const int FIELD_ID_INCIDENT_METADATA = 2;
Yi Jinc23fad22017-09-15 17:24:59 -070056
57// incident section parameters
Yi Jin3c034c92017-12-22 17:36:47 -080058const char INCIDENT_HELPER[] = "/system/bin/incident_helper";
Yi Jinc36e91d2018-03-08 11:25:58 -080059const char* GZIP[] = {"/system/bin/gzip", NULL};
Yi Jinb44f7d42017-07-21 12:12:59 -070060
Yi Jin1a11fa12018-02-22 16:44:10 -080061static pid_t fork_execute_incident_helper(const int id, Fpipe* p2cPipe, Fpipe* c2pPipe) {
Yi Jinb592e3b2018-02-01 15:17:04 -080062 const char* ihArgs[]{INCIDENT_HELPER, "-s", String8::format("%d", id).string(), NULL};
Yi Jinc36e91d2018-03-08 11:25:58 -080063 return fork_execute_cmd(const_cast<char**>(ihArgs), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -070064}
65
Yi Jin99c248f2017-08-25 18:11:58 -070066// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -080067static status_t write_section_header(int fd, int sectionId, size_t size) {
Yi Jin99c248f2017-08-25 18:11:58 -070068 uint8_t buf[20];
Yi Jinb592e3b2018-02-01 15:17:04 -080069 uint8_t* p = write_length_delimited_tag_header(buf, sectionId, size);
70 return WriteFully(fd, buf, p - buf) ? NO_ERROR : -errno;
Yi Jin99c248f2017-08-25 18:11:58 -070071}
72
Yi Jin98ce8102018-04-12 11:15:39 -070073static void write_section_stats(IncidentMetadata::SectionStats* stats, const FdBuffer& buffer) {
74 stats->set_dump_size_bytes(buffer.data().size());
75 stats->set_dump_duration_ms(buffer.durationMs());
76 stats->set_timed_out(buffer.timedOut());
77 stats->set_is_truncated(buffer.truncated());
78}
79
Kweku Adamseadd1232018-02-05 16:45:13 -080080// Reads data from FdBuffer and writes it to the requests file descriptor.
Yi Jinb592e3b2018-02-01 15:17:04 -080081static status_t write_report_requests(const int id, const FdBuffer& buffer,
82 ReportRequestSet* requests) {
Yi Jin0f047162017-09-05 13:44:22 -070083 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -070084 EncodedBuffer::iterator data = buffer.data();
85 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -070086 int writeable = 0;
87
Yi Jin0f047162017-09-05 13:44:22 -070088 // The streaming ones, group requests by spec in order to save unnecessary strip operations
89 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -080090 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -070091 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -070092 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -070093 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -070094 }
Yi Jin3ec5cc72018-01-26 13:42:43 -080095 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -070096 requestsBySpec[spec].push_back(request);
97 }
98
Yi Jin3ec5cc72018-01-26 13:42:43 -080099 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -0700100 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700101 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800102 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700103 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700104
Yi Jin3ec5cc72018-01-26 13:42:43 -0800105 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700106 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700107 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800108 if (err != NO_ERROR) {
109 request->err = err;
110 continue;
111 }
Yi Jinc23fad22017-09-15 17:24:59 -0700112 err = privacyBuffer.flush(request->fd);
Yi Jinb592e3b2018-02-01 15:17:04 -0800113 if (err != NO_ERROR) {
114 request->err = err;
115 continue;
116 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700117 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800118 VLOG("Section %d flushed %zu bytes to fd %d with spec %d", id, privacyBuffer.size(),
119 request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700120 }
Yi Jinc23fad22017-09-15 17:24:59 -0700121 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700122 }
123
124 // The dropbox file
125 if (requests->mainFd() >= 0) {
Yi Jin329130b2018-02-09 16:47:47 -0800126 PrivacySpec spec = PrivacySpec::new_spec(requests->mainDest());
Yi Jin3ec5cc72018-01-26 13:42:43 -0800127 err = privacyBuffer.strip(spec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800128 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700129 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700130
Yi Jinc23fad22017-09-15 17:24:59 -0700131 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800132 if (err != NO_ERROR) {
133 requests->setMainFd(-1);
134 goto DONE;
135 }
Yi Jinc23fad22017-09-15 17:24:59 -0700136 err = privacyBuffer.flush(requests->mainFd());
Yi Jinb592e3b2018-02-01 15:17:04 -0800137 if (err != NO_ERROR) {
138 requests->setMainFd(-1);
139 goto DONE;
140 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700141 writeable++;
Yi Jinb592e3b2018-02-01 15:17:04 -0800142 VLOG("Section %d flushed %zu bytes to dropbox %d with spec %d", id, privacyBuffer.size(),
143 requests->mainFd(), spec.dest);
Yi Jin98ce8102018-04-12 11:15:39 -0700144 // Reports bytes of the section uploaded via dropbox after filtering.
145 requests->sectionStats(id)->set_report_size_bytes(privacyBuffer.size());
Yi Jin99c248f2017-08-25 18:11:58 -0700146 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700147
148DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700149 // only returns error if there is no fd to write to.
150 return writeable > 0 ? NO_ERROR : err;
151}
152
153// ================================================================================
Kweku Adamse04ef772018-06-13 12:24:38 -0700154Section::Section(int i, int64_t timeoutMs, bool userdebugAndEngOnly)
Kweku Adams3d160912018-05-07 11:26:27 -0700155 : id(i),
156 timeoutMs(timeoutMs),
Kweku Adamse04ef772018-06-13 12:24:38 -0700157 userdebugAndEngOnly(userdebugAndEngOnly) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800158
Yi Jinb592e3b2018-02-01 15:17:04 -0800159Section::~Section() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800160
Joe Onorato1754d742016-11-21 17:51:35 -0800161// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800162HeaderSection::HeaderSection() : Section(FIELD_ID_INCIDENT_HEADER, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700163
Yi Jinb592e3b2018-02-01 15:17:04 -0800164HeaderSection::~HeaderSection() {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700165
Yi Jinb592e3b2018-02-01 15:17:04 -0800166status_t HeaderSection::Execute(ReportRequestSet* requests) const {
167 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700168 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800169 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700170
Yi Jinb592e3b2018-02-01 15:17:04 -0800171 for (vector<vector<uint8_t>>::const_iterator buf = headers.begin(); buf != headers.end();
172 buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700173 if (buf->empty()) continue;
174
175 // So the idea is only requests with negative fd are written to dropbox file.
176 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800177 write_section_header(fd, id, buf->size());
Yi Jinb592e3b2018-02-01 15:17:04 -0800178 WriteFully(fd, (uint8_t const*)buf->data(), buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700179 // If there was an error now, there will be an error later and we will remove
180 // it from the list then.
181 }
182 }
183 return NO_ERROR;
184}
Yi Jin329130b2018-02-09 16:47:47 -0800185// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800186MetadataSection::MetadataSection() : Section(FIELD_ID_INCIDENT_METADATA, 0) {}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700187
Yi Jinb592e3b2018-02-01 15:17:04 -0800188MetadataSection::~MetadataSection() {}
Yi Jin329130b2018-02-09 16:47:47 -0800189
Yi Jinb592e3b2018-02-01 15:17:04 -0800190status_t MetadataSection::Execute(ReportRequestSet* requests) const {
Yi Jin86dce412018-03-07 11:36:57 -0800191 ProtoOutputStream proto;
192 IncidentMetadata metadata = requests->metadata();
193 proto.write(FIELD_TYPE_ENUM | IncidentMetadata::kDestFieldNumber, metadata.dest());
194 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::kRequestSizeFieldNumber,
195 metadata.request_size());
196 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::kUseDropboxFieldNumber, metadata.use_dropbox());
197 for (auto iter = requests->allSectionStats().begin(); iter != requests->allSectionStats().end();
198 iter++) {
199 IncidentMetadata::SectionStats stats = iter->second;
200 uint64_t token = proto.start(FIELD_TYPE_MESSAGE | IncidentMetadata::kSectionsFieldNumber);
201 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kIdFieldNumber, stats.id());
202 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kSuccessFieldNumber,
203 stats.success());
204 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kReportSizeBytesFieldNumber,
205 stats.report_size_bytes());
206 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kExecDurationMsFieldNumber,
207 stats.exec_duration_ms());
208 proto.write(FIELD_TYPE_INT32 | IncidentMetadata::SectionStats::kDumpSizeBytesFieldNumber,
209 stats.dump_size_bytes());
210 proto.write(FIELD_TYPE_INT64 | IncidentMetadata::SectionStats::kDumpDurationMsFieldNumber,
211 stats.dump_duration_ms());
212 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kTimedOutFieldNumber,
213 stats.timed_out());
214 proto.write(FIELD_TYPE_BOOL | IncidentMetadata::SectionStats::kIsTruncatedFieldNumber,
215 stats.is_truncated());
216 proto.end(token);
217 }
218
Yi Jinb592e3b2018-02-01 15:17:04 -0800219 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
Yi Jin329130b2018-02-09 16:47:47 -0800220 const sp<ReportRequest> request = *it;
Yi Jin86dce412018-03-07 11:36:57 -0800221 if (request->fd < 0 || request->err != NO_ERROR) {
Yi Jin329130b2018-02-09 16:47:47 -0800222 continue;
223 }
Yi Jin86dce412018-03-07 11:36:57 -0800224 write_section_header(request->fd, id, proto.size());
225 if (!proto.flush(request->fd)) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800226 ALOGW("Failed to write metadata to fd %d", request->fd);
227 // we don't fail if we can't write to a single request's fd.
228 }
Yi Jin329130b2018-02-09 16:47:47 -0800229 }
Yi Jin86dce412018-03-07 11:36:57 -0800230 if (requests->mainFd() >= 0) {
231 write_section_header(requests->mainFd(), id, proto.size());
232 if (!proto.flush(requests->mainFd())) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800233 ALOGW("Failed to write metadata to dropbox fd %d", requests->mainFd());
234 return -1;
235 }
Yi Jin329130b2018-02-09 16:47:47 -0800236 }
237 return NO_ERROR;
238}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700239// ================================================================================
Yi Jin1a11fa12018-02-22 16:44:10 -0800240static inline bool isSysfs(const char* filename) { return strncmp(filename, "/sys/", 5) == 0; }
241
Kweku Adamse04ef772018-06-13 12:24:38 -0700242FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
243 : Section(id, timeoutMs, false), mFilename(filename) {
Yi Jin3be0b432018-04-20 17:08:11 -0700244 name = "file ";
245 name += filename;
Yi Jin1a11fa12018-02-22 16:44:10 -0800246 mIsSysfs = isSysfs(filename);
Yi Jin0a3406f2017-06-22 19:23:11 -0700247}
248
249FileSection::~FileSection() {}
250
Yi Jinb592e3b2018-02-01 15:17:04 -0800251status_t FileSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700252 // read from mFilename first, make sure the file is available
253 // add O_CLOEXEC to make sure it is closed when exec incident helper
Yi Jin6355d2f2018-03-14 15:18:02 -0700254 unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
255 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700256 ALOGW("[%s] failed to open file", this->name.string());
Kweku Adamse04ef772018-06-13 12:24:38 -0700257 // There may be some devices/architectures that won't have the file.
258 // Just return here without an error.
259 return NO_ERROR;
Yi Jin0a3406f2017-06-22 19:23:11 -0700260 }
261
Yi Jinb44f7d42017-07-21 12:12:59 -0700262 FdBuffer buffer;
263 Fpipe p2cPipe;
264 Fpipe c2pPipe;
265 // initiate pipes to pass data to/from incident_helper
266 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700267 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700268 return -errno;
269 }
270
Yi Jin1a11fa12018-02-22 16:44:10 -0800271 pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700272 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700273 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700274 return -errno;
275 }
276
277 // parent process
Yi Jine3dab2d2018-03-22 16:56:39 -0700278 status_t readStatus = buffer.readProcessedDataInStream(fd.get(), std::move(p2cPipe.writeFd()),
279 std::move(c2pPipe.readFd()),
280 this->timeoutMs, mIsSysfs);
Yi Jin98ce8102018-04-12 11:15:39 -0700281 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700282 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700283 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800284 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800285 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700286 return readStatus;
287 }
288
Yi Jinedfd5bb2017-09-06 17:09:11 -0700289 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700290 if (ihStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700291 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700292 return ihStatus;
293 }
294
Yi Jin3be0b432018-04-20 17:08:11 -0700295 return write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700296}
Yi Jin1a11fa12018-02-22 16:44:10 -0800297// ================================================================================
298GZipSection::GZipSection(int id, const char* filename, ...) : Section(id) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800299 va_list args;
300 va_start(args, filename);
301 mFilenames = varargs(filename, args);
302 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800303 name = "gzip";
304 for (int i = 0; mFilenames[i] != NULL; i++) {
305 name += " ";
306 name += mFilenames[i];
307 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800308}
Yi Jin0a3406f2017-06-22 19:23:11 -0700309
Yi Jin480de782018-04-06 15:37:36 -0700310GZipSection::~GZipSection() { free(mFilenames); }
Yi Jin1a11fa12018-02-22 16:44:10 -0800311
312status_t GZipSection::Execute(ReportRequestSet* requests) const {
313 // Reads the files in order, use the first available one.
314 int index = 0;
Yi Jin6355d2f2018-03-14 15:18:02 -0700315 unique_fd fd;
Yi Jin1a11fa12018-02-22 16:44:10 -0800316 while (mFilenames[index] != NULL) {
Yi Jin6355d2f2018-03-14 15:18:02 -0700317 fd.reset(open(mFilenames[index], O_RDONLY | O_CLOEXEC));
318 if (fd.get() != -1) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800319 break;
320 }
321 ALOGW("GZipSection failed to open file %s", mFilenames[index]);
322 index++; // look at the next file.
323 }
Yi Jinc858e272018-03-28 15:32:50 -0700324 if (fd.get() == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700325 ALOGW("[%s] can't open all the files", this->name.string());
Yi Jin6cacbcb2018-03-30 14:04:52 -0700326 return NO_ERROR; // e.g. LAST_KMSG will reach here in user build.
Yi Jinc858e272018-03-28 15:32:50 -0700327 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800328 FdBuffer buffer;
329 Fpipe p2cPipe;
330 Fpipe c2pPipe;
331 // initiate pipes to pass data to/from gzip
332 if (!p2cPipe.init() || !c2pPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700333 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800334 return -errno;
335 }
336
Yi Jinc36e91d2018-03-08 11:25:58 -0800337 pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
Yi Jin1a11fa12018-02-22 16:44:10 -0800338 if (pid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700339 ALOGW("[%s] failed to fork", this->name.string());
Yi Jin1a11fa12018-02-22 16:44:10 -0800340 return -errno;
341 }
342 // parent process
343
344 // construct Fdbuffer to output GZippedfileProto, the reason to do this instead of using
345 // ProtoOutputStream is to avoid allocation of another buffer inside ProtoOutputStream.
346 EncodedBuffer* internalBuffer = buffer.getInternalBuffer();
347 internalBuffer->writeHeader((uint32_t)GZippedFileProto::FILENAME, WIRE_TYPE_LENGTH_DELIMITED);
Yi Jina9635e42018-03-23 12:05:32 -0700348 size_t fileLen = strlen(mFilenames[index]);
349 internalBuffer->writeRawVarint32(fileLen);
350 for (size_t i = 0; i < fileLen; i++) {
Yi Jin1a11fa12018-02-22 16:44:10 -0800351 internalBuffer->writeRawByte(mFilenames[index][i]);
352 }
353 internalBuffer->writeHeader((uint32_t)GZippedFileProto::GZIPPED_DATA,
354 WIRE_TYPE_LENGTH_DELIMITED);
355 size_t editPos = internalBuffer->wp()->pos();
356 internalBuffer->wp()->move(8); // reserve 8 bytes for the varint of the data size.
357 size_t dataBeginAt = internalBuffer->wp()->pos();
Yi Jin3be0b432018-04-20 17:08:11 -0700358 VLOG("[%s] editPos=%zu, dataBeginAt=%zu", this->name.string(), editPos, dataBeginAt);
Yi Jin1a11fa12018-02-22 16:44:10 -0800359
Yi Jine3dab2d2018-03-22 16:56:39 -0700360 status_t readStatus = buffer.readProcessedDataInStream(
361 fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
362 isSysfs(mFilenames[index]));
Yi Jin98ce8102018-04-12 11:15:39 -0700363 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jin1a11fa12018-02-22 16:44:10 -0800364 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700365 ALOGW("[%s] failed to read data from gzip: %s, timedout: %s", this->name.string(),
366 strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin1a11fa12018-02-22 16:44:10 -0800367 kill_child(pid);
368 return readStatus;
369 }
370
371 status_t gzipStatus = wait_child(pid);
372 if (gzipStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700373 ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-gzipStatus));
Yi Jin1a11fa12018-02-22 16:44:10 -0800374 return gzipStatus;
375 }
376 // Revisit the actual size from gzip result and edit the internal buffer accordingly.
377 size_t dataSize = buffer.size() - dataBeginAt;
378 internalBuffer->wp()->rewind()->move(editPos);
379 internalBuffer->writeRawVarint32(dataSize);
380 internalBuffer->copy(dataBeginAt, dataSize);
Yi Jin1a11fa12018-02-22 16:44:10 -0800381
Yi Jin3be0b432018-04-20 17:08:11 -0700382 return write_report_requests(this->id, buffer, requests);
Yi Jin1a11fa12018-02-22 16:44:10 -0800383}
Kweku Adamseadd1232018-02-05 16:45:13 -0800384
Yi Jin0a3406f2017-06-22 19:23:11 -0700385// ================================================================================
Yi Jinb592e3b2018-02-01 15:17:04 -0800386struct WorkerThreadData : public virtual RefBase {
Joe Onorato1754d742016-11-21 17:51:35 -0800387 const WorkerThreadSection* section;
Yi Jin6355d2f2018-03-14 15:18:02 -0700388 Fpipe pipe;
Joe Onorato1754d742016-11-21 17:51:35 -0800389
390 // Lock protects these fields
391 mutex lock;
392 bool workerDone;
393 status_t workerError;
394
395 WorkerThreadData(const WorkerThreadSection* section);
396 virtual ~WorkerThreadData();
Joe Onorato1754d742016-11-21 17:51:35 -0800397};
398
399WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
Yi Jin6355d2f2018-03-14 15:18:02 -0700400 : section(sec), workerDone(false), workerError(NO_ERROR) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800401
Yi Jinb592e3b2018-02-01 15:17:04 -0800402WorkerThreadData::~WorkerThreadData() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800403
404// ================================================================================
Kweku Adams3d160912018-05-07 11:26:27 -0700405WorkerThreadSection::WorkerThreadSection(int id, const int64_t timeoutMs, bool userdebugAndEngOnly)
406 : Section(id, timeoutMs, userdebugAndEngOnly) {}
Joe Onorato1754d742016-11-21 17:51:35 -0800407
Yi Jinb592e3b2018-02-01 15:17:04 -0800408WorkerThreadSection::~WorkerThreadSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800409
Yi Jinb592e3b2018-02-01 15:17:04 -0800410static void* worker_thread_func(void* cookie) {
Joe Onorato1754d742016-11-21 17:51:35 -0800411 WorkerThreadData* data = (WorkerThreadData*)cookie;
Yi Jin6355d2f2018-03-14 15:18:02 -0700412 status_t err = data->section->BlockingCall(data->pipe.writeFd().get());
Joe Onorato1754d742016-11-21 17:51:35 -0800413
414 {
415 unique_lock<mutex> lock(data->lock);
416 data->workerDone = true;
417 data->workerError = err;
418 }
419
Yi Jin6355d2f2018-03-14 15:18:02 -0700420 data->pipe.writeFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800421 data->decStrong(data->section);
422 // data might be gone now. don't use it after this point in this thread.
423 return NULL;
424}
425
Yi Jinb592e3b2018-02-01 15:17:04 -0800426status_t WorkerThreadSection::Execute(ReportRequestSet* requests) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800427 status_t err = NO_ERROR;
428 pthread_t thread;
429 pthread_attr_t attr;
430 bool timedOut = false;
431 FdBuffer buffer;
432
433 // Data shared between this thread and the worker thread.
434 sp<WorkerThreadData> data = new WorkerThreadData(this);
435
436 // Create the pipe
Yi Jin6355d2f2018-03-14 15:18:02 -0700437 if (!data->pipe.init()) {
Joe Onorato1754d742016-11-21 17:51:35 -0800438 return -errno;
439 }
440
441 // The worker thread needs a reference and we can't let the count go to zero
442 // if that thread is slow to start.
443 data->incStrong(this);
444
445 // Create the thread
446 err = pthread_attr_init(&attr);
447 if (err != 0) {
448 return -err;
449 }
450 // TODO: Do we need to tweak thread priority?
451 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
452 if (err != 0) {
453 pthread_attr_destroy(&attr);
454 return -err;
455 }
456 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
457 if (err != 0) {
458 pthread_attr_destroy(&attr);
459 return -err;
460 }
461 pthread_attr_destroy(&attr);
462
463 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jine3dab2d2018-03-22 16:56:39 -0700464 err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800465 if (err != NO_ERROR) {
466 // TODO: Log this error into the incident report.
Yi Jin3be0b432018-04-20 17:08:11 -0700467 ALOGW("[%s] reader failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800468 }
469
470 // Done with the read fd. The worker thread closes the write one so
471 // we never race and get here first.
Yi Jin6355d2f2018-03-14 15:18:02 -0700472 data->pipe.readFd().reset();
Joe Onorato1754d742016-11-21 17:51:35 -0800473
474 // If the worker side is finished, then return its error (which may overwrite
475 // our possible error -- but it's more interesting anyway). If not, then we timed out.
476 {
477 unique_lock<mutex> lock(data->lock);
478 if (!data->workerDone) {
479 // We timed out
480 timedOut = true;
481 } else {
482 if (data->workerError != NO_ERROR) {
483 err = data->workerError;
484 // TODO: Log this error into the incident report.
Yi Jin3be0b432018-04-20 17:08:11 -0700485 ALOGW("[%s] worker failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800486 }
487 }
488 }
Yi Jin98ce8102018-04-12 11:15:39 -0700489 write_section_stats(requests->sectionStats(this->id), buffer);
Joe Onorato1754d742016-11-21 17:51:35 -0800490 if (timedOut || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700491 ALOGW("[%s] timed out", this->name.string());
Joe Onorato1754d742016-11-21 17:51:35 -0800492 return NO_ERROR;
493 }
494
Joe Onorato1754d742016-11-21 17:51:35 -0800495 // TODO: There was an error with the command or buffering. Report that. For now
496 // just exit with a log messasge.
497 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700498 ALOGW("[%s] failed with error '%s'", this->name.string(), strerror(-err));
Joe Onorato1754d742016-11-21 17:51:35 -0800499 return NO_ERROR;
500 }
501
502 // Write the data that was collected
Yi Jin3be0b432018-04-20 17:08:11 -0700503 return write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800504}
505
506// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700507CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinb592e3b2018-02-01 15:17:04 -0800508 : Section(id, timeoutMs) {
Joe Onorato1754d742016-11-21 17:51:35 -0800509 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700510 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800511 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800512 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800513 name = "cmd";
514 for (int i = 0; mCommand[i] != NULL; i++) {
515 name += " ";
516 name += mCommand[i];
517 }
Yi Jinb44f7d42017-07-21 12:12:59 -0700518}
Joe Onorato1754d742016-11-21 17:51:35 -0800519
Yi Jinb592e3b2018-02-01 15:17:04 -0800520CommandSection::CommandSection(int id, const char* command, ...) : Section(id) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700521 va_list args;
522 va_start(args, command);
Yi Jin1a11fa12018-02-22 16:44:10 -0800523 mCommand = varargs(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800524 va_end(args);
Yi Jinc36e91d2018-03-08 11:25:58 -0800525 name = "cmd";
526 for (int i = 0; mCommand[i] != NULL; i++) {
527 name += " ";
528 name += mCommand[i];
529 }
Joe Onorato1754d742016-11-21 17:51:35 -0800530}
531
Yi Jinb592e3b2018-02-01 15:17:04 -0800532CommandSection::~CommandSection() { free(mCommand); }
Joe Onorato1754d742016-11-21 17:51:35 -0800533
Yi Jinb592e3b2018-02-01 15:17:04 -0800534status_t CommandSection::Execute(ReportRequestSet* requests) const {
Yi Jinb44f7d42017-07-21 12:12:59 -0700535 FdBuffer buffer;
536 Fpipe cmdPipe;
537 Fpipe ihPipe;
538
539 if (!cmdPipe.init() || !ihPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700540 ALOGW("[%s] failed to setup pipes", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700541 return -errno;
542 }
543
Yi Jinc36e91d2018-03-08 11:25:58 -0800544 pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700545 if (cmdPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700546 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700547 return -errno;
548 }
Yi Jin1a11fa12018-02-22 16:44:10 -0800549 pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700550 if (ihPid == -1) {
Yi Jin3be0b432018-04-20 17:08:11 -0700551 ALOGW("[%s] failed to fork", this->name.string());
Yi Jinb44f7d42017-07-21 12:12:59 -0700552 return -errno;
553 }
554
Yi Jin6355d2f2018-03-14 15:18:02 -0700555 cmdPipe.writeFd().reset();
Yi Jine3dab2d2018-03-22 16:56:39 -0700556 status_t readStatus = buffer.read(ihPipe.readFd().get(), this->timeoutMs);
Yi Jin98ce8102018-04-12 11:15:39 -0700557 write_section_stats(requests->sectionStats(this->id), buffer);
Yi Jinb44f7d42017-07-21 12:12:59 -0700558 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700559 ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
Yi Jinb592e3b2018-02-01 15:17:04 -0800560 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
Yi Jin4bab3a12018-01-10 16:50:59 -0800561 kill_child(cmdPid);
562 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700563 return readStatus;
564 }
565
Kweku Adamseadd1232018-02-05 16:45:13 -0800566 // Waiting for command here has one trade-off: the failed status of command won't be detected
Yi Jin1a11fa12018-02-22 16:44:10 -0800567 // until buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700568 status_t cmdStatus = wait_child(cmdPid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800569 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700570 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700571 ALOGW("[%s] abnormal child processes, return status: command: %s, incident "
Yi Jinb592e3b2018-02-01 15:17:04 -0800572 "helper: %s",
573 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
Yi Jinb44f7d42017-07-21 12:12:59 -0700574 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
575 }
576
Yi Jin3be0b432018-04-20 17:08:11 -0700577 return write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800578}
579
580// ================================================================================
Kweku Adams3d160912018-05-07 11:26:27 -0700581DumpsysSection::DumpsysSection(int id, bool userdebugAndEngOnly, const char* service, ...)
582 : WorkerThreadSection(id, REMOTE_CALL_TIMEOUT_MS, userdebugAndEngOnly), mService(service) {
Joe Onorato1754d742016-11-21 17:51:35 -0800583 name = "dumpsys ";
584 name += service;
585
586 va_list args;
587 va_start(args, service);
588 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700589 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800590 if (arg == NULL) {
591 break;
592 }
593 mArgs.add(String16(arg));
594 name += " ";
595 name += arg;
596 }
597 va_end(args);
598}
599
Yi Jinb592e3b2018-02-01 15:17:04 -0800600DumpsysSection::~DumpsysSection() {}
Joe Onorato1754d742016-11-21 17:51:35 -0800601
Yi Jinb592e3b2018-02-01 15:17:04 -0800602status_t DumpsysSection::BlockingCall(int pipeWriteFd) const {
Joe Onorato1754d742016-11-21 17:51:35 -0800603 // checkService won't wait for the service to show up like getService will.
604 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700605
Joe Onorato1754d742016-11-21 17:51:35 -0800606 if (service == NULL) {
607 // Returning an error interrupts the entire incident report, so just
608 // log the failure.
609 // TODO: have a meta record inside the report that would log this
610 // failure inside the report, because the fact that we can't find
611 // the service is good data in and of itself. This is running in
612 // another thread so lock that carefully...
613 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
614 return NO_ERROR;
615 }
616
617 service->dump(pipeWriteFd, mArgs);
618
619 return NO_ERROR;
620}
Yi Jin3c034c92017-12-22 17:36:47 -0800621
622// ================================================================================
623// initialization only once in Section.cpp.
624map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
625
Yi Jinb592e3b2018-02-01 15:17:04 -0800626LogSection::LogSection(int id, log_id_t logID) : WorkerThreadSection(id), mLogID(logID) {
Yi Jin3be0b432018-04-20 17:08:11 -0700627 name = "logcat ";
Yi Jin3c034c92017-12-22 17:36:47 -0800628 name += android_log_id_to_name(logID);
629 switch (logID) {
Yi Jinb592e3b2018-02-01 15:17:04 -0800630 case LOG_ID_EVENTS:
631 case LOG_ID_STATS:
632 case LOG_ID_SECURITY:
633 mBinary = true;
634 break;
635 default:
636 mBinary = false;
Yi Jin3c034c92017-12-22 17:36:47 -0800637 }
638}
639
Yi Jinb592e3b2018-02-01 15:17:04 -0800640LogSection::~LogSection() {}
Yi Jin3c034c92017-12-22 17:36:47 -0800641
Yi Jinb592e3b2018-02-01 15:17:04 -0800642static size_t trimTail(char const* buf, size_t len) {
Yi Jin3c034c92017-12-22 17:36:47 -0800643 while (len > 0) {
644 char c = buf[len - 1];
645 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
646 len--;
647 } else {
648 break;
649 }
650 }
651 return len;
652}
653
654static inline int32_t get4LE(uint8_t const* src) {
655 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
656}
657
Yi Jinb592e3b2018-02-01 15:17:04 -0800658status_t LogSection::BlockingCall(int pipeWriteFd) const {
Yi Jin3c034c92017-12-22 17:36:47 -0800659 // Open log buffer and getting logs since last retrieved time if any.
660 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
Yi Jinb592e3b2018-02-01 15:17:04 -0800661 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end()
662 ? android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0)
663 : android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
664 gLastLogsRetrieved[mLogID], 0),
665 android_logger_list_free);
Yi Jin3c034c92017-12-22 17:36:47 -0800666
667 if (android_logger_open(loggers.get(), mLogID) == NULL) {
Yi Jin3be0b432018-04-20 17:08:11 -0700668 ALOGE("[%s] Can't get logger.", this->name.string());
Yi Jin83fb1d52018-03-16 12:03:53 -0700669 return -1;
Yi Jin3c034c92017-12-22 17:36:47 -0800670 }
671
672 log_msg msg;
673 log_time lastTimestamp(0);
674
675 ProtoOutputStream proto;
Yi Jinb592e3b2018-02-01 15:17:04 -0800676 while (true) { // keeps reading until logd buffer is fully read.
Yi Jin83fb1d52018-03-16 12:03:53 -0700677 status_t err = android_logger_list_read(loggers.get(), &msg);
Yi Jin3c034c92017-12-22 17:36:47 -0800678 // err = 0 - no content, unexpected connection drop or EOF.
679 // err = +ive number - size of retrieved data from logger
680 // err = -ive number, OS supplied error _except_ for -EAGAIN
681 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
682 if (err <= 0) {
683 if (err != -EAGAIN) {
Yi Jin3be0b432018-04-20 17:08:11 -0700684 ALOGW("[%s] fails to read a log_msg.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800685 }
Yi Jin83fb1d52018-03-16 12:03:53 -0700686 // dump previous logs and don't consider this error a failure.
Yi Jin3c034c92017-12-22 17:36:47 -0800687 break;
688 }
689 if (mBinary) {
690 // remove the first uint32 which is tag's index in event log tags
691 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
Yi Jinb592e3b2018-02-01 15:17:04 -0800692 msg.len() - sizeof(uint32_t));
693 ;
Yi Jin3c034c92017-12-22 17:36:47 -0800694 android_log_list_element elem;
695
696 lastTimestamp.tv_sec = msg.entry_v1.sec;
697 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
698
699 // format a BinaryLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800700 uint64_t token = proto.start(LogProto::BINARY_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800701 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
702 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
Yi Jinb592e3b2018-02-01 15:17:04 -0800703 proto.write(BinaryLogEntry::UID, (int)msg.entry_v4.uid);
Yi Jin3c034c92017-12-22 17:36:47 -0800704 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
705 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
Yi Jinb592e3b2018-02-01 15:17:04 -0800706 proto.write(BinaryLogEntry::TAG_INDEX,
707 get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
Yi Jin3c034c92017-12-22 17:36:47 -0800708 do {
709 elem = android_log_read_next(context);
Yi Jin5ee07872018-03-05 18:18:27 -0800710 uint64_t elemToken = proto.start(BinaryLogEntry::ELEMS);
Yi Jin3c034c92017-12-22 17:36:47 -0800711 switch (elem.type) {
712 case EVENT_TYPE_INT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800713 proto.write(BinaryLogEntry::Elem::TYPE,
714 BinaryLogEntry::Elem::EVENT_TYPE_INT);
715 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int)elem.data.int32);
Yi Jin3c034c92017-12-22 17:36:47 -0800716 break;
717 case EVENT_TYPE_LONG:
Yi Jinb592e3b2018-02-01 15:17:04 -0800718 proto.write(BinaryLogEntry::Elem::TYPE,
719 BinaryLogEntry::Elem::EVENT_TYPE_LONG);
720 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long)elem.data.int64);
Yi Jin3c034c92017-12-22 17:36:47 -0800721 break;
722 case EVENT_TYPE_STRING:
Yi Jinb592e3b2018-02-01 15:17:04 -0800723 proto.write(BinaryLogEntry::Elem::TYPE,
724 BinaryLogEntry::Elem::EVENT_TYPE_STRING);
Yi Jin3c034c92017-12-22 17:36:47 -0800725 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
726 break;
727 case EVENT_TYPE_FLOAT:
Yi Jinb592e3b2018-02-01 15:17:04 -0800728 proto.write(BinaryLogEntry::Elem::TYPE,
729 BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
Yi Jin3c034c92017-12-22 17:36:47 -0800730 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
731 break;
732 case EVENT_TYPE_LIST:
Yi Jinb592e3b2018-02-01 15:17:04 -0800733 proto.write(BinaryLogEntry::Elem::TYPE,
734 BinaryLogEntry::Elem::EVENT_TYPE_LIST);
Yi Jin3c034c92017-12-22 17:36:47 -0800735 break;
736 case EVENT_TYPE_LIST_STOP:
Yi Jinb592e3b2018-02-01 15:17:04 -0800737 proto.write(BinaryLogEntry::Elem::TYPE,
738 BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
Yi Jin3c034c92017-12-22 17:36:47 -0800739 break;
740 case EVENT_TYPE_UNKNOWN:
Yi Jinb592e3b2018-02-01 15:17:04 -0800741 proto.write(BinaryLogEntry::Elem::TYPE,
742 BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
Yi Jin3c034c92017-12-22 17:36:47 -0800743 break;
744 }
745 proto.end(elemToken);
746 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
747 proto.end(token);
748 if (context) {
749 android_log_destroy(&context);
750 }
751 } else {
752 AndroidLogEntry entry;
753 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
754 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700755 ALOGW("[%s] fails to process to an entry.\n", this->name.string());
Yi Jin3c034c92017-12-22 17:36:47 -0800756 break;
757 }
758 lastTimestamp.tv_sec = entry.tv_sec;
759 lastTimestamp.tv_nsec = entry.tv_nsec;
760
761 // format a TextLogEntry
Yi Jin5ee07872018-03-05 18:18:27 -0800762 uint64_t token = proto.start(LogProto::TEXT_LOGS);
Yi Jin3c034c92017-12-22 17:36:47 -0800763 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
764 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
765 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
766 proto.write(TextLogEntry::UID, entry.uid);
767 proto.write(TextLogEntry::PID, entry.pid);
768 proto.write(TextLogEntry::TID, entry.tid);
769 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
Yi Jinb592e3b2018-02-01 15:17:04 -0800770 proto.write(TextLogEntry::LOG, entry.message,
771 trimTail(entry.message, entry.messageLen));
Yi Jin3c034c92017-12-22 17:36:47 -0800772 proto.end(token);
773 }
774 }
775 gLastLogsRetrieved[mLogID] = lastTimestamp;
776 proto.flush(pipeWriteFd);
Yi Jin83fb1d52018-03-16 12:03:53 -0700777 return NO_ERROR;
Yi Jin3c034c92017-12-22 17:36:47 -0800778}
Kweku Adamseadd1232018-02-05 16:45:13 -0800779
780// ================================================================================
781
782TombstoneSection::TombstoneSection(int id, const char* type, const int64_t timeoutMs)
783 : WorkerThreadSection(id, timeoutMs), mType(type) {
Yi Jin3be0b432018-04-20 17:08:11 -0700784 name = "tombstone ";
Kweku Adamseadd1232018-02-05 16:45:13 -0800785 name += type;
786}
787
788TombstoneSection::~TombstoneSection() {}
789
790status_t TombstoneSection::BlockingCall(int pipeWriteFd) const {
791 std::unique_ptr<DIR, decltype(&closedir)> proc(opendir("/proc"), closedir);
792 if (proc.get() == nullptr) {
793 ALOGE("opendir /proc failed: %s\n", strerror(errno));
794 return -errno;
795 }
796
797 const std::set<int> hal_pids = get_interesting_hal_pids();
798
799 ProtoOutputStream proto;
800 struct dirent* d;
801 status_t err = NO_ERROR;
802 while ((d = readdir(proc.get()))) {
803 int pid = atoi(d->d_name);
804 if (pid <= 0) {
805 continue;
806 }
807
808 const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid);
809 std::string exe;
810 if (!android::base::Readlink(link_name, &exe)) {
811 ALOGE("Can't read '%s': %s\n", link_name.c_str(), strerror(errno));
812 continue;
813 }
814
815 bool is_java_process;
816 if (exe == "/system/bin/app_process32" || exe == "/system/bin/app_process64") {
817 if (mType != "java") continue;
818 // Don't bother dumping backtraces for the zygote.
819 if (IsZygote(pid)) {
820 VLOG("Skipping Zygote");
821 continue;
822 }
823
824 is_java_process = true;
825 } else if (should_dump_native_traces(exe.c_str())) {
826 if (mType != "native") continue;
827 is_java_process = false;
828 } else if (hal_pids.find(pid) != hal_pids.end()) {
829 if (mType != "hal") continue;
830 is_java_process = false;
831 } else {
832 // Probably a native process we don't care about, continue.
833 VLOG("Skipping %d", pid);
834 continue;
835 }
836
837 Fpipe dumpPipe;
838 if (!dumpPipe.init()) {
Yi Jin3be0b432018-04-20 17:08:11 -0700839 ALOGW("[%s] failed to setup dump pipe", this->name.string());
Kweku Adamseadd1232018-02-05 16:45:13 -0800840 err = -errno;
841 break;
842 }
843
844 const uint64_t start = Nanotime();
845 pid_t child = fork();
846 if (child < 0) {
847 ALOGE("Failed to fork child process");
848 break;
849 } else if (child == 0) {
850 // This is the child process.
Yi Jin6355d2f2018-03-14 15:18:02 -0700851 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800852 const int ret = dump_backtrace_to_file_timeout(
853 pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace,
Yi Jin6355d2f2018-03-14 15:18:02 -0700854 is_java_process ? 5 : 20, dumpPipe.writeFd().get());
Kweku Adamseadd1232018-02-05 16:45:13 -0800855 if (ret == -1) {
856 if (errno == 0) {
857 ALOGW("Dumping failed for pid '%d', likely due to a timeout\n", pid);
858 } else {
859 ALOGE("Dumping failed for pid '%d': %s\n", pid, strerror(errno));
860 }
861 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700862 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800863 _exit(EXIT_SUCCESS);
864 }
Yi Jin6355d2f2018-03-14 15:18:02 -0700865 dumpPipe.writeFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800866 // Parent process.
867 // Read from the pipe concurrently to avoid blocking the child.
868 FdBuffer buffer;
Yi Jine3dab2d2018-03-22 16:56:39 -0700869 err = buffer.readFully(dumpPipe.readFd().get());
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700870 // Wait on the child to avoid it becoming a zombie process.
871 status_t cStatus = wait_child(child);
Kweku Adamseadd1232018-02-05 16:45:13 -0800872 if (err != NO_ERROR) {
Yi Jin3be0b432018-04-20 17:08:11 -0700873 ALOGW("[%s] failed to read stack dump: %d", this->name.string(), err);
Yi Jin6355d2f2018-03-14 15:18:02 -0700874 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800875 break;
876 }
Kweku Adamsa8a56c82018-04-23 06:15:31 -0700877 if (cStatus != NO_ERROR) {
878 ALOGE("TombstoneSection '%s' child had an issue: %s\n", this->name.string(), strerror(-cStatus));
879 }
Kweku Adamseadd1232018-02-05 16:45:13 -0800880
881 auto dump = std::make_unique<char[]>(buffer.size());
882 auto iterator = buffer.data();
883 int i = 0;
884 while (iterator.hasNext()) {
885 dump[i] = iterator.next();
886 i++;
887 }
Yi Jin6cacbcb2018-03-30 14:04:52 -0700888 uint64_t token = proto.start(android::os::BackTraceProto::TRACES);
Kweku Adamseadd1232018-02-05 16:45:13 -0800889 proto.write(android::os::BackTraceProto::Stack::PID, pid);
890 proto.write(android::os::BackTraceProto::Stack::DUMP, dump.get(), i);
891 proto.write(android::os::BackTraceProto::Stack::DUMP_DURATION_NS,
892 static_cast<long long>(Nanotime() - start));
893 proto.end(token);
Yi Jin6355d2f2018-03-14 15:18:02 -0700894 dumpPipe.readFd().reset();
Kweku Adamseadd1232018-02-05 16:45:13 -0800895 }
896
897 proto.flush(pipeWriteFd);
898 return err;
899}
Yi Jin6cacbcb2018-03-30 14:04:52 -0700900
901} // namespace incidentd
902} // namespace os
Yi Jin98ce8102018-04-12 11:15:39 -0700903} // namespace android