blob: faeab87f81780ae7bf74e45fbac64ffcae86ac11 [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;
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 // fork used in multithreaded environment, avoid adding unnecessary code in child process
59 pid_t pid = fork();
60 if (pid == 0) {
Yi Jin4bab3a12018-01-10 16:50:59 -080061 if (TEMP_FAILURE_RETRY(dup2(p2cPipe.readFd(), STDIN_FILENO)) != 0
62 || !p2cPipe.close()
63 || TEMP_FAILURE_RETRY(dup2(c2pPipe.writeFd(), STDOUT_FILENO)) != 1
64 || !c2pPipe.close()) {
Yi Jinb44f7d42017-07-21 12:12:59 -070065 ALOGW("%s can't setup stdin and stdout for incident helper", name);
66 _exit(EXIT_FAILURE);
67 }
68
Yi Jin4bab3a12018-01-10 16:50:59 -080069 /* make sure the child dies when incidentd dies */
70 prctl(PR_SET_PDEATHSIG, SIGKILL);
71
Yi Jinb44f7d42017-07-21 12:12:59 -070072 execv(INCIDENT_HELPER, const_cast<char**>(ihArgs));
73
74 ALOGW("%s failed in incident helper process: %s", name, strerror(errno));
75 _exit(EXIT_FAILURE); // always exits with failure if any
76 }
77 // close the fds used in incident helper
78 close(p2cPipe.readFd());
79 close(c2pPipe.writeFd());
80 return pid;
81}
82
Yi Jin99c248f2017-08-25 18:11:58 -070083// ================================================================================
Yi Jin4bab3a12018-01-10 16:50:59 -080084static status_t statusCode(int status) {
85 if (WIFSIGNALED(status)) {
86 ALOGD("return by signal: %s", strerror(WTERMSIG(status)));
87 return -WTERMSIG(status);
88 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
89 ALOGD("return by exit: %s", strerror(WEXITSTATUS(status)));
90 return -WEXITSTATUS(status);
91 }
92 return NO_ERROR;
93}
94
Yi Jinedfd5bb2017-09-06 17:09:11 -070095static status_t kill_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -070096 int status;
Yi Jin4bab3a12018-01-10 16:50:59 -080097 ALOGD("try to kill child process %d", pid);
Yi Jinb44f7d42017-07-21 12:12:59 -070098 kill(pid, SIGKILL);
99 if (waitpid(pid, &status, 0) == -1) return -1;
Yi Jin4bab3a12018-01-10 16:50:59 -0800100 return statusCode(status);
Yi Jinb44f7d42017-07-21 12:12:59 -0700101}
102
Yi Jinedfd5bb2017-09-06 17:09:11 -0700103static status_t wait_child(pid_t pid) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700104 int status;
105 bool died = false;
106 // wait for child to report status up to 1 seconds
107 for(int loop = 0; !died && loop < WAIT_MAX; loop++) {
108 if (waitpid(pid, &status, WNOHANG) == pid) died = true;
109 // sleep for 0.2 second
110 nanosleep(&WAIT_INTERVAL_NS, NULL);
111 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700112 if (!died) return kill_child(pid);
Yi Jin4bab3a12018-01-10 16:50:59 -0800113 return statusCode(status);
Yi Jinb44f7d42017-07-21 12:12:59 -0700114}
Joe Onorato1754d742016-11-21 17:51:35 -0800115// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700116static const Privacy*
Yi Jinedfd5bb2017-09-06 17:09:11 -0700117get_privacy_of_section(int id)
Yi Jin99c248f2017-08-25 18:11:58 -0700118{
Yi Jin7e0b4e52017-09-12 20:00:25 -0700119 int l = 0;
120 int r = PRIVACY_POLICY_COUNT - 1;
121 while (l <= r) {
122 int mid = (l + r) >> 1;
123 const Privacy* p = PRIVACY_POLICY_LIST[mid];
124
125 if (p->field_id < (uint32_t)id) {
126 l = mid + 1;
127 } else if (p->field_id > (uint32_t)id) {
128 r = mid - 1;
129 } else {
130 return p;
131 }
Yi Jin99c248f2017-08-25 18:11:58 -0700132 }
133 return NULL;
134}
135
Yi Jinedfd5bb2017-09-06 17:09:11 -0700136// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700137static status_t
Yi Jinedfd5bb2017-09-06 17:09:11 -0700138write_section_header(int fd, int sectionId, size_t size)
Yi Jin99c248f2017-08-25 18:11:58 -0700139{
Yi Jin99c248f2017-08-25 18:11:58 -0700140 uint8_t buf[20];
Yi Jinedfd5bb2017-09-06 17:09:11 -0700141 uint8_t *p = write_length_delimited_tag_header(buf, sectionId, size);
142 return write_all(fd, buf, p-buf);
Yi Jin99c248f2017-08-25 18:11:58 -0700143}
144
145static status_t
Yi Jinedfd5bb2017-09-06 17:09:11 -0700146write_report_requests(const int id, const FdBuffer& buffer, ReportRequestSet* requests)
Yi Jin99c248f2017-08-25 18:11:58 -0700147{
Yi Jin0f047162017-09-05 13:44:22 -0700148 status_t err = -EBADF;
Yi Jinc23fad22017-09-15 17:24:59 -0700149 EncodedBuffer::iterator data = buffer.data();
150 PrivacyBuffer privacyBuffer(get_privacy_of_section(id), data);
Yi Jin99c248f2017-08-25 18:11:58 -0700151 int writeable = 0;
152
Yi Jin0f047162017-09-05 13:44:22 -0700153 // The streaming ones, group requests by spec in order to save unnecessary strip operations
154 map<PrivacySpec, vector<sp<ReportRequest>>> requestsBySpec;
Yi Jin3ec5cc72018-01-26 13:42:43 -0800155 for (auto it = requests->begin(); it != requests->end(); it++) {
Yi Jin99c248f2017-08-25 18:11:58 -0700156 sp<ReportRequest> request = *it;
Yi Jinedfd5bb2017-09-06 17:09:11 -0700157 if (!request->ok() || !request->args.containsSection(id)) {
Yi Jin0f047162017-09-05 13:44:22 -0700158 continue; // skip invalid request
Yi Jin99c248f2017-08-25 18:11:58 -0700159 }
Yi Jin3ec5cc72018-01-26 13:42:43 -0800160 PrivacySpec spec = PrivacySpec::new_spec(request->args.dest());
Yi Jin0f047162017-09-05 13:44:22 -0700161 requestsBySpec[spec].push_back(request);
162 }
163
Yi Jin3ec5cc72018-01-26 13:42:43 -0800164 for (auto mit = requestsBySpec.begin(); mit != requestsBySpec.end(); mit++) {
Yi Jin0f047162017-09-05 13:44:22 -0700165 PrivacySpec spec = mit->first;
Yi Jinc23fad22017-09-15 17:24:59 -0700166 err = privacyBuffer.strip(spec);
167 if (err != NO_ERROR) return err; // it means the privacyBuffer data is corrupted.
168 if (privacyBuffer.size() == 0) continue;
Yi Jin0f047162017-09-05 13:44:22 -0700169
Yi Jin3ec5cc72018-01-26 13:42:43 -0800170 for (auto it = mit->second.begin(); it != mit->second.end(); it++) {
Yi Jin0f047162017-09-05 13:44:22 -0700171 sp<ReportRequest> request = *it;
Yi Jinc23fad22017-09-15 17:24:59 -0700172 err = write_section_header(request->fd, id, privacyBuffer.size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700173 if (err != NO_ERROR) { request->err = err; continue; }
Yi Jinc23fad22017-09-15 17:24:59 -0700174 err = privacyBuffer.flush(request->fd);
Yi Jinedfd5bb2017-09-06 17:09:11 -0700175 if (err != NO_ERROR) { request->err = err; continue; }
176 writeable++;
Yi Jin3ec5cc72018-01-26 13:42:43 -0800177 ALOGD("Section %d flushed %zu bytes to fd %d with spec %d", id,
178 privacyBuffer.size(), request->fd, spec.dest);
Yi Jin0f047162017-09-05 13:44:22 -0700179 }
Yi Jinc23fad22017-09-15 17:24:59 -0700180 privacyBuffer.clear();
Yi Jin99c248f2017-08-25 18:11:58 -0700181 }
182
183 // The dropbox file
184 if (requests->mainFd() >= 0) {
Yi Jin3ec5cc72018-01-26 13:42:43 -0800185 PrivacySpec spec = requests->mainDest() < 0 ?
186 PrivacySpec::get_default_dropbox_spec() :
187 PrivacySpec::new_spec(requests->mainDest());
188 err = privacyBuffer.strip(spec);
Yi Jin0f047162017-09-05 13:44:22 -0700189 if (err != NO_ERROR) return err; // the buffer data is corrupted.
Yi Jinc23fad22017-09-15 17:24:59 -0700190 if (privacyBuffer.size() == 0) goto DONE;
Yi Jin0f047162017-09-05 13:44:22 -0700191
Yi Jinc23fad22017-09-15 17:24:59 -0700192 err = write_section_header(requests->mainFd(), id, privacyBuffer.size());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700193 if (err != NO_ERROR) { requests->setMainFd(-1); goto DONE; }
Yi Jinc23fad22017-09-15 17:24:59 -0700194 err = privacyBuffer.flush(requests->mainFd());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700195 if (err != NO_ERROR) { requests->setMainFd(-1); goto DONE; }
196 writeable++;
Yi Jin3ec5cc72018-01-26 13:42:43 -0800197 ALOGD("Section %d flushed %zu bytes to dropbox %d with spec %d", id,
198 privacyBuffer.size(), requests->mainFd(), spec.dest);
Yi Jin99c248f2017-08-25 18:11:58 -0700199 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700200
201DONE:
Yi Jin99c248f2017-08-25 18:11:58 -0700202 // only returns error if there is no fd to write to.
203 return writeable > 0 ? NO_ERROR : err;
204}
205
206// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700207Section::Section(int i, const int64_t timeoutMs)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700208 :id(i),
209 timeoutMs(timeoutMs)
Joe Onorato1754d742016-11-21 17:51:35 -0800210{
211}
212
213Section::~Section()
214{
215}
216
Joe Onorato1754d742016-11-21 17:51:35 -0800217// ================================================================================
Yi Jinedfd5bb2017-09-06 17:09:11 -0700218HeaderSection::HeaderSection()
219 :Section(FIELD_ID_INCIDENT_HEADER, 0)
220{
221}
222
223HeaderSection::~HeaderSection()
224{
225}
226
227status_t
228HeaderSection::Execute(ReportRequestSet* requests) const
229{
230 for (ReportRequestSet::iterator it=requests->begin(); it!=requests->end(); it++) {
231 const sp<ReportRequest> request = *it;
Yi Jinbdf58942017-11-14 17:58:19 -0800232 const vector<vector<uint8_t>>& headers = request->args.headers();
Yi Jinedfd5bb2017-09-06 17:09:11 -0700233
Yi Jinbdf58942017-11-14 17:58:19 -0800234 for (vector<vector<uint8_t>>::const_iterator buf=headers.begin(); buf!=headers.end(); buf++) {
Yi Jinedfd5bb2017-09-06 17:09:11 -0700235 if (buf->empty()) continue;
236
237 // So the idea is only requests with negative fd are written to dropbox file.
238 int fd = request->fd >= 0 ? request->fd : requests->mainFd();
239 write_section_header(fd, FIELD_ID_INCIDENT_HEADER, buf->size());
240 write_all(fd, (uint8_t const*)buf->data(), buf->size());
241 // If there was an error now, there will be an error later and we will remove
242 // it from the list then.
243 }
244 }
245 return NO_ERROR;
246}
247
248// ================================================================================
Yi Jinb44f7d42017-07-21 12:12:59 -0700249FileSection::FileSection(int id, const char* filename, const int64_t timeoutMs)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700250 :Section(id, timeoutMs),
251 mFilename(filename)
252{
Yi Jinb44f7d42017-07-21 12:12:59 -0700253 name = filename;
Yi Jin0eb22342017-11-06 17:17:27 -0800254 mIsSysfs = strncmp(filename, "/sys/", 5) == 0;
Yi Jin0a3406f2017-06-22 19:23:11 -0700255}
256
257FileSection::~FileSection() {}
258
Yi Jin99c248f2017-08-25 18:11:58 -0700259status_t
260FileSection::Execute(ReportRequestSet* requests) const
261{
Yi Jinb44f7d42017-07-21 12:12:59 -0700262 // read from mFilename first, make sure the file is available
263 // add O_CLOEXEC to make sure it is closed when exec incident helper
George Burgess IV6f9735b2017-08-03 16:08:29 -0700264 int fd = open(mFilename, O_RDONLY | O_CLOEXEC);
Yi Jin0a3406f2017-06-22 19:23:11 -0700265 if (fd == -1) {
266 ALOGW("FileSection '%s' failed to open file", this->name.string());
267 return -errno;
268 }
269
Yi Jinb44f7d42017-07-21 12:12:59 -0700270 FdBuffer buffer;
271 Fpipe p2cPipe;
272 Fpipe c2pPipe;
273 // initiate pipes to pass data to/from incident_helper
274 if (!p2cPipe.init() || !c2pPipe.init()) {
275 ALOGW("FileSection '%s' failed to setup pipes", this->name.string());
Yi Jin0a3406f2017-06-22 19:23:11 -0700276 return -errno;
277 }
278
Yi Jinedfd5bb2017-09-06 17:09:11 -0700279 pid_t pid = fork_execute_incident_helper(this->id, this->name.string(), p2cPipe, c2pPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700280 if (pid == -1) {
281 ALOGW("FileSection '%s' failed to fork", this->name.string());
282 return -errno;
283 }
284
285 // parent process
286 status_t readStatus = buffer.readProcessedDataInStream(fd, p2cPipe.writeFd(), c2pPipe.readFd(),
Yi Jin0eb22342017-11-06 17:17:27 -0800287 this->timeoutMs, mIsSysfs);
Yi Jinb44f7d42017-07-21 12:12:59 -0700288 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800289 ALOGW("FileSection '%s' failed to read data from incident helper: %s, timedout: %s",
290 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
291 kill_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700292 return readStatus;
293 }
294
Yi Jinedfd5bb2017-09-06 17:09:11 -0700295 status_t ihStatus = wait_child(pid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700296 if (ihStatus != NO_ERROR) {
297 ALOGW("FileSection '%s' abnormal child process: %s", this->name.string(), strerror(-ihStatus));
298 return ihStatus;
299 }
300
301 ALOGD("FileSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
Yi Jin0a3406f2017-06-22 19:23:11 -0700302 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700303 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jin0a3406f2017-06-22 19:23:11 -0700304 if (err != NO_ERROR) {
305 ALOGW("FileSection '%s' failed writing: %s", this->name.string(), strerror(-err));
306 return err;
307 }
308
309 return NO_ERROR;
310}
311
312// ================================================================================
Joe Onorato1754d742016-11-21 17:51:35 -0800313struct WorkerThreadData : public virtual RefBase
314{
315 const WorkerThreadSection* section;
316 int fds[2];
317
318 // Lock protects these fields
319 mutex lock;
320 bool workerDone;
321 status_t workerError;
322
323 WorkerThreadData(const WorkerThreadSection* section);
324 virtual ~WorkerThreadData();
325
326 int readFd() { return fds[0]; }
327 int writeFd() { return fds[1]; }
328};
329
330WorkerThreadData::WorkerThreadData(const WorkerThreadSection* sec)
331 :section(sec),
332 workerDone(false),
333 workerError(NO_ERROR)
334{
335 fds[0] = -1;
336 fds[1] = -1;
337}
338
339WorkerThreadData::~WorkerThreadData()
340{
341}
342
343// ================================================================================
344WorkerThreadSection::WorkerThreadSection(int id)
345 :Section(id)
346{
347}
348
349WorkerThreadSection::~WorkerThreadSection()
350{
351}
352
353static void*
354worker_thread_func(void* cookie)
355{
356 WorkerThreadData* data = (WorkerThreadData*)cookie;
357 status_t err = data->section->BlockingCall(data->writeFd());
358
359 {
360 unique_lock<mutex> lock(data->lock);
361 data->workerDone = true;
362 data->workerError = err;
363 }
364
365 close(data->writeFd());
366 data->decStrong(data->section);
367 // data might be gone now. don't use it after this point in this thread.
368 return NULL;
369}
370
371status_t
372WorkerThreadSection::Execute(ReportRequestSet* requests) const
373{
374 status_t err = NO_ERROR;
375 pthread_t thread;
376 pthread_attr_t attr;
377 bool timedOut = false;
378 FdBuffer buffer;
379
380 // Data shared between this thread and the worker thread.
381 sp<WorkerThreadData> data = new WorkerThreadData(this);
382
383 // Create the pipe
384 err = pipe(data->fds);
385 if (err != 0) {
386 return -errno;
387 }
388
389 // The worker thread needs a reference and we can't let the count go to zero
390 // if that thread is slow to start.
391 data->incStrong(this);
392
393 // Create the thread
394 err = pthread_attr_init(&attr);
395 if (err != 0) {
396 return -err;
397 }
398 // TODO: Do we need to tweak thread priority?
399 err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
400 if (err != 0) {
401 pthread_attr_destroy(&attr);
402 return -err;
403 }
404 err = pthread_create(&thread, &attr, worker_thread_func, (void*)data.get());
405 if (err != 0) {
406 pthread_attr_destroy(&attr);
407 return -err;
408 }
409 pthread_attr_destroy(&attr);
410
411 // Loop reading until either the timeout or the worker side is done (i.e. eof).
Yi Jinb44f7d42017-07-21 12:12:59 -0700412 err = buffer.read(data->readFd(), this->timeoutMs);
Joe Onorato1754d742016-11-21 17:51:35 -0800413 if (err != NO_ERROR) {
414 // TODO: Log this error into the incident report.
415 ALOGW("WorkerThreadSection '%s' reader failed with error '%s'", this->name.string(),
416 strerror(-err));
417 }
418
419 // Done with the read fd. The worker thread closes the write one so
420 // we never race and get here first.
421 close(data->readFd());
422
423 // If the worker side is finished, then return its error (which may overwrite
424 // our possible error -- but it's more interesting anyway). If not, then we timed out.
425 {
426 unique_lock<mutex> lock(data->lock);
427 if (!data->workerDone) {
428 // We timed out
429 timedOut = true;
430 } else {
431 if (data->workerError != NO_ERROR) {
432 err = data->workerError;
433 // TODO: Log this error into the incident report.
434 ALOGW("WorkerThreadSection '%s' worker failed with error '%s'", this->name.string(),
435 strerror(-err));
436 }
437 }
438 }
439
440 if (timedOut || buffer.timedOut()) {
441 ALOGW("WorkerThreadSection '%s' timed out", this->name.string());
442 return NO_ERROR;
443 }
444
445 if (buffer.truncated()) {
446 // TODO: Log this into the incident report.
447 }
448
449 // TODO: There was an error with the command or buffering. Report that. For now
450 // just exit with a log messasge.
451 if (err != NO_ERROR) {
452 ALOGW("WorkerThreadSection '%s' failed with error '%s'", this->name.string(),
453 strerror(-err));
454 return NO_ERROR;
455 }
456
457 // Write the data that was collected
Yi Jinb44f7d42017-07-21 12:12:59 -0700458 ALOGD("WorkerThreadSection '%s' wrote %zd bytes in %d ms", name.string(), buffer.size(),
Joe Onorato1754d742016-11-21 17:51:35 -0800459 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700460 err = write_report_requests(this->id, buffer, requests);
Joe Onorato1754d742016-11-21 17:51:35 -0800461 if (err != NO_ERROR) {
462 ALOGW("WorkerThreadSection '%s' failed writing: '%s'", this->name.string(), strerror(-err));
463 return err;
464 }
465
466 return NO_ERROR;
467}
468
469// ================================================================================
Yi Jin99c248f2017-08-25 18:11:58 -0700470void
471CommandSection::init(const char* command, va_list args)
Yi Jinb44f7d42017-07-21 12:12:59 -0700472{
473 va_list copied_args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700474 int numOfArgs = 0;
Yi Jin4ef28b72017-08-14 14:45:28 -0700475
476 va_copy(copied_args, args);
477 while(va_arg(copied_args, const char*) != NULL) {
Yi Jinb44f7d42017-07-21 12:12:59 -0700478 numOfArgs++;
479 }
Yi Jin4ef28b72017-08-14 14:45:28 -0700480 va_end(copied_args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700481
482 // allocate extra 1 for command and 1 for NULL terminator
483 mCommand = (const char**)malloc(sizeof(const char*) * (numOfArgs + 2));
484
485 mCommand[0] = command;
486 name = command;
487 for (int i=0; i<numOfArgs; i++) {
Yi Jin4ef28b72017-08-14 14:45:28 -0700488 const char* arg = va_arg(args, const char*);
Yi Jinb44f7d42017-07-21 12:12:59 -0700489 mCommand[i+1] = arg;
490 name += " ";
491 name += arg;
492 }
493 mCommand[numOfArgs+1] = NULL;
Yi Jinb44f7d42017-07-21 12:12:59 -0700494}
495
496CommandSection::CommandSection(int id, const int64_t timeoutMs, const char* command, ...)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700497 :Section(id, timeoutMs)
Joe Onorato1754d742016-11-21 17:51:35 -0800498{
499 va_list args;
Yi Jinb44f7d42017-07-21 12:12:59 -0700500 va_start(args, command);
501 init(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800502 va_end(args);
Yi Jinb44f7d42017-07-21 12:12:59 -0700503}
Joe Onorato1754d742016-11-21 17:51:35 -0800504
Yi Jinb44f7d42017-07-21 12:12:59 -0700505CommandSection::CommandSection(int id, const char* command, ...)
Yi Jinedfd5bb2017-09-06 17:09:11 -0700506 :Section(id)
Yi Jinb44f7d42017-07-21 12:12:59 -0700507{
508 va_list args;
509 va_start(args, command);
510 init(command, args);
Joe Onorato1754d742016-11-21 17:51:35 -0800511 va_end(args);
512}
513
514CommandSection::~CommandSection()
515{
Yi Jinb44f7d42017-07-21 12:12:59 -0700516 free(mCommand);
Joe Onorato1754d742016-11-21 17:51:35 -0800517}
518
519status_t
Yi Jinb44f7d42017-07-21 12:12:59 -0700520CommandSection::Execute(ReportRequestSet* requests) const
Joe Onorato1754d742016-11-21 17:51:35 -0800521{
Yi Jinb44f7d42017-07-21 12:12:59 -0700522 FdBuffer buffer;
523 Fpipe cmdPipe;
524 Fpipe ihPipe;
525
526 if (!cmdPipe.init() || !ihPipe.init()) {
527 ALOGW("CommandSection '%s' failed to setup pipes", this->name.string());
528 return -errno;
529 }
530
531 pid_t cmdPid = fork();
532 if (cmdPid == -1) {
533 ALOGW("CommandSection '%s' failed to fork", this->name.string());
534 return -errno;
535 }
536 // child process to execute the command as root
537 if (cmdPid == 0) {
538 // replace command's stdout with ihPipe's write Fd
539 if (dup2(cmdPipe.writeFd(), STDOUT_FILENO) != 1 || !ihPipe.close() || !cmdPipe.close()) {
540 ALOGW("CommandSection '%s' failed to set up stdout: %s", this->name.string(), strerror(errno));
541 _exit(EXIT_FAILURE);
542 }
Kweku Adamsf5cc5752017-12-20 17:59:17 -0800543 execvp(this->mCommand[0], (char *const *) this->mCommand);
Yi Jinb44f7d42017-07-21 12:12:59 -0700544 int err = errno; // record command error code
545 ALOGW("CommandSection '%s' failed in executing command: %s", this->name.string(), strerror(errno));
546 _exit(err); // exit with command error code
547 }
Yi Jinedfd5bb2017-09-06 17:09:11 -0700548 pid_t ihPid = fork_execute_incident_helper(this->id, this->name.string(), cmdPipe, ihPipe);
Yi Jinb44f7d42017-07-21 12:12:59 -0700549 if (ihPid == -1) {
550 ALOGW("CommandSection '%s' failed to fork", this->name.string());
551 return -errno;
552 }
553
554 close(cmdPipe.writeFd());
555 status_t readStatus = buffer.read(ihPipe.readFd(), this->timeoutMs);
556 if (readStatus != NO_ERROR || buffer.timedOut()) {
Yi Jin4bab3a12018-01-10 16:50:59 -0800557 ALOGW("CommandSection '%s' failed to read data from incident helper: %s, timedout: %s",
558 this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
559 kill_child(cmdPid);
560 kill_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700561 return readStatus;
562 }
563
564 // TODO: wait for command here has one trade-off: the failed status of command won't be detected until
565 // buffer timeout, but it has advatage on starting the data stream earlier.
Yi Jinedfd5bb2017-09-06 17:09:11 -0700566 status_t cmdStatus = wait_child(cmdPid);
567 status_t ihStatus = wait_child(ihPid);
Yi Jinb44f7d42017-07-21 12:12:59 -0700568 if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
Yi Jinadd11e92017-07-30 16:10:07 -0700569 ALOGW("CommandSection '%s' abnormal child processes, return status: command: %s, incident helper: %s",
Yi Jinb44f7d42017-07-21 12:12:59 -0700570 this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
571 return cmdStatus != NO_ERROR ? cmdStatus : ihStatus;
572 }
573
574 ALOGD("CommandSection '%s' wrote %zd bytes in %d ms", this->name.string(), buffer.size(),
575 (int)buffer.durationMs());
Yi Jinedfd5bb2017-09-06 17:09:11 -0700576 status_t err = write_report_requests(this->id, buffer, requests);
Yi Jinb44f7d42017-07-21 12:12:59 -0700577 if (err != NO_ERROR) {
578 ALOGW("CommandSection '%s' failed writing: %s", this->name.string(), strerror(-err));
579 return err;
580 }
Joe Onorato1754d742016-11-21 17:51:35 -0800581 return NO_ERROR;
582}
583
584// ================================================================================
585DumpsysSection::DumpsysSection(int id, const char* service, ...)
586 :WorkerThreadSection(id),
587 mService(service)
588{
589 name = "dumpsys ";
590 name += service;
591
592 va_list args;
593 va_start(args, service);
594 while (true) {
Yi Jin0a3406f2017-06-22 19:23:11 -0700595 const char* arg = va_arg(args, const char*);
Joe Onorato1754d742016-11-21 17:51:35 -0800596 if (arg == NULL) {
597 break;
598 }
599 mArgs.add(String16(arg));
600 name += " ";
601 name += arg;
602 }
603 va_end(args);
604}
605
606DumpsysSection::~DumpsysSection()
607{
608}
609
610status_t
611DumpsysSection::BlockingCall(int pipeWriteFd) const
612{
613 // checkService won't wait for the service to show up like getService will.
614 sp<IBinder> service = defaultServiceManager()->checkService(mService);
Yi Jin0a3406f2017-06-22 19:23:11 -0700615
Joe Onorato1754d742016-11-21 17:51:35 -0800616 if (service == NULL) {
617 // Returning an error interrupts the entire incident report, so just
618 // log the failure.
619 // TODO: have a meta record inside the report that would log this
620 // failure inside the report, because the fact that we can't find
621 // the service is good data in and of itself. This is running in
622 // another thread so lock that carefully...
623 ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
624 return NO_ERROR;
625 }
626
627 service->dump(pipeWriteFd, mArgs);
628
629 return NO_ERROR;
630}
Yi Jin3c034c92017-12-22 17:36:47 -0800631
632// ================================================================================
633// initialization only once in Section.cpp.
634map<log_id_t, log_time> LogSection::gLastLogsRetrieved;
635
636LogSection::LogSection(int id, log_id_t logID)
637 :WorkerThreadSection(id),
638 mLogID(logID)
639{
640 name += "logcat ";
641 name += android_log_id_to_name(logID);
642 switch (logID) {
643 case LOG_ID_EVENTS:
644 case LOG_ID_STATS:
645 case LOG_ID_SECURITY:
646 mBinary = true;
647 break;
648 default:
649 mBinary = false;
650 }
651}
652
653LogSection::~LogSection()
654{
655}
656
657static size_t
658trimTail(char const* buf, size_t len)
659{
660 while (len > 0) {
661 char c = buf[len - 1];
662 if (c == '\0' || c == ' ' || c == '\n' || c == '\r' || c == ':') {
663 len--;
664 } else {
665 break;
666 }
667 }
668 return len;
669}
670
671static inline int32_t get4LE(uint8_t const* src) {
672 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
673}
674
675status_t
676LogSection::BlockingCall(int pipeWriteFd) const
677{
678 status_t err = NO_ERROR;
679 // Open log buffer and getting logs since last retrieved time if any.
680 unique_ptr<logger_list, void (*)(logger_list*)> loggers(
681 gLastLogsRetrieved.find(mLogID) == gLastLogsRetrieved.end() ?
682 android_logger_list_alloc(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 0, 0) :
683 android_logger_list_alloc_time(ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
684 gLastLogsRetrieved[mLogID], 0),
685 android_logger_list_free);
686
687 if (android_logger_open(loggers.get(), mLogID) == NULL) {
688 ALOGW("LogSection %s: Can't get logger.", this->name.string());
689 return err;
690 }
691
692 log_msg msg;
693 log_time lastTimestamp(0);
694
695 ProtoOutputStream proto;
696 while (true) { // keeps reading until logd buffer is fully read.
697 status_t err = android_logger_list_read(loggers.get(), &msg);
698 // err = 0 - no content, unexpected connection drop or EOF.
699 // err = +ive number - size of retrieved data from logger
700 // err = -ive number, OS supplied error _except_ for -EAGAIN
701 // err = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end of data.
702 if (err <= 0) {
703 if (err != -EAGAIN) {
704 ALOGE("LogSection %s: fails to read a log_msg.\n", this->name.string());
705 }
706 break;
707 }
708 if (mBinary) {
709 // remove the first uint32 which is tag's index in event log tags
710 android_log_context context = create_android_log_parser(msg.msg() + sizeof(uint32_t),
711 msg.len() - sizeof(uint32_t));;
712 android_log_list_element elem;
713
714 lastTimestamp.tv_sec = msg.entry_v1.sec;
715 lastTimestamp.tv_nsec = msg.entry_v1.nsec;
716
717 // format a BinaryLogEntry
718 long long token = proto.start(LogProto::BINARY_LOGS);
719 proto.write(BinaryLogEntry::SEC, msg.entry_v1.sec);
720 proto.write(BinaryLogEntry::NANOSEC, msg.entry_v1.nsec);
721 proto.write(BinaryLogEntry::UID, (int) msg.entry_v4.uid);
722 proto.write(BinaryLogEntry::PID, msg.entry_v1.pid);
723 proto.write(BinaryLogEntry::TID, msg.entry_v1.tid);
724 proto.write(BinaryLogEntry::TAG_INDEX, get4LE(reinterpret_cast<uint8_t const*>(msg.msg())));
725 do {
726 elem = android_log_read_next(context);
727 long long elemToken = proto.start(BinaryLogEntry::ELEMS);
728 switch (elem.type) {
729 case EVENT_TYPE_INT:
730 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_INT);
731 proto.write(BinaryLogEntry::Elem::VAL_INT32, (int) elem.data.int32);
732 break;
733 case EVENT_TYPE_LONG:
734 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LONG);
735 proto.write(BinaryLogEntry::Elem::VAL_INT64, (long long) elem.data.int64);
736 break;
737 case EVENT_TYPE_STRING:
738 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_STRING);
739 proto.write(BinaryLogEntry::Elem::VAL_STRING, elem.data.string, elem.len);
740 break;
741 case EVENT_TYPE_FLOAT:
742 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_FLOAT);
743 proto.write(BinaryLogEntry::Elem::VAL_FLOAT, elem.data.float32);
744 break;
745 case EVENT_TYPE_LIST:
746 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LIST);
747 break;
748 case EVENT_TYPE_LIST_STOP:
749 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_LIST_STOP);
750 break;
751 case EVENT_TYPE_UNKNOWN:
752 proto.write(BinaryLogEntry::Elem::TYPE, BinaryLogEntry::Elem::EVENT_TYPE_UNKNOWN);
753 break;
754 }
755 proto.end(elemToken);
756 } while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
757 proto.end(token);
758 if (context) {
759 android_log_destroy(&context);
760 }
761 } else {
762 AndroidLogEntry entry;
763 err = android_log_processLogBuffer(&msg.entry_v1, &entry);
764 if (err != NO_ERROR) {
765 ALOGE("LogSection %s: fails to process to an entry.\n", this->name.string());
766 break;
767 }
768 lastTimestamp.tv_sec = entry.tv_sec;
769 lastTimestamp.tv_nsec = entry.tv_nsec;
770
771 // format a TextLogEntry
772 long long token = proto.start(LogProto::TEXT_LOGS);
773 proto.write(TextLogEntry::SEC, (long long)entry.tv_sec);
774 proto.write(TextLogEntry::NANOSEC, (long long)entry.tv_nsec);
775 proto.write(TextLogEntry::PRIORITY, (int)entry.priority);
776 proto.write(TextLogEntry::UID, entry.uid);
777 proto.write(TextLogEntry::PID, entry.pid);
778 proto.write(TextLogEntry::TID, entry.tid);
779 proto.write(TextLogEntry::TAG, entry.tag, trimTail(entry.tag, entry.tagLen));
780 proto.write(TextLogEntry::LOG, entry.message, trimTail(entry.message, entry.messageLen));
781 proto.end(token);
782 }
783 }
784 gLastLogsRetrieved[mLogID] = lastTimestamp;
785 proto.flush(pipeWriteFd);
786 return err;
787}