blob: 78f62bdba3ef96dab91d8a84b59ac7fcd3b65fc2 [file] [log] [blame]
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <assert.h>
30#include <ctype.h>
31#include <errno.h>
32#include <fcntl.h>
33#include <pthread.h>
34#include <stdarg.h>
35#include <stddef.h>
36#include <stdlib.h>
37#include <string.h>
38#include <sys/mman.h>
39#include <sys/socket.h>
40#include <sys/types.h>
41#include <sys/uio.h>
42#include <sys/un.h>
43#include <time.h>
44#include <unistd.h>
45
46#include <android/set_abort_message.h>
47#include <async_safe/log.h>
48
49#include "private/CachedProperty.h"
50#include "private/ScopedPthreadMutexLocker.h"
51
52// Must be kept in sync with frameworks/base/core/java/android/util/EventLog.java.
53enum AndroidEventLogType {
54 EVENT_TYPE_INT = 0,
55 EVENT_TYPE_LONG = 1,
56 EVENT_TYPE_STRING = 2,
57 EVENT_TYPE_LIST = 3,
58 EVENT_TYPE_FLOAT = 4,
59};
60
61struct BufferOutputStream {
62 public:
Christopher Ferris92476402017-08-22 11:24:09 -070063 BufferOutputStream(char* buffer, size_t size) : total(0), pos_(buffer), avail_(size) {
64 if (avail_ > 0) pos_[0] = '\0';
Christopher Ferris7a3681e2017-04-24 17:48:32 -070065 }
Christopher Ferris92476402017-08-22 11:24:09 -070066 ~BufferOutputStream() = default;
Christopher Ferris7a3681e2017-04-24 17:48:32 -070067
68 void Send(const char* data, int len) {
69 if (len < 0) {
70 len = strlen(data);
71 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -070072 total += len;
73
Christopher Ferris92476402017-08-22 11:24:09 -070074 if (avail_ <= 1) {
75 // No space to put anything else.
76 return;
Christopher Ferris7a3681e2017-04-24 17:48:32 -070077 }
Christopher Ferris92476402017-08-22 11:24:09 -070078
79 if (static_cast<size_t>(len) >= avail_) {
80 len = avail_ - 1;
81 }
82 memcpy(pos_, data, len);
83 pos_ += len;
84 pos_[0] = '\0';
85 avail_ -= len;
Christopher Ferris7a3681e2017-04-24 17:48:32 -070086 }
87
88 size_t total;
89
90 private:
Christopher Ferris7a3681e2017-04-24 17:48:32 -070091 char* pos_;
Christopher Ferris92476402017-08-22 11:24:09 -070092 size_t avail_;
Christopher Ferris7a3681e2017-04-24 17:48:32 -070093};
94
95struct FdOutputStream {
96 public:
97 explicit FdOutputStream(int fd) : total(0), fd_(fd) {}
98
99 void Send(const char* data, int len) {
100 if (len < 0) {
101 len = strlen(data);
102 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700103 total += len;
104
105 while (len > 0) {
Christopher Ferris92476402017-08-22 11:24:09 -0700106 ssize_t bytes = TEMP_FAILURE_RETRY(write(fd_, data, len));
107 if (bytes == -1) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700108 return;
109 }
Christopher Ferris92476402017-08-22 11:24:09 -0700110 data += bytes;
111 len -= bytes;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700112 }
113 }
114
115 size_t total;
116
117 private:
118 int fd_;
119};
120
121/*** formatted output implementation
122 ***/
123
124/* Parse a decimal string from 'format + *ppos',
125 * return the value, and writes the new position past
126 * the decimal string in '*ppos' on exit.
127 *
128 * NOTE: Does *not* handle a sign prefix.
129 */
130static unsigned parse_decimal(const char* format, int* ppos) {
131 const char* p = format + *ppos;
132 unsigned result = 0;
133
134 for (;;) {
135 int ch = *p;
136 unsigned d = static_cast<unsigned>(ch - '0');
137
138 if (d >= 10U) {
139 break;
140 }
141
142 result = result * 10 + d;
143 p++;
144 }
145 *ppos = p - format;
146 return result;
147}
148
149// Writes number 'value' in base 'base' into buffer 'buf' of size 'buf_size' bytes.
150// Assumes that buf_size > 0.
151static void format_unsigned(char* buf, size_t buf_size, uint64_t value, int base, bool caps) {
152 char* p = buf;
153 char* end = buf + buf_size - 1;
154
155 // Generate digit string in reverse order.
156 while (value) {
157 unsigned d = value % base;
158 value /= base;
159 if (p != end) {
160 char ch;
161 if (d < 10) {
162 ch = '0' + d;
163 } else {
164 ch = (caps ? 'A' : 'a') + (d - 10);
165 }
166 *p++ = ch;
167 }
168 }
169
170 // Special case for 0.
171 if (p == buf) {
172 if (p != end) {
173 *p++ = '0';
174 }
175 }
176 *p = '\0';
177
178 // Reverse digit string in-place.
179 size_t length = p - buf;
180 for (size_t i = 0, j = length - 1; i < j; ++i, --j) {
181 char ch = buf[i];
182 buf[i] = buf[j];
183 buf[j] = ch;
184 }
185}
186
187static void format_integer(char* buf, size_t buf_size, uint64_t value, char conversion) {
188 // Decode the conversion specifier.
189 int is_signed = (conversion == 'd' || conversion == 'i' || conversion == 'o');
190 int base = 10;
191 if (conversion == 'x' || conversion == 'X') {
192 base = 16;
193 } else if (conversion == 'o') {
194 base = 8;
195 }
196 bool caps = (conversion == 'X');
197
198 if (is_signed && static_cast<int64_t>(value) < 0) {
199 buf[0] = '-';
200 buf += 1;
201 buf_size -= 1;
202 value = static_cast<uint64_t>(-static_cast<int64_t>(value));
203 }
204 format_unsigned(buf, buf_size, value, base, caps);
205}
206
207template <typename Out>
208static void SendRepeat(Out& o, char ch, int count) {
209 char pad[8];
210 memset(pad, ch, sizeof(pad));
211
212 const int pad_size = static_cast<int>(sizeof(pad));
213 while (count > 0) {
214 int avail = count;
215 if (avail > pad_size) {
216 avail = pad_size;
217 }
218 o.Send(pad, avail);
219 count -= avail;
220 }
221}
222
223/* Perform formatted output to an output target 'o' */
224template <typename Out>
225static void out_vformat(Out& o, const char* format, va_list args) {
226 int nn = 0;
227
228 for (;;) {
229 int mm;
230 int padZero = 0;
231 int padLeft = 0;
232 char sign = '\0';
233 int width = -1;
234 int prec = -1;
235 size_t bytelen = sizeof(int);
236 int slen;
237 char buffer[32]; /* temporary buffer used to format numbers */
238
239 char c;
240
241 /* first, find all characters that are not 0 or '%' */
242 /* then send them to the output directly */
243 mm = nn;
244 do {
245 c = format[mm];
246 if (c == '\0' || c == '%') break;
247 mm++;
248 } while (1);
249
250 if (mm > nn) {
251 o.Send(format + nn, mm - nn);
252 nn = mm;
253 }
254
255 /* is this it ? then exit */
256 if (c == '\0') break;
257
258 /* nope, we are at a '%' modifier */
259 nn++; // skip it
260
261 /* parse flags */
262 for (;;) {
263 c = format[nn++];
264 if (c == '\0') { /* single trailing '%' ? */
265 c = '%';
266 o.Send(&c, 1);
267 return;
268 } else if (c == '0') {
269 padZero = 1;
270 continue;
271 } else if (c == '-') {
272 padLeft = 1;
273 continue;
274 } else if (c == ' ' || c == '+') {
275 sign = c;
276 continue;
277 }
278 break;
279 }
280
281 /* parse field width */
282 if ((c >= '0' && c <= '9')) {
283 nn--;
284 width = static_cast<int>(parse_decimal(format, &nn));
285 c = format[nn++];
286 }
287
288 /* parse precision */
289 if (c == '.') {
290 prec = static_cast<int>(parse_decimal(format, &nn));
291 c = format[nn++];
292 }
293
294 /* length modifier */
295 switch (c) {
296 case 'h':
297 bytelen = sizeof(short);
298 if (format[nn] == 'h') {
299 bytelen = sizeof(char);
300 nn += 1;
301 }
302 c = format[nn++];
303 break;
304 case 'l':
305 bytelen = sizeof(long);
306 if (format[nn] == 'l') {
307 bytelen = sizeof(long long);
308 nn += 1;
309 }
310 c = format[nn++];
311 break;
312 case 'z':
313 bytelen = sizeof(size_t);
314 c = format[nn++];
315 break;
316 case 't':
317 bytelen = sizeof(ptrdiff_t);
318 c = format[nn++];
319 break;
320 default:;
321 }
322
323 /* conversion specifier */
324 const char* str = buffer;
325 if (c == 's') {
326 /* string */
327 str = va_arg(args, const char*);
328 if (str == NULL) {
329 str = "(null)";
330 }
331 } else if (c == 'c') {
332 /* character */
333 /* NOTE: char is promoted to int when passed through the stack */
334 buffer[0] = static_cast<char>(va_arg(args, int));
335 buffer[1] = '\0';
336 } else if (c == 'p') {
337 uint64_t value = reinterpret_cast<uintptr_t>(va_arg(args, void*));
338 buffer[0] = '0';
339 buffer[1] = 'x';
340 format_integer(buffer + 2, sizeof(buffer) - 2, value, 'x');
341 } else if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X') {
342 /* integers - first read value from stack */
343 uint64_t value;
344 int is_signed = (c == 'd' || c == 'i' || c == 'o');
345
346 /* NOTE: int8_t and int16_t are promoted to int when passed
347 * through the stack
348 */
349 switch (bytelen) {
350 case 1:
351 value = static_cast<uint8_t>(va_arg(args, int));
352 break;
353 case 2:
354 value = static_cast<uint16_t>(va_arg(args, int));
355 break;
356 case 4:
357 value = va_arg(args, uint32_t);
358 break;
359 case 8:
360 value = va_arg(args, uint64_t);
361 break;
362 default:
363 return; /* should not happen */
364 }
365
366 /* sign extension, if needed */
367 if (is_signed) {
368 int shift = 64 - 8 * bytelen;
369 value = static_cast<uint64_t>((static_cast<int64_t>(value << shift)) >> shift);
370 }
371
372 /* format the number properly into our buffer */
373 format_integer(buffer, sizeof(buffer), value, c);
374 } else if (c == '%') {
375 buffer[0] = '%';
376 buffer[1] = '\0';
377 } else {
378 __assert(__FILE__, __LINE__, "conversion specifier unsupported");
379 }
380
381 /* if we are here, 'str' points to the content that must be
382 * outputted. handle padding and alignment now */
383
384 slen = strlen(str);
385
386 if (sign != '\0' || prec != -1) {
387 __assert(__FILE__, __LINE__, "sign/precision unsupported");
388 }
389
390 if (slen < width && !padLeft) {
391 char padChar = padZero ? '0' : ' ';
392 SendRepeat(o, padChar, width - slen);
393 }
394
395 o.Send(str, slen);
396
397 if (slen < width && padLeft) {
398 char padChar = padZero ? '0' : ' ';
399 SendRepeat(o, padChar, width - slen);
400 }
401 }
402}
403
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700404int async_safe_format_buffer_va_list(char* buffer, size_t buffer_size, const char* format,
405 va_list args) {
406 BufferOutputStream os(buffer, buffer_size);
407 out_vformat(os, format, args);
408 return os.total;
409}
410
Christopher Ferris92476402017-08-22 11:24:09 -0700411int async_safe_format_buffer(char* buffer, size_t buffer_size, const char* format, ...) {
412 va_list args;
413 va_start(args, format);
414 int buffer_len = async_safe_format_buffer_va_list(buffer, buffer_size, format, args);
415 va_end(args);
416 return buffer_len;
417}
418
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700419int async_safe_format_fd(int fd, const char* format, ...) {
420 FdOutputStream os(fd);
421 va_list args;
422 va_start(args, format);
423 out_vformat(os, format, args);
424 va_end(args);
425 return os.total;
426}
427
428static int write_stderr(const char* tag, const char* msg) {
429 iovec vec[4];
430 vec[0].iov_base = const_cast<char*>(tag);
431 vec[0].iov_len = strlen(tag);
432 vec[1].iov_base = const_cast<char*>(": ");
433 vec[1].iov_len = 2;
434 vec[2].iov_base = const_cast<char*>(msg);
435 vec[2].iov_len = strlen(msg);
436 vec[3].iov_base = const_cast<char*>("\n");
437 vec[3].iov_len = 1;
438
439 int result = TEMP_FAILURE_RETRY(writev(STDERR_FILENO, vec, 4));
440 return result;
441}
442
443static int open_log_socket() {
444 // ToDo: Ideally we want this to fail if the gid of the current
445 // process is AID_LOGD, but will have to wait until we have
446 // registered this in private/android_filesystem_config.h. We have
447 // found that all logd crashes thus far have had no problem stuffing
448 // the UNIX domain socket and moving on so not critical *today*.
449
450 int log_fd = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
451 if (log_fd == -1) {
452 return -1;
453 }
454
455 union {
456 struct sockaddr addr;
457 struct sockaddr_un addrUn;
458 } u;
459 memset(&u, 0, sizeof(u));
460 u.addrUn.sun_family = AF_UNIX;
461 strlcpy(u.addrUn.sun_path, "/dev/socket/logdw", sizeof(u.addrUn.sun_path));
462
463 if (TEMP_FAILURE_RETRY(connect(log_fd, &u.addr, sizeof(u.addrUn))) != 0) {
464 close(log_fd);
465 return -1;
466 }
467
468 return log_fd;
469}
470
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700471struct log_time { // Wire format
472 uint32_t tv_sec;
473 uint32_t tv_nsec;
474};
475
476int async_safe_write_log(int priority, const char* tag, const char* msg) {
477 int main_log_fd = open_log_socket();
478 if (main_log_fd == -1) {
479 // Try stderr instead.
480 return write_stderr(tag, msg);
481 }
482
483 iovec vec[6];
484 char log_id = (priority == ANDROID_LOG_FATAL) ? LOG_ID_CRASH : LOG_ID_MAIN;
485 vec[0].iov_base = &log_id;
486 vec[0].iov_len = sizeof(log_id);
487 uint16_t tid = gettid();
488 vec[1].iov_base = &tid;
489 vec[1].iov_len = sizeof(tid);
490 timespec ts;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -0700491 clock_gettime(CLOCK_REALTIME, &ts);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700492 log_time realtime_ts;
493 realtime_ts.tv_sec = ts.tv_sec;
494 realtime_ts.tv_nsec = ts.tv_nsec;
495 vec[2].iov_base = &realtime_ts;
496 vec[2].iov_len = sizeof(realtime_ts);
497
498 vec[3].iov_base = &priority;
499 vec[3].iov_len = 1;
500 vec[4].iov_base = const_cast<char*>(tag);
501 vec[4].iov_len = strlen(tag) + 1;
502 vec[5].iov_base = const_cast<char*>(msg);
503 vec[5].iov_len = strlen(msg) + 1;
504
505 int result = TEMP_FAILURE_RETRY(writev(main_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
506 close(main_log_fd);
507 return result;
508}
509
510int async_safe_format_log_va_list(int priority, const char* tag, const char* format, va_list args) {
511 char buffer[1024];
512 BufferOutputStream os(buffer, sizeof(buffer));
513 out_vformat(os, format, args);
514 return async_safe_write_log(priority, tag, buffer);
515}
516
517int async_safe_format_log(int priority, const char* tag, const char* format, ...) {
518 va_list args;
519 va_start(args, format);
520 int result = async_safe_format_log_va_list(priority, tag, format, args);
521 va_end(args);
522 return result;
523}
524
525void async_safe_fatal_va_list(const char* prefix, const char* format, va_list args) {
526 char msg[1024];
527 BufferOutputStream os(msg, sizeof(msg));
528
529 if (prefix) {
530 os.Send(prefix, strlen(prefix));
531 os.Send(": ", 2);
532 }
533
534 out_vformat(os, format, args);
535
536 // Log to stderr for the benefit of "adb shell" users and gtests.
537 struct iovec iov[2] = {
538 {msg, os.total}, {const_cast<char*>("\n"), 1},
539 };
540 TEMP_FAILURE_RETRY(writev(2, iov, 2));
541
542 // Log to the log for the benefit of regular app developers (whose stdout and stderr are closed).
543 async_safe_write_log(ANDROID_LOG_FATAL, "libc", msg);
544
545 android_set_abort_message(msg);
546}
547
Elliott Hughes695713e2017-06-20 17:28:42 -0700548void async_safe_fatal_no_abort(const char* fmt, ...) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700549 va_list args;
550 va_start(args, fmt);
551 async_safe_fatal_va_list(nullptr, fmt, args);
552 va_end(args);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700553}