blob: 61d16f815e65be6565465c1af55d337c741dce82 [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>
22#include <unistd.h>
23#include <wait.h>
24
25#include <memory>
26#include <mutex>
Joe Onorato1754d742016-11-21 17:51:35 -080027
Yi Jinc23fad22017-09-15 17:24:59 -070028#include <android/util/protobuf.h>
Joe Onorato1754d742016-11-21 17:51:35 -080029#include <binder/IServiceManager.h>
Yi Jin3c034c92017-12-22 17:36:47 -080030#include <log/log_event_list.h>
31#include <log/logprint.h>
32#include <log/log_read.h>
33#include <private/android_filesystem_config.h> // for AID_NOBODY
34#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;
48
49// incident section parameters
Yi Jinb44f7d42017-07-21 12:12:59 -070050const int WAIT_MAX = 5;
51const struct timespec WAIT_INTERVAL_NS = {0, 200 * 1000 * 1000};
Yi Jin3c034c92017-12-22 17:36:47 -080052const char INCIDENT_HELPER[] = "/system/bin/incident_helper";
Yi Jinb44f7d42017-07-21 12:12:59 -070053
54static pid_t
Yi Jinedfd5bb2017-09-06 17:09:11 -070055fork_execute_incident_helper(const int id, const char* name, Fpipe& p2cPipe, Fpipe& c2pPipe)
Yi Jinb44f7d42017-07-21 12:12:59 -070056{
Yi Jin0ed9b682017-08-18 14:51:20 -070057 const char* ihArgs[] { INCIDENT_HELPER, "-s", String8::format("%d", id).string(), NULL };
Yi Jinb44f7d42017-07-21 12:12:59 -070058
59 // fork used in multithreaded environment, avoid adding unnecessary code in child process
60 pid_t pid = fork();
61 if (pid == 0) {
62 // child process executes incident helper as nobody
63 if (setgid(AID_NOBODY) == -1) {
64 ALOGW("%s can't change gid: %s", name, strerror(errno));
65 _exit(EXIT_FAILURE);
66 }
67 if (setuid(AID_NOBODY) == -1) {
68 ALOGW("%s can't change uid: %s", name, strerror(errno));
69 _exit(EXIT_FAILURE);
70 }
71
72 if (dup2(p2cPipe.readFd(), STDIN_FILENO) != 0 || !p2cPipe.close() ||
73 dup2(c2pPipe.writeFd(), STDOUT_FILENO) != 1 || !c2pPipe.close()) {
74 ALOGW("%s can't setup stdin and stdout for incident helper", name);
75 _exit(EXIT_FAILURE);
76 }
77
78 execv(INCIDENT_HELPER, const_cast<char**>(ihArgs));
79
80 ALOGW("%s failed in incident helper process: %s", name, strerror(errno));
81 _exit(EXIT_FAILURE); // always exits with failure if any
82 }
83 // close the fds used in incident helper
84 close(p2cPipe.readFd());
85 close(c2pPipe.writeFd());
86 return pid;
87}
88
Yi Jin99c248f2017-08-25 18:11:58 -070089// ================================================================================
Yi Jinedfd5bb2017-09-06 17:09:11 -070090static status_t kill_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -070091 int status;
92 kill(pid, SIGKILL);
93 if (waitpid(pid, &status, 0) == -1) return -1;
94 return WIFEXITED(status) == 0 ? NO_ERROR : -WEXITSTATUS(status);
95}
96
Yi Jinedfd5bb2017-09-06 17:09:11 -070097static status_t wait_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -070098 int status;
99 bool died = false;
100 // wait for child to report status up to 1 seconds
101 for(int loop = 0; !died && loop < WAIT_MAX; loop++) {
102 if (waitpid(pid, &status, WNOHANG) == pid) died = true;
103 // sleep for 0.2 second
104 nanosleep(&WAIT_INTERVAL_NS, NULL);
105 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700106 if (!died) return kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700107 return WIFEXITED(status) == 0 ? NO_ERROR : -WEXITSTATUS(status);
108}
Joe Onorato1754d742016-11-21 17:51:35 -0800109// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700110static const Privacy*
Yi Jinedfd5bb2017-09-06 17:09:11 -0700111get_privacy_of_section(int id)
Yi Jin99c248f2017-08-25 18:11:58 -0700112{
Yi Jin7e0b4e52017-09-12 20:00:25 -0700113 int l = 0;
114 int r = PRIVACY_POLICY_COUNT - 1;
115 while (l <= r) {
116 int mid = (l + r) >> 1;
117 const Privacy* p = PRIVACY_POLICY_LIST[mid];
118
119 if (p->field_id < (uint32_t)id) {
120 l = mid + 1;
121 } else if (p->field_id > (uint32_t)id) {
122 r = mid - 1;
123 } else {
124 return p;
125 }
Yi Jin99c248f2017-08-25 18:11:58 -0700126 }
127 return NULL;
128}
129
Yi Jinedfd5bb2017-09-06 17:09:11 -0700130// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700131static status_t
Yi Jinedfd5bb2017-09-06 17:09:11 -0700132write_section_header(int fd, int sectionId, size_t size)
Yi Jin99c248f2017-08-25 18:11:58 -0700133{
Yi Jin99c248f2017-08-25 18:11:58 -0700134 uint8_t buf[20];
Yi Jinedfd5bb2017-09-06 17:09:11 -0700135 uint8_t *p = write_length_delimited_tag_header(buf, sectionId, size);
136 return write_all(fd, buf, p-buf);
Yi Jin99c248f2017-08-25 18:11:58 -0700137}
138
139static status_t
Yi Jinedfd5bb2017-09-06 17:09:11 -0700140write_report_requests(const int id, const FdBuffer& buffer, ReportRequestSet* requests)
Yi Jin99c248f2017-08-25 18:11:58 -0700141{
Yi Jin0f047162017-09-05 13:44:22 -0700142 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -0700143 EncodedBuffer::iterator data = buffer.data();
144 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -0700145 int writeable = 0;
146
Yi Jin0f047162017-09-05 13:44:22 -0700147 // The streaming ones, group requests by spec in order to save unnecessary strip operations
148 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin99c248f2017-08-25 18:11:58 -0700149 for (ReportRequestSet::iterator it = requests->begin(); it != requests->end(); it++) {
150 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -0700151 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -0700152 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -0700153 }
Yi Jin0f047162017-09-05 13:44:22 -0700154 PrivacySpec spec = new_spec_from_args(request->args.dest());
155 requestsBySpec[spec].push_back(request);
156 }
157
158 for (map<PrivacySpec, vector<sp<ReportRequest>>>::iterator mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
159 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700160 err = privacyBuffer.strip(spec);
161 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
162 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700163
164 for (vector<sp<ReportRequest>>::iterator it = mit->second.begin(); it != mit->second.end(); it++) {
165 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700166 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700167 if (err != NO_ERROR) { request->err = err; continue; }
Yi Jinc23fad22017-09-15 17:24:59 -0700168 err = privacyBuffer.flush(request->fd);
Yi Jinedfd5bb2017-09-06 17:09:11 -0700169 if (err != NO_ERROR) { request->err = err; continue; }
170 writeable++;
Yi Jinc23fad22017-09-15 17:24:59 -0700171 ALOGD("Section %d flushed %zu bytes to fd %d with spec %d", id, privacyBuffer.size(), request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700172 }
Yi Jinc23fad22017-09-15 17:24:59 -0700173 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700174 }
175
176 // The dropbox file
177 if (requests->mainFd() >= 0) {
Yi Jinc23fad22017-09-15 17:24:59 -0700178 err = privacyBuffer.strip(get_default_dropbox_spec());
Yi Jin0f047162017-09-05 13:44:22 -0700179 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700180 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700181
Yi Jinc23fad22017-09-15 17:24:59 -0700182 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700183 if (err != NO_ERROR) { requests->setMainFd(-1); goto DONE; }
Yi Jinc23fad22017-09-15 17:24:59 -0700184 err = privacyBuffer.flush(requests->mainFd());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700185 if (err != NO_ERROR) { requests->setMainFd(-1); goto DONE; }
186 writeable++;
Yi Jinc23fad22017-09-15 17:24:59 -0700187 ALOGD("Section %d flushed %zu bytes to dropbox %d", id, privacyBuffer.size(), requests->mainFd());
Yi Jin99c248f2017-08-25 18:11:58 -0700188 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700189
190DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700191 // only returns error if there is no fd to write to.
192 return writeable > 0 ? NO_ERROR : err;
193}
194
195// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700196Section::Section(int i, const int64_t timeoutMs)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700197 :id(i),
198 timeoutMs(timeoutMs)
Joe Onorato1754d742016-11-21 17:51:35 -0800199{
200}
201
202Section::~Section()
203{
204}
205
Joe Onorato1754d742016-11-21 17:51:35 -0800206// ================================================================================
Yi Jinedfd5bb2017-09-06 17:09:11 -0700207HeaderSection::HeaderSection()
208 :Section(FIELD_ID_INCIDENT_HEADER, 0)
209{
210}
211
212HeaderSection::~HeaderSection()
213{
214}
215
216status_t
217HeaderSection::Execute(ReportRequestSet* requests) const
218{
219 for (ReportRequestSet::iterator it=requests->begin(); it!=requests->end(); it++) {
220 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800221 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700222
Yi Jinbdf58942017-11-14 17:58:19 -0800223 for (vector<vector<uint8_t>>::const_iterator buf=headers.begin(); buf!=headers.end(); buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700224 if (buf->empty()) continue;
225
226 // So the idea is only requests with negative fd are written to dropbox file.
227 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
228 write_section_header(fd, FIELD_ID_INCIDENT_HEADER, buf->size());
229 write_all(fd, (uint8_t const*)buf->data(), buf->size());
230 // If there was an error now, there will be an error later and we will remove
231 // it from the list then.
232 }
233 }
234 return NO_ERROR;
235}
236
237// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700238FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700239 :Section(id, timeoutMs),
240 mFilename(filename)
241{
Yi Jinb44f7d42017-07-21 12:12:59 -0700242 name = filename;
Yi Jin0eb22342017-11-06 17:17:27 -0800243 mIsSysfs = strncmp(filename, "/sys/", 5) == 0;
Yi Jin0a3406f2017-06-22 19:23:11 -0700244}
245
246FileSection::~FileSection() {}
247
Yi Jin99c248f2017-08-25 18:11:58 -0700248status_t
249FileSection::Execute(ReportRequestSet* requests) const
250{
Yi Jinb44f7d42017-07-21 12:12:59 -0700251 // read from mFilename first, make sure the file is available
252 // add O_CLOEXEC to make sure it is closed when exec incident helper
George Burgess IV6f9735b2017-08-03 16:08:29 -0700253 int fd = open(mFilename, O_RDONLY | O_CLOEXEC);
Yi Jin0a3406f2017-06-22 19:23:11 -0700254 if (fd == -1) {
255 ALOGW("FileSection '%s' failed to open file", this->name.string());
256 return -errno;
257 }
258
Yi Jinb44f7d42017-07-21 12:12:59 -0700259 FdBuffer buffer;
260 Fpipe p2cPipe;
261 Fpipe c2pPipe;
262 // initiate pipes to pass data to/from incident_helper
263 if (!p2cPipe.init() || !c2pPipe.init()) {
264 ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700265 return -errno;
266 }
267
Yi Jinedfd5bb2017-09-06 17:09:11 -0700268 pid_t pid = fork_execute_incident_helper(this->id, this->name.string(), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700269 if (pid == -1) {
270 ALOGW("FileSection '%s' failed to fork", this->name.string());
271 return -errno;
272 }
273
274 // parent process
275 status_t readStatus = buffer.readProcessedDataInStream(fd, p2cPipe.writeFd(), c2pPipe.readFd(),
Yi Jin0eb22342017-11-06 17:17:27 -0800276 this->timeoutMs, mIsSysfs);
Yi Jinb44f7d42017-07-21 12:12:59 -0700277 if (readStatus != NO_ERROR || buffer.timedOut()) {
278 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s, kill: %s",
279 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false",
Yi Jinedfd5bb2017-09-06 17:09:11 -0700280 strerror(-kill_child(pid)));
Yi Jinb44f7d42017-07-21 12:12:59 -0700281 return readStatus;
282 }
283
Yi Jinedfd5bb2017-09-06 17:09:11 -0700284 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700285 if (ihStatus != NO_ERROR) {
286 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(), strerror(-ihStatus));
287 return ihStatus;
288 }
289
290 ALOGD("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
Yi Jin0a3406f2017-06-22 19:23:11 -0700291 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700292 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700293 if (err != NO_ERROR) {
294 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
295 return err;
296 }
297
298 return NO_ERROR;
299}
300
301// ================================================================================
Joe Onorato1754d742016-11-21 17:51:35 -0800302struct WorkerThreadData : public virtual RefBase
303{
304 const WorkerThreadSection* section;
305 int fds[2];
306
307 // Lock protects these fields
308 mutex lock;
309 bool workerDone;
310 status_t workerError;
311
312 WorkerThreadData(const WorkerThreadSection* section);
313 virtual ~WorkerThreadData();
314
315 int readFd() { return fds[0]; }
316 int writeFd() { return fds[1]; }
317};
318
319WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
320 :section(sec),
321 workerDone(false),
322 workerError(NO_ERROR)
323{
324 fds[0] = -1;
325 fds[1] = -1;
326}
327
328WorkerThreadData::~WorkerThreadData()
329{
330}
331
332// ================================================================================
333WorkerThreadSection::WorkerThreadSection(int id)
334 :Section(id)
335{
336}
337
338WorkerThreadSection::~WorkerThreadSection()
339{
340}
341
342static void*
343worker_thread_func(void* cookie)
344{
345 WorkerThreadData* data = (WorkerThreadData*)cookie;
346 status_t err = data->section->BlockingCall(data->writeFd());
347
348 {
349 unique_lock<mutex> lock(data->lock);
350 data->workerDone = true;
351 data->workerError = err;
352 }
353
354 close(data->writeFd());
355 data->decStrong(data->section);
356 // data might be gone now. don't use it after this point in this thread.
357 return NULL;
358}
359
360status_t
361WorkerThreadSection::Execute(ReportRequestSet* requests) const
362{
363 status_t err = NO_ERROR;
364 pthread_t thread;
365 pthread_attr_t attr;
366 bool timedOut = false;
367 FdBuffer buffer;
368
369 // Data shared between this thread and the worker thread.
370 sp<WorkerThreadData> data = new WorkerThreadData(this);
371
372 // Create the pipe
373 err = pipe(data->fds);
374 if (err != 0) {
375 return -errno;
376 }
377
378 // The worker thread needs a reference and we can't let the count go to zero
379 // if that thread is slow to start.
380 data->incStrong(this);
381
382 // Create the thread
383 err = pthread_attr_init(&attr);
384 if (err != 0) {
385 return -err;
386 }
387 // TODO: Do we need to tweak thread priority?
388 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
389 if (err != 0) {
390 pthread_attr_destroy(&attr);
391 return -err;
392 }
393 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
394 if (err != 0) {
395 pthread_attr_destroy(&attr);
396 return -err;
397 }
398 pthread_attr_destroy(&attr);
399
400 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jinb44f7d42017-07-21 12:12:59 -0700401 err = buffer.read(data->readFd(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800402 if (err != NO_ERROR) {
403 // TODO: Log this error into the incident report.
404 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
405 strerror(-err));
406 }
407
408 // Done with the read fd. The worker thread closes the write one so
409 // we never race and get here first.
410 close(data->readFd());
411
412 // If the worker side is finished, then return its error (which may overwrite
413 // our possible error -- but it's more interesting anyway). If not, then we timed out.
414 {
415 unique_lock<mutex> lock(data->lock);
416 if (!data->workerDone) {
417 // We timed out
418 timedOut = true;
419 } else {
420 if (data->workerError != NO_ERROR) {
421 err = data->workerError;
422 // TODO: Log this error into the incident report.
423 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
424 strerror(-err));
425 }
426 }
427 }
428
429 if (timedOut || buffer.timedOut()) {
430 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
431 return NO_ERROR;
432 }
433
434 if (buffer.truncated()) {
435 // TODO: Log this into the incident report.
436 }
437
438 // TODO: There was an error with the command or buffering. Report that. For now
439 // just exit with a log messasge.
440 if (err != NO_ERROR) {
441 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
442 strerror(-err));
443 return NO_ERROR;
444 }
445
446 // Write the data that was collected
Yi Jinb44f7d42017-07-21 12:12:59 -0700447 ALOGD("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
Joe Onorato1754d742016-11-21 17:51:35 -0800448 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700449 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800450 if (err != NO_ERROR) {
451 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
452 return err;
453 }
454
455 return NO_ERROR;
456}
457
458// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700459void
460CommandSection::init(const char* command, va_list args)
Yi Jinb44f7d42017-07-21 12:12:59 -0700461{
462 va_list copied_args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700463 int numOfArgs = 0;
Yi Jin4ef28b72017-08-14 14:45:28 -0700464
465 va_copy(copied_args, args);
466 while(va_arg(copied_args, const char*) != NULL) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700467 numOfArgs++;
468 }
Yi Jin4ef28b72017-08-14 14:45:28 -0700469 va_end(copied_args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700470
471 // allocate extra 1 for command and 1 for NULL terminator
472 mCommand = (const char**)malloc(sizeof(const char*) * (numOfArgs + 2));
473
474 mCommand[0] = command;
475 name = command;
476 for (int i=0; i<numOfArgs; i++) {
Yi Jin4ef28b72017-08-14 14:45:28 -0700477 const char* arg = va_arg(args, const char*);
Yi Jinb44f7d42017-07-21 12:12:59 -0700478 mCommand[i+1] = arg;
479 name += " ";
480 name += arg;
481 }
482 mCommand[numOfArgs+1] = NULL;
Yi Jinb44f7d42017-07-21 12:12:59 -0700483}
484
485CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700486 :Section(id, timeoutMs)
Joe Onorato1754d742016-11-21 17:51:35 -0800487{
488 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700489 va_start(args, command);
490 init(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800491 va_end(args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700492}
Joe Onorato1754d742016-11-21 17:51:35 -0800493
Yi Jinb44f7d42017-07-21 12:12:59 -0700494CommandSection::CommandSection(int id, const char* command, ...)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700495 :Section(id)
Yi Jinb44f7d42017-07-21 12:12:59 -0700496{
497 va_list args;
498 va_start(args, command);
499 init(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800500 va_end(args);
501}
502
503CommandSection::~CommandSection()
504{
Yi Jinb44f7d42017-07-21 12:12:59 -0700505 free(mCommand);
Joe Onorato1754d742016-11-21 17:51:35 -0800506}
507
508status_t
Yi Jinb44f7d42017-07-21 12:12:59 -0700509CommandSection::Execute(ReportRequestSet* requests) const
Joe Onorato1754d742016-11-21 17:51:35 -0800510{
Yi Jinb44f7d42017-07-21 12:12:59 -0700511 FdBuffer buffer;
512 Fpipe cmdPipe;
513 Fpipe ihPipe;
514
515 if (!cmdPipe.init() || !ihPipe.init()) {
516 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
517 return -errno;
518 }
519
520 pid_t cmdPid = fork();
521 if (cmdPid == -1) {
522 ALOGW("CommandSection '%s' failed to fork", this->name.string());
523 return -errno;
524 }
525 // child process to execute the command as root
526 if (cmdPid == 0) {
527 // replace command's stdout with ihPipe's write Fd
528 if (dup2(cmdPipe.writeFd(), STDOUT_FILENO) != 1 || !ihPipe.close() || !cmdPipe.close()) {
529 ALOGW("CommandSection '%s' failed to set up stdout: %s", this->name.string(), strerror(errno));
530 _exit(EXIT_FAILURE);
531 }
Kweku Adamsf5cc5752017-12-20 17:59:17 -0800532 execvp(this->mCommand[0], (char *const *) this->mCommand);
Yi Jinb44f7d42017-07-21 12:12:59 -0700533 int err = errno; // record command error code
534 ALOGW("CommandSection '%s' failed in executing command: %s", this->name.string(), strerror(errno));
535 _exit(err); // exit with command error code
536 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700537 pid_t ihPid = fork_execute_incident_helper(this->id, this->name.string(), cmdPipe, ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700538 if (ihPid == -1) {
539 ALOGW("CommandSection '%s' failed to fork", this->name.string());
540 return -errno;
541 }
542
543 close(cmdPipe.writeFd());
544 status_t readStatus = buffer.read(ihPipe.readFd(), this->timeoutMs);
545 if (readStatus != NO_ERROR || buffer.timedOut()) {
546 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, "
547 "timedout: %s, kill command: %s, kill incident helper: %s",
548 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false",
Yi Jinedfd5bb2017-09-06 17:09:11 -0700549 strerror(-kill_child(cmdPid)), strerror(-kill_child(ihPid)));
Yi Jinb44f7d42017-07-21 12:12:59 -0700550 return readStatus;
551 }
552
553 // TODO: wait for command here has one trade-off: the failed status of command won't be detected until
554 // buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700555 status_t cmdStatus = wait_child(cmdPid);
556 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700557 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinadd11e92017-07-30 16:10:07 -0700558 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident helper: %s",
Yi Jinb44f7d42017-07-21 12:12:59 -0700559 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
560 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
561 }
562
563 ALOGD("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
564 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700565 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700566 if (err != NO_ERROR) {
567 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
568 return err;
569 }
Joe Onorato1754d742016-11-21 17:51:35 -0800570 return NO_ERROR;
571}
572
573// ================================================================================
574DumpsysSection::DumpsysSection(int id, const char* service, ...)
575 :WorkerThreadSection(id),
576 mService(service)
577{
578 name = "dumpsys ";
579 name += service;
580
581 va_list args;
582 va_start(args, service);
583 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700584 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800585 if (arg == NULL) {
586 break;
587 }
588 mArgs.add(String16(arg));
589 name += " ";
590 name += arg;
591 }
592 va_end(args);
593}
594
595DumpsysSection::~DumpsysSection()
596{
597}
598
599status_t
600DumpsysSection::BlockingCall(int pipeWriteFd) const
601{
602 // checkService won't wait for the service to show up like getService will.
603 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700604
Joe Onorato1754d742016-11-21 17:51:35 -0800605 if (service == NULL) {
606 // Returning an error interrupts the entire incident report, so just
607 // log the failure.
608 // TODO: have a meta record inside the report that would log this
609 // failure inside the report, because the fact that we can't find
610 // the service is good data in and of itself. This is running in
611 // another thread so lock that carefully...
612 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
613 return NO_ERROR;
614 }
615
616 service->dump(pipeWriteFd, mArgs);
617
618 return NO_ERROR;
619}
Yi Jin3c034c92017-12-22 17:36:47 -0800620
621// ================================================================================
622// initialization only once in Section.cpp.
623map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
624
625LogSection::LogSection(int id, log_id_t logID)
626 :WorkerThreadSection(id),
627 mLogID(logID)
628{
629 name += "logcat ";
630 name += android_log_id_to_name(logID);
631 switch (logID) {
632 case LOG_ID_EVENTS:
633 case LOG_ID_STATS:
634 case LOG_ID_SECURITY:
635 mBinary = true;
636 break;
637 default:
638 mBinary = false;
639 }
640}
641
642LogSection::~LogSection()
643{
644}
645
646static size_t
647trimTail(char const* buf, size_t len)
648{
649 while (len > 0) {
650 char c = buf[len - 1];
651 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
652 len--;
653 } else {
654 break;
655 }
656 }
657 return len;
658}
659
660static inline int32_t get4LE(uint8_t const* src) {
661 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
662}
663
664status_t
665LogSection::BlockingCall(int pipeWriteFd) const
666{
667 status_t err = NO_ERROR;
668 // Open log buffer and getting logs since last retrieved time if any.
669 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
670 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end() ?
671 android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0) :
672 android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
673 gLastLogsRetrieved[mLogID], 0),
674 android_logger_list_free);
675
676 if (android_logger_open(loggers.get(), mLogID) == NULL) {
677 ALOGW("LogSection %s: Can't get logger.", this->name.string());
678 return err;
679 }
680
681 log_msg msg;
682 log_time lastTimestamp(0);
683
684 ProtoOutputStream proto;
685 while (true) { // keeps reading until logd buffer is fully read.
686 status_t err = android_logger_list_read(loggers.get(), &msg);
687 // err = 0 - no content, unexpected connection drop or EOF.
688 // err = +ive number - size of retrieved data from logger
689 // err = -ive number, OS supplied error _except_ for -EAGAIN
690 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
691 if (err <= 0) {
692 if (err != -EAGAIN) {
693 ALOGE("LogSection %s: fails to read a log_msg.\n", this->name.string());
694 }
695 break;
696 }
697 if (mBinary) {
698 // remove the first uint32 which is tag's index in event log tags
699 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
700 msg.len() - sizeof(uint32_t));;
701 android_log_list_element elem;
702
703 lastTimestamp.tv_sec = msg.entry_v1.sec;
704 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
705
706 // format a BinaryLogEntry
707 long long token = proto.start(LogProto::BINARY_LOGS);
708 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
709 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
710 proto.write(BinaryLogEntry::UID, (int) msg.entry_v4.uid);
711 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
712 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
713 proto.write(BinaryLogEntry::TAG_INDEX, get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
714 do {
715 elem = android_log_read_next(context);
716 long long elemToken = proto.start(BinaryLogEntry::ELEMS);
717 switch (elem.type) {
718 case EVENT_TYPE_INT:
719 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_INT);
720 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int) elem.data.int32);
721 break;
722 case EVENT_TYPE_LONG:
723 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LONG);
724 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long) elem.data.int64);
725 break;
726 case EVENT_TYPE_STRING:
727 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_STRING);
728 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
729 break;
730 case EVENT_TYPE_FLOAT:
731 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
732 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
733 break;
734 case EVENT_TYPE_LIST:
735 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LIST);
736 break;
737 case EVENT_TYPE_LIST_STOP:
738 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
739 break;
740 case EVENT_TYPE_UNKNOWN:
741 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
742 break;
743 }
744 proto.end(elemToken);
745 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
746 proto.end(token);
747 if (context) {
748 android_log_destroy(&context);
749 }
750 } else {
751 AndroidLogEntry entry;
752 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
753 if (err != NO_ERROR) {
754 ALOGE("LogSection %s: fails to process to an entry.\n", this->name.string());
755 break;
756 }
757 lastTimestamp.tv_sec = entry.tv_sec;
758 lastTimestamp.tv_nsec = entry.tv_nsec;
759
760 // format a TextLogEntry
761 long long token = proto.start(LogProto::TEXT_LOGS);
762 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
763 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
764 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
765 proto.write(TextLogEntry::UID, entry.uid);
766 proto.write(TextLogEntry::PID, entry.pid);
767 proto.write(TextLogEntry::TID, entry.tid);
768 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
769 proto.write(TextLogEntry::LOG, entry.message, trimTail(entry.message, entry.messageLen));
770 proto.end(token);
771 }
772 }
773 gLastLogsRetrieved[mLogID] = lastTimestamp;
774 proto.flush(pipeWriteFd);
775 return err;
776}