blob: 3c76298c284c675b6880df3ca6b0eac77b4f42c0 [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 */
16
17#define LOG_TAG "incidentd"
18
19#include "Section.h"
Yi Jin99c248f2017-08-25 18:11:58 -070020
Yi Jin3c034c92017-12-22 17:36:47 -080021#include <errno.h>
Yi Jin4bab3a12018-01-10 16:50:59 -080022#include <sys/prctl.h>
Yi Jin3c034c92017-12-22 17:36:47 -080023#include <unistd.h>
24#include <wait.h>
25
26#include <memory>
27#include <mutex>
Joe Onorato1754d742016-11-21 17:51:35 -080028
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>
Yi Jin3c034c92017-12-22 17:36:47 -080031#include <log/log_event_list.h>
32#include <log/logprint.h>
33#include <log/log_read.h>
Yi Jin3c034c92017-12-22 17:36:47 -080034#include <private/android_logger.h>
35
36#include "FdBuffer.h"
37#include "frameworks/base/core/proto/android/util/log.proto.h"
38#include "io_util.h"
39#include "Privacy.h"
40#include "PrivacyBuffer.h"
41#include "section_list.h"
Joe Onorato1754d742016-11-21 17:51:35 -080042
Yi Jinc23fad22017-09-15 17:24:59 -070043using namespace android::util;
Joe Onorato1754d742016-11-21 17:51:35 -080044using namespace std;
45
Yi Jinc23fad22017-09-15 17:24:59 -070046// special section ids
47const int FIELD_ID_INCIDENT_HEADER = 1;
Yi Jin329130b2018-02-09 16:47:47 -080048const int FIELD_ID_INCIDENT_METADATA = 2;
Yi Jinc23fad22017-09-15 17:24:59 -070049
50// incident section parameters
Yi Jinb44f7d42017-07-21 12:12:59 -070051const int WAIT_MAX = 5;
52const struct timespec WAIT_INTERVAL_NS = {0, 200 * 1000 * 1000};
Yi Jin3c034c92017-12-22 17:36:47 -080053const char INCIDENT_HELPER[] = "/system/bin/incident_helper";
Yi Jinb44f7d42017-07-21 12:12:59 -070054
55static pid_t
Yi Jinedfd5bb2017-09-06 17:09:11 -070056fork_execute_incident_helper(const int id, const char* name, Fpipe& p2cPipe, Fpipe& c2pPipe)
Yi Jinb44f7d42017-07-21 12:12:59 -070057{
Yi Jin0ed9b682017-08-18 14:51:20 -070058 const char* ihArgs[] { INCIDENT_HELPER, "-s", String8::format("%d", id).string(), NULL };
Yi Jinb44f7d42017-07-21 12:12:59 -070059 // fork used in multithreaded environment, avoid adding unnecessary code in child process
60 pid_t pid = fork();
61 if (pid == 0) {
Yi Jin4bab3a12018-01-10 16:50:59 -080062 if (TEMP_FAILURE_RETRY(dup2(p2cPipe.readFd(), STDIN_FILENO)) != 0
63 || !p2cPipe.close()
64 || TEMP_FAILURE_RETRY(dup2(c2pPipe.writeFd(), STDOUT_FILENO)) != 1
65 || !c2pPipe.close()) {
Yi Jinb44f7d42017-07-21 12:12:59 -070066 ALOGW("%s can't setup stdin and stdout for incident helper", name);
67 _exit(EXIT_FAILURE);
68 }
69
Yi Jin4bab3a12018-01-10 16:50:59 -080070 /* make sure the child dies when incidentd dies */
71 prctl(PR_SET_PDEATHSIG, SIGKILL);
72
Yi Jinb44f7d42017-07-21 12:12:59 -070073 execv(INCIDENT_HELPER, const_cast<char**>(ihArgs));
74
75 ALOGW("%s failed in incident helper process: %s", name, strerror(errno));
76 _exit(EXIT_FAILURE); // always exits with failure if any
77 }
78 // close the fds used in incident helper
79 close(p2cPipe.readFd());
80 close(c2pPipe.writeFd());
81 return pid;
82}
83
Yi Jin99c248f2017-08-25 18:11:58 -070084// ================================================================================
Yi Jin4bab3a12018-01-10 16:50:59 -080085static status_t statusCode(int status) {
86 if (WIFSIGNALED(status)) {
87 ALOGD("return by signal: %s", strerror(WTERMSIG(status)));
88 return -WTERMSIG(status);
89 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
90 ALOGD("return by exit: %s", strerror(WEXITSTATUS(status)));
91 return -WEXITSTATUS(status);
92 }
93 return NO_ERROR;
94}
95
Yi Jinedfd5bb2017-09-06 17:09:11 -070096static status_t kill_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -070097 int status;
Yi Jin4bab3a12018-01-10 16:50:59 -080098 ALOGD("try to kill child process %d", pid);
Yi Jinb44f7d42017-07-21 12:12:59 -070099 kill(pid, SIGKILL);
100 if (waitpid(pid, &status, 0) == -1) return -1;
Yi Jin4bab3a12018-01-10 16:50:59 -0800101 return statusCode(status);
Yi Jinb44f7d42017-07-21 12:12:59 -0700102}
103
Yi Jinedfd5bb2017-09-06 17:09:11 -0700104static status_t wait_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700105 int status;
106 bool died = false;
107 // wait for child to report status up to 1 seconds
108 for(int loop = 0; !died && loop < WAIT_MAX; loop++) {
109 if (waitpid(pid, &status, WNOHANG) == pid) died = true;
110 // sleep for 0.2 second
111 nanosleep(&WAIT_INTERVAL_NS, NULL);
112 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700113 if (!died) return kill_child(pid);
Yi Jin4bab3a12018-01-10 16:50:59 -0800114 return statusCode(status);
Yi Jinb44f7d42017-07-21 12:12:59 -0700115}
Joe Onorato1754d742016-11-21 17:51:35 -0800116// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700117static const Privacy*
Yi Jinedfd5bb2017-09-06 17:09:11 -0700118get_privacy_of_section(int id)
Yi Jin99c248f2017-08-25 18:11:58 -0700119{
Yi Jin7e0b4e52017-09-12 20:00:25 -0700120 int l = 0;
121 int r = PRIVACY_POLICY_COUNT - 1;
122 while (l <= r) {
123 int mid = (l + r) >> 1;
124 const Privacy* p = PRIVACY_POLICY_LIST[mid];
125
126 if (p->field_id < (uint32_t)id) {
127 l = mid + 1;
128 } else if (p->field_id > (uint32_t)id) {
129 r = mid - 1;
130 } else {
131 return p;
132 }
Yi Jin99c248f2017-08-25 18:11:58 -0700133 }
134 return NULL;
135}
136
Yi Jinedfd5bb2017-09-06 17:09:11 -0700137// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700138static status_t
Yi Jinedfd5bb2017-09-06 17:09:11 -0700139write_section_header(int fd, int sectionId, size_t size)
Yi Jin99c248f2017-08-25 18:11:58 -0700140{
Yi Jin99c248f2017-08-25 18:11:58 -0700141 uint8_t buf[20];
Yi Jinedfd5bb2017-09-06 17:09:11 -0700142 uint8_t *p = write_length_delimited_tag_header(buf, sectionId, size);
143 return write_all(fd, buf, p-buf);
Yi Jin99c248f2017-08-25 18:11:58 -0700144}
145
146static status_t
Yi Jinedfd5bb2017-09-06 17:09:11 -0700147write_report_requests(const int id, const FdBuffer& buffer, ReportRequestSet* requests)
Yi Jin99c248f2017-08-25 18:11:58 -0700148{
Yi Jin0f047162017-09-05 13:44:22 -0700149 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -0700150 EncodedBuffer::iterator data = buffer.data();
151 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -0700152 int writeable = 0;
Yi Jin329130b2018-02-09 16:47:47 -0800153 auto stats = requests->sectionStats(id);
154
155 stats->set_dump_size_bytes(data.size());
156 stats->set_dump_duration_ms(buffer.durationMs());
157 stats->set_timed_out(buffer.timedOut());
158 stats->set_is_truncated(buffer.truncated());
Yi Jin99c248f2017-08-25 18:11:58 -0700159
Yi Jin0f047162017-09-05 13:44:22 -0700160 // The streaming ones, group requests by spec in order to save unnecessary strip operations
161 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -0800162 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -0700163 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -0700164 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -0700165 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -0700166 }
Yi Jin3ec5cc72018-01-26 13:42:43 -0800167 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -0700168 requestsBySpec[spec].push_back(request);
169 }
170
Yi Jin3ec5cc72018-01-26 13:42:43 -0800171 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -0700172 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700173 err = privacyBuffer.strip(spec);
174 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
175 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700176
Yi Jin3ec5cc72018-01-26 13:42:43 -0800177 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700178 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700179 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700180 if (err != NO_ERROR) { request->err = err; continue; }
Yi Jinc23fad22017-09-15 17:24:59 -0700181 err = privacyBuffer.flush(request->fd);
Yi Jinedfd5bb2017-09-06 17:09:11 -0700182 if (err != NO_ERROR) { request->err = err; continue; }
183 writeable++;
Yi Jin3ec5cc72018-01-26 13:42:43 -0800184 ALOGD("Section %d flushed %zu bytes to fd %d with spec %d", id,
185 privacyBuffer.size(), request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700186 }
Yi Jinc23fad22017-09-15 17:24:59 -0700187 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700188 }
189
190 // The dropbox file
191 if (requests->mainFd() >= 0) {
Yi Jin329130b2018-02-09 16:47:47 -0800192 PrivacySpec spec = PrivacySpec::new_spec(requests->mainDest());
Yi Jin3ec5cc72018-01-26 13:42:43 -0800193 err = privacyBuffer.strip(spec);
Yi Jin0f047162017-09-05 13:44:22 -0700194 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700195 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700196
Yi Jinc23fad22017-09-15 17:24:59 -0700197 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700198 if (err != NO_ERROR) { requests->setMainFd(-1); goto DONE; }
Yi Jinc23fad22017-09-15 17:24:59 -0700199 err = privacyBuffer.flush(requests->mainFd());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700200 if (err != NO_ERROR) { requests->setMainFd(-1); goto DONE; }
201 writeable++;
Yi Jin3ec5cc72018-01-26 13:42:43 -0800202 ALOGD("Section %d flushed %zu bytes to dropbox %d with spec %d", id,
203 privacyBuffer.size(), requests->mainFd(), spec.dest);
Yi Jin329130b2018-02-09 16:47:47 -0800204 stats->set_report_size_bytes(privacyBuffer.size());
Yi Jin99c248f2017-08-25 18:11:58 -0700205 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700206
207DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700208 // only returns error if there is no fd to write to.
209 return writeable > 0 ? NO_ERROR : err;
210}
211
212// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700213Section::Section(int i, const int64_t timeoutMs)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700214 :id(i),
215 timeoutMs(timeoutMs)
Joe Onorato1754d742016-11-21 17:51:35 -0800216{
217}
218
219Section::~Section()
220{
221}
222
Joe Onorato1754d742016-11-21 17:51:35 -0800223// ================================================================================
Yi Jinedfd5bb2017-09-06 17:09:11 -0700224HeaderSection::HeaderSection()
225 :Section(FIELD_ID_INCIDENT_HEADER, 0)
226{
227}
228
229HeaderSection::~HeaderSection()
230{
231}
232
233status_t
234HeaderSection::Execute(ReportRequestSet* requests) const
235{
236 for (ReportRequestSet::iterator it=requests->begin(); it!=requests->end(); it++) {
237 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800238 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700239
Yi Jinbdf58942017-11-14 17:58:19 -0800240 for (vector<vector<uint8_t>>::const_iterator buf=headers.begin(); buf!=headers.end(); buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700241 if (buf->empty()) continue;
242
243 // So the idea is only requests with negative fd are written to dropbox file.
244 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
Yi Jin329130b2018-02-09 16:47:47 -0800245 write_section_header(fd, id, buf->size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700246 write_all(fd, (uint8_t const*)buf->data(), buf->size());
247 // If there was an error now, there will be an error later and we will remove
248 // it from the list then.
249 }
250 }
251 return NO_ERROR;
252}
Yi Jin329130b2018-02-09 16:47:47 -0800253// ================================================================================
254MetadataSection::MetadataSection()
255 :Section(FIELD_ID_INCIDENT_METADATA, 0)
256{
257}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700258
Yi Jin329130b2018-02-09 16:47:47 -0800259MetadataSection::~MetadataSection()
260{
261}
262
263status_t
264MetadataSection::Execute(ReportRequestSet* requests) const
265{
266 std::string metadataBuf;
267 requests->metadata().SerializeToString(&metadataBuf);
268 for (ReportRequestSet::iterator it=requests->begin(); it!=requests->end(); it++) {
269 const sp<ReportRequest> request = *it;
270 if (metadataBuf.empty() || request->fd < 0 || request->err != NO_ERROR) {
271 continue;
272 }
273 write_section_header(request->fd, id, metadataBuf.size());
274 write_all(request->fd, (uint8_t const*)metadataBuf.data(), metadataBuf.size());
275 }
276 if (requests->mainFd() >= 0 && !metadataBuf.empty()) {
277 write_section_header(requests->mainFd(), id, metadataBuf.size());
278 write_all(requests->mainFd(), (uint8_t const*)metadataBuf.data(), metadataBuf.size());
279 }
280 return NO_ERROR;
281}
Yi Jinedfd5bb2017-09-06 17:09:11 -0700282// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700283FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700284 :Section(id, timeoutMs),
285 mFilename(filename)
286{
Yi Jinb44f7d42017-07-21 12:12:59 -0700287 name = filename;
Yi Jin0eb22342017-11-06 17:17:27 -0800288 mIsSysfs = strncmp(filename, "/sys/", 5) == 0;
Yi Jin0a3406f2017-06-22 19:23:11 -0700289}
290
291FileSection::~FileSection() {}
292
Yi Jin99c248f2017-08-25 18:11:58 -0700293status_t
294FileSection::Execute(ReportRequestSet* requests) const
295{
Yi Jinb44f7d42017-07-21 12:12:59 -0700296 // read from mFilename first, make sure the file is available
297 // add O_CLOEXEC to make sure it is closed when exec incident helper
George Burgess IV6f9735b2017-08-03 16:08:29 -0700298 int fd = open(mFilename, O_RDONLY | O_CLOEXEC);
Yi Jin0a3406f2017-06-22 19:23:11 -0700299 if (fd == -1) {
300 ALOGW("FileSection '%s' failed to open file", this->name.string());
301 return -errno;
302 }
303
Yi Jinb44f7d42017-07-21 12:12:59 -0700304 FdBuffer buffer;
305 Fpipe p2cPipe;
306 Fpipe c2pPipe;
307 // initiate pipes to pass data to/from incident_helper
308 if (!p2cPipe.init() || !c2pPipe.init()) {
309 ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700310 return -errno;
311 }
312
Yi Jinedfd5bb2017-09-06 17:09:11 -0700313 pid_t pid = fork_execute_incident_helper(this->id, this->name.string(), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700314 if (pid == -1) {
315 ALOGW("FileSection '%s' failed to fork", this->name.string());
316 return -errno;
317 }
318
319 // parent process
320 status_t readStatus = buffer.readProcessedDataInStream(fd, p2cPipe.writeFd(), c2pPipe.readFd(),
Yi Jin0eb22342017-11-06 17:17:27 -0800321 this->timeoutMs, mIsSysfs);
Yi Jinb44f7d42017-07-21 12:12:59 -0700322 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800323 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
324 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
325 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700326 return readStatus;
327 }
328
Yi Jinedfd5bb2017-09-06 17:09:11 -0700329 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700330 if (ihStatus != NO_ERROR) {
331 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(), strerror(-ihStatus));
332 return ihStatus;
333 }
334
335 ALOGD("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
Yi Jin0a3406f2017-06-22 19:23:11 -0700336 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700337 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700338 if (err != NO_ERROR) {
339 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
340 return err;
341 }
342
343 return NO_ERROR;
344}
345
346// ================================================================================
Joe Onorato1754d742016-11-21 17:51:35 -0800347struct WorkerThreadData : public virtual RefBase
348{
349 const WorkerThreadSection* section;
350 int fds[2];
351
352 // Lock protects these fields
353 mutex lock;
354 bool workerDone;
355 status_t workerError;
356
357 WorkerThreadData(const WorkerThreadSection* section);
358 virtual ~WorkerThreadData();
359
360 int readFd() { return fds[0]; }
361 int writeFd() { return fds[1]; }
362};
363
364WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
365 :section(sec),
366 workerDone(false),
367 workerError(NO_ERROR)
368{
369 fds[0] = -1;
370 fds[1] = -1;
371}
372
373WorkerThreadData::~WorkerThreadData()
374{
375}
376
377// ================================================================================
378WorkerThreadSection::WorkerThreadSection(int id)
379 :Section(id)
380{
381}
382
383WorkerThreadSection::~WorkerThreadSection()
384{
385}
386
387static void*
388worker_thread_func(void* cookie)
389{
390 WorkerThreadData* data = (WorkerThreadData*)cookie;
391 status_t err = data->section->BlockingCall(data->writeFd());
392
393 {
394 unique_lock<mutex> lock(data->lock);
395 data->workerDone = true;
396 data->workerError = err;
397 }
398
399 close(data->writeFd());
400 data->decStrong(data->section);
401 // data might be gone now. don't use it after this point in this thread.
402 return NULL;
403}
404
405status_t
406WorkerThreadSection::Execute(ReportRequestSet* requests) const
407{
408 status_t err = NO_ERROR;
409 pthread_t thread;
410 pthread_attr_t attr;
411 bool timedOut = false;
412 FdBuffer buffer;
413
414 // Data shared between this thread and the worker thread.
415 sp<WorkerThreadData> data = new WorkerThreadData(this);
416
417 // Create the pipe
418 err = pipe(data->fds);
419 if (err != 0) {
420 return -errno;
421 }
422
423 // The worker thread needs a reference and we can't let the count go to zero
424 // if that thread is slow to start.
425 data->incStrong(this);
426
427 // Create the thread
428 err = pthread_attr_init(&attr);
429 if (err != 0) {
430 return -err;
431 }
432 // TODO: Do we need to tweak thread priority?
433 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
434 if (err != 0) {
435 pthread_attr_destroy(&attr);
436 return -err;
437 }
438 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
439 if (err != 0) {
440 pthread_attr_destroy(&attr);
441 return -err;
442 }
443 pthread_attr_destroy(&attr);
444
445 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jinb44f7d42017-07-21 12:12:59 -0700446 err = buffer.read(data->readFd(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800447 if (err != NO_ERROR) {
448 // TODO: Log this error into the incident report.
449 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
450 strerror(-err));
451 }
452
453 // Done with the read fd. The worker thread closes the write one so
454 // we never race and get here first.
455 close(data->readFd());
456
457 // If the worker side is finished, then return its error (which may overwrite
458 // our possible error -- but it's more interesting anyway). If not, then we timed out.
459 {
460 unique_lock<mutex> lock(data->lock);
461 if (!data->workerDone) {
462 // We timed out
463 timedOut = true;
464 } else {
465 if (data->workerError != NO_ERROR) {
466 err = data->workerError;
467 // TODO: Log this error into the incident report.
468 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
469 strerror(-err));
470 }
471 }
472 }
473
474 if (timedOut || buffer.timedOut()) {
475 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
476 return NO_ERROR;
477 }
478
479 if (buffer.truncated()) {
480 // TODO: Log this into the incident report.
481 }
482
483 // TODO: There was an error with the command or buffering. Report that. For now
484 // just exit with a log messasge.
485 if (err != NO_ERROR) {
486 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
487 strerror(-err));
488 return NO_ERROR;
489 }
490
491 // Write the data that was collected
Yi Jinb44f7d42017-07-21 12:12:59 -0700492 ALOGD("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
Joe Onorato1754d742016-11-21 17:51:35 -0800493 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700494 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800495 if (err != NO_ERROR) {
496 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
497 return err;
498 }
499
500 return NO_ERROR;
501}
502
503// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700504void
505CommandSection::init(const char* command, va_list args)
Yi Jinb44f7d42017-07-21 12:12:59 -0700506{
507 va_list copied_args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700508 int numOfArgs = 0;
Yi Jin4ef28b72017-08-14 14:45:28 -0700509
510 va_copy(copied_args, args);
511 while(va_arg(copied_args, const char*) != NULL) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700512 numOfArgs++;
513 }
Yi Jin4ef28b72017-08-14 14:45:28 -0700514 va_end(copied_args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700515
516 // allocate extra 1 for command and 1 for NULL terminator
517 mCommand = (const char**)malloc(sizeof(const char*) * (numOfArgs + 2));
518
519 mCommand[0] = command;
520 name = command;
521 for (int i=0; i<numOfArgs; i++) {
Yi Jin4ef28b72017-08-14 14:45:28 -0700522 const char* arg = va_arg(args, const char*);
Yi Jinb44f7d42017-07-21 12:12:59 -0700523 mCommand[i+1] = arg;
524 name += " ";
525 name += arg;
526 }
527 mCommand[numOfArgs+1] = NULL;
Yi Jinb44f7d42017-07-21 12:12:59 -0700528}
529
530CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700531 :Section(id, timeoutMs)
Joe Onorato1754d742016-11-21 17:51:35 -0800532{
533 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700534 va_start(args, command);
535 init(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800536 va_end(args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700537}
Joe Onorato1754d742016-11-21 17:51:35 -0800538
Yi Jinb44f7d42017-07-21 12:12:59 -0700539CommandSection::CommandSection(int id, const char* command, ...)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700540 :Section(id)
Yi Jinb44f7d42017-07-21 12:12:59 -0700541{
542 va_list args;
543 va_start(args, command);
544 init(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800545 va_end(args);
546}
547
548CommandSection::~CommandSection()
549{
Yi Jinb44f7d42017-07-21 12:12:59 -0700550 free(mCommand);
Joe Onorato1754d742016-11-21 17:51:35 -0800551}
552
553status_t
Yi Jinb44f7d42017-07-21 12:12:59 -0700554CommandSection::Execute(ReportRequestSet* requests) const
Joe Onorato1754d742016-11-21 17:51:35 -0800555{
Yi Jinb44f7d42017-07-21 12:12:59 -0700556 FdBuffer buffer;
557 Fpipe cmdPipe;
558 Fpipe ihPipe;
559
560 if (!cmdPipe.init() || !ihPipe.init()) {
561 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
562 return -errno;
563 }
564
565 pid_t cmdPid = fork();
566 if (cmdPid == -1) {
567 ALOGW("CommandSection '%s' failed to fork", this->name.string());
568 return -errno;
569 }
570 // child process to execute the command as root
571 if (cmdPid == 0) {
572 // replace command's stdout with ihPipe's write Fd
573 if (dup2(cmdPipe.writeFd(), STDOUT_FILENO) != 1 || !ihPipe.close() || !cmdPipe.close()) {
574 ALOGW("CommandSection '%s' failed to set up stdout: %s", this->name.string(), strerror(errno));
575 _exit(EXIT_FAILURE);
576 }
Kweku Adamsf5cc5752017-12-20 17:59:17 -0800577 execvp(this->mCommand[0], (char *const *) this->mCommand);
Yi Jinb44f7d42017-07-21 12:12:59 -0700578 int err = errno; // record command error code
579 ALOGW("CommandSection '%s' failed in executing command: %s", this->name.string(), strerror(errno));
580 _exit(err); // exit with command error code
581 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700582 pid_t ihPid = fork_execute_incident_helper(this->id, this->name.string(), cmdPipe, ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700583 if (ihPid == -1) {
584 ALOGW("CommandSection '%s' failed to fork", this->name.string());
585 return -errno;
586 }
587
588 close(cmdPipe.writeFd());
589 status_t readStatus = buffer.read(ihPipe.readFd(), this->timeoutMs);
590 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800591 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
592 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
593 kill_child(cmdPid);
594 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700595 return readStatus;
596 }
597
598 // TODO: wait for command here has one trade-off: the failed status of command won't be detected until
599 // buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700600 status_t cmdStatus = wait_child(cmdPid);
601 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700602 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinadd11e92017-07-30 16:10:07 -0700603 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident helper: %s",
Yi Jinb44f7d42017-07-21 12:12:59 -0700604 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
605 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
606 }
607
608 ALOGD("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
609 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700610 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700611 if (err != NO_ERROR) {
612 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
613 return err;
614 }
Joe Onorato1754d742016-11-21 17:51:35 -0800615 return NO_ERROR;
616}
617
618// ================================================================================
619DumpsysSection::DumpsysSection(int id, const char* service, ...)
620 :WorkerThreadSection(id),
621 mService(service)
622{
623 name = "dumpsys ";
624 name += service;
625
626 va_list args;
627 va_start(args, service);
628 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700629 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800630 if (arg == NULL) {
631 break;
632 }
633 mArgs.add(String16(arg));
634 name += " ";
635 name += arg;
636 }
637 va_end(args);
638}
639
640DumpsysSection::~DumpsysSection()
641{
642}
643
644status_t
645DumpsysSection::BlockingCall(int pipeWriteFd) const
646{
647 // checkService won't wait for the service to show up like getService will.
648 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700649
Joe Onorato1754d742016-11-21 17:51:35 -0800650 if (service == NULL) {
651 // Returning an error interrupts the entire incident report, so just
652 // log the failure.
653 // TODO: have a meta record inside the report that would log this
654 // failure inside the report, because the fact that we can't find
655 // the service is good data in and of itself. This is running in
656 // another thread so lock that carefully...
657 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
658 return NO_ERROR;
659 }
660
661 service->dump(pipeWriteFd, mArgs);
662
663 return NO_ERROR;
664}
Yi Jin3c034c92017-12-22 17:36:47 -0800665
666// ================================================================================
667// initialization only once in Section.cpp.
668map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
669
670LogSection::LogSection(int id, log_id_t logID)
671 :WorkerThreadSection(id),
672 mLogID(logID)
673{
674 name += "logcat ";
675 name += android_log_id_to_name(logID);
676 switch (logID) {
677 case LOG_ID_EVENTS:
678 case LOG_ID_STATS:
679 case LOG_ID_SECURITY:
680 mBinary = true;
681 break;
682 default:
683 mBinary = false;
684 }
685}
686
687LogSection::~LogSection()
688{
689}
690
691static size_t
692trimTail(char const* buf, size_t len)
693{
694 while (len > 0) {
695 char c = buf[len - 1];
696 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
697 len--;
698 } else {
699 break;
700 }
701 }
702 return len;
703}
704
705static inline int32_t get4LE(uint8_t const* src) {
706 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
707}
708
709status_t
710LogSection::BlockingCall(int pipeWriteFd) const
711{
712 status_t err = NO_ERROR;
713 // Open log buffer and getting logs since last retrieved time if any.
714 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
715 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end() ?
716 android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0) :
717 android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
718 gLastLogsRetrieved[mLogID], 0),
719 android_logger_list_free);
720
721 if (android_logger_open(loggers.get(), mLogID) == NULL) {
722 ALOGW("LogSection %s: Can't get logger.", this->name.string());
723 return err;
724 }
725
726 log_msg msg;
727 log_time lastTimestamp(0);
728
729 ProtoOutputStream proto;
730 while (true) { // keeps reading until logd buffer is fully read.
731 status_t err = android_logger_list_read(loggers.get(), &msg);
732 // err = 0 - no content, unexpected connection drop or EOF.
733 // err = +ive number - size of retrieved data from logger
734 // err = -ive number, OS supplied error _except_ for -EAGAIN
735 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
736 if (err <= 0) {
737 if (err != -EAGAIN) {
738 ALOGE("LogSection %s: fails to read a log_msg.\n", this->name.string());
739 }
740 break;
741 }
742 if (mBinary) {
743 // remove the first uint32 which is tag's index in event log tags
744 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
745 msg.len() - sizeof(uint32_t));;
746 android_log_list_element elem;
747
748 lastTimestamp.tv_sec = msg.entry_v1.sec;
749 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
750
751 // format a BinaryLogEntry
752 long long token = proto.start(LogProto::BINARY_LOGS);
753 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
754 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
755 proto.write(BinaryLogEntry::UID, (int) msg.entry_v4.uid);
756 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
757 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
758 proto.write(BinaryLogEntry::TAG_INDEX, get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
759 do {
760 elem = android_log_read_next(context);
761 long long elemToken = proto.start(BinaryLogEntry::ELEMS);
762 switch (elem.type) {
763 case EVENT_TYPE_INT:
764 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_INT);
765 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int) elem.data.int32);
766 break;
767 case EVENT_TYPE_LONG:
768 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LONG);
769 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long) elem.data.int64);
770 break;
771 case EVENT_TYPE_STRING:
772 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_STRING);
773 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
774 break;
775 case EVENT_TYPE_FLOAT:
776 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
777 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
778 break;
779 case EVENT_TYPE_LIST:
780 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LIST);
781 break;
782 case EVENT_TYPE_LIST_STOP:
783 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
784 break;
785 case EVENT_TYPE_UNKNOWN:
786 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
787 break;
788 }
789 proto.end(elemToken);
790 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
791 proto.end(token);
792 if (context) {
793 android_log_destroy(&context);
794 }
795 } else {
796 AndroidLogEntry entry;
797 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
798 if (err != NO_ERROR) {
799 ALOGE("LogSection %s: fails to process to an entry.\n", this->name.string());
800 break;
801 }
802 lastTimestamp.tv_sec = entry.tv_sec;
803 lastTimestamp.tv_nsec = entry.tv_nsec;
804
805 // format a TextLogEntry
806 long long token = proto.start(LogProto::TEXT_LOGS);
807 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
808 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
809 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
810 proto.write(TextLogEntry::UID, entry.uid);
811 proto.write(TextLogEntry::PID, entry.pid);
812 proto.write(TextLogEntry::TID, entry.tid);
813 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
814 proto.write(TextLogEntry::LOG, entry.message, trimTail(entry.message, entry.messageLen));
815 proto.end(token);
816 }
817 }
818 gLastLogsRetrieved[mLogID] = lastTimestamp;
819 proto.flush(pipeWriteFd);
820 return err;
821}