1 /*
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 */
29 #include "../private/libc_logging.h" // Relative path so we can #include this .cpp file for testing.
30 #include "../private/ScopedPthreadMutexLocker.h"
32 #include <android/set_abort_message.h>
33 #include <assert.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <pthread.h>
37 #include <stdarg.h>
38 #include <stddef.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/mman.h>
42 #include <sys/socket.h>
43 #include <sys/types.h>
44 #include <sys/uio.h>
45 #include <sys/un.h>
46 #include <time.h>
47 #include <unistd.h>
49 static pthread_mutex_t g_abort_msg_lock = PTHREAD_MUTEX_INITIALIZER;
51 __LIBC_HIDDEN__ abort_msg_t** __abort_message_ptr; // Accessible to __libc_init_common.
53 // Must be kept in sync with frameworks/base/core/java/android/util/EventLog.java.
54 enum AndroidEventLogType {
55 EVENT_TYPE_INT = 0,
56 EVENT_TYPE_LONG = 1,
57 EVENT_TYPE_STRING = 2,
58 EVENT_TYPE_LIST = 3,
59 };
61 struct BufferOutputStream {
62 public:
63 BufferOutputStream(char* buffer, size_t size) : total(0) {
64 buffer_ = buffer;
65 end_ = buffer + size - 1;
66 pos_ = buffer_;
67 pos_[0] = '\0';
68 }
70 ~BufferOutputStream() {
71 }
73 void Send(const char* data, int len) {
74 if (len < 0) {
75 len = strlen(data);
76 }
78 total += len;
80 while (len > 0) {
81 int avail = end_ - pos_;
82 if (avail == 0) {
83 return;
84 }
85 if (avail > len) {
86 avail = len;
87 }
88 memcpy(pos_, data, avail);
89 pos_ += avail;
90 pos_[0] = '\0';
91 len -= avail;
92 }
93 }
95 size_t total;
97 private:
98 char* buffer_;
99 char* pos_;
100 char* end_;
101 };
103 struct FdOutputStream {
104 public:
105 FdOutputStream(int fd) : total(0), fd_(fd) {
106 }
108 void Send(const char* data, int len) {
109 if (len < 0) {
110 len = strlen(data);
111 }
113 total += len;
115 while (len > 0) {
116 int rc = TEMP_FAILURE_RETRY(write(fd_, data, len));
117 if (rc == -1) {
118 return;
119 }
120 data += rc;
121 len -= rc;
122 }
123 }
125 size_t total;
127 private:
128 int fd_;
129 };
131 /*** formatted output implementation
132 ***/
134 /* Parse a decimal string from 'format + *ppos',
135 * return the value, and writes the new position past
136 * the decimal string in '*ppos' on exit.
137 *
138 * NOTE: Does *not* handle a sign prefix.
139 */
140 static unsigned parse_decimal(const char *format, int *ppos) {
141 const char* p = format + *ppos;
142 unsigned result = 0;
144 for (;;) {
145 int ch = *p;
146 unsigned d = static_cast<unsigned>(ch - '0');
148 if (d >= 10U) {
149 break;
150 }
152 result = result*10 + d;
153 p++;
154 }
155 *ppos = p - format;
156 return result;
157 }
159 // Writes number 'value' in base 'base' into buffer 'buf' of size 'buf_size' bytes.
160 // Assumes that buf_size > 0.
161 static void format_unsigned(char* buf, size_t buf_size, uint64_t value, int base, bool caps) {
162 char* p = buf;
163 char* end = buf + buf_size - 1;
165 // Generate digit string in reverse order.
166 while (value) {
167 unsigned d = value % base;
168 value /= base;
169 if (p != end) {
170 char ch;
171 if (d < 10) {
172 ch = '0' + d;
173 } else {
174 ch = (caps ? 'A' : 'a') + (d - 10);
175 }
176 *p++ = ch;
177 }
178 }
180 // Special case for 0.
181 if (p == buf) {
182 if (p != end) {
183 *p++ = '0';
184 }
185 }
186 *p = '\0';
188 // Reverse digit string in-place.
189 size_t length = p - buf;
190 for (size_t i = 0, j = length - 1; i < j; ++i, --j) {
191 char ch = buf[i];
192 buf[i] = buf[j];
193 buf[j] = ch;
194 }
195 }
197 static void format_integer(char* buf, size_t buf_size, uint64_t value, char conversion) {
198 // Decode the conversion specifier.
199 int is_signed = (conversion == 'd' || conversion == 'i' || conversion == 'o');
200 int base = 10;
201 if (conversion == 'x' || conversion == 'X') {
202 base = 16;
203 } else if (conversion == 'o') {
204 base = 8;
205 }
206 bool caps = (conversion == 'X');
208 if (is_signed && static_cast<int64_t>(value) < 0) {
209 buf[0] = '-';
210 buf += 1;
211 buf_size -= 1;
212 value = static_cast<uint64_t>(-static_cast<int64_t>(value));
213 }
214 format_unsigned(buf, buf_size, value, base, caps);
215 }
217 template <typename Out>
218 static void SendRepeat(Out& o, char ch, int count) {
219 char pad[8];
220 memset(pad, ch, sizeof(pad));
222 const int pad_size = static_cast<int>(sizeof(pad));
223 while (count > 0) {
224 int avail = count;
225 if (avail > pad_size) {
226 avail = pad_size;
227 }
228 o.Send(pad, avail);
229 count -= avail;
230 }
231 }
233 /* Perform formatted output to an output target 'o' */
234 template <typename Out>
235 static void out_vformat(Out& o, const char* format, va_list args) {
236 int nn = 0;
238 for (;;) {
239 int mm;
240 int padZero = 0;
241 int padLeft = 0;
242 char sign = '\0';
243 int width = -1;
244 int prec = -1;
245 size_t bytelen = sizeof(int);
246 int slen;
247 char buffer[32]; /* temporary buffer used to format numbers */
249 char c;
251 /* first, find all characters that are not 0 or '%' */
252 /* then send them to the output directly */
253 mm = nn;
254 do {
255 c = format[mm];
256 if (c == '\0' || c == '%')
257 break;
258 mm++;
259 } while (1);
261 if (mm > nn) {
262 o.Send(format+nn, mm-nn);
263 nn = mm;
264 }
266 /* is this it ? then exit */
267 if (c == '\0')
268 break;
270 /* nope, we are at a '%' modifier */
271 nn++; // skip it
273 /* parse flags */
274 for (;;) {
275 c = format[nn++];
276 if (c == '\0') { /* single trailing '%' ? */
277 c = '%';
278 o.Send(&c, 1);
279 return;
280 }
281 else if (c == '0') {
282 padZero = 1;
283 continue;
284 }
285 else if (c == '-') {
286 padLeft = 1;
287 continue;
288 }
289 else if (c == ' ' || c == '+') {
290 sign = c;
291 continue;
292 }
293 break;
294 }
296 /* parse field width */
297 if ((c >= '0' && c <= '9')) {
298 nn --;
299 width = static_cast<int>(parse_decimal(format, &nn));
300 c = format[nn++];
301 }
303 /* parse precision */
304 if (c == '.') {
305 prec = static_cast<int>(parse_decimal(format, &nn));
306 c = format[nn++];
307 }
309 /* length modifier */
310 switch (c) {
311 case 'h':
312 bytelen = sizeof(short);
313 if (format[nn] == 'h') {
314 bytelen = sizeof(char);
315 nn += 1;
316 }
317 c = format[nn++];
318 break;
319 case 'l':
320 bytelen = sizeof(long);
321 if (format[nn] == 'l') {
322 bytelen = sizeof(long long);
323 nn += 1;
324 }
325 c = format[nn++];
326 break;
327 case 'z':
328 bytelen = sizeof(size_t);
329 c = format[nn++];
330 break;
331 case 't':
332 bytelen = sizeof(ptrdiff_t);
333 c = format[nn++];
334 break;
335 default:
336 ;
337 }
339 /* conversion specifier */
340 const char* str = buffer;
341 if (c == 's') {
342 /* string */
343 str = va_arg(args, const char*);
344 if (str == NULL) {
345 str = "(null)";
346 }
347 } else if (c == 'c') {
348 /* character */
349 /* NOTE: char is promoted to int when passed through the stack */
350 buffer[0] = static_cast<char>(va_arg(args, int));
351 buffer[1] = '\0';
352 } else if (c == 'p') {
353 uint64_t value = reinterpret_cast<uintptr_t>(va_arg(args, void*));
354 buffer[0] = '0';
355 buffer[1] = 'x';
356 format_integer(buffer + 2, sizeof(buffer) - 2, value, 'x');
357 } else if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X') {
358 /* integers - first read value from stack */
359 uint64_t value;
360 int is_signed = (c == 'd' || c == 'i' || c == 'o');
362 /* NOTE: int8_t and int16_t are promoted to int when passed
363 * through the stack
364 */
365 switch (bytelen) {
366 case 1: value = static_cast<uint8_t>(va_arg(args, int)); break;
367 case 2: value = static_cast<uint16_t>(va_arg(args, int)); break;
368 case 4: value = va_arg(args, uint32_t); break;
369 case 8: value = va_arg(args, uint64_t); break;
370 default: return; /* should not happen */
371 }
373 /* sign extension, if needed */
374 if (is_signed) {
375 int shift = 64 - 8*bytelen;
376 value = static_cast<uint64_t>((static_cast<int64_t>(value << shift)) >> shift);
377 }
379 /* format the number properly into our buffer */
380 format_integer(buffer, sizeof(buffer), value, c);
381 } else if (c == '%') {
382 buffer[0] = '%';
383 buffer[1] = '\0';
384 } else {
385 __assert(__FILE__, __LINE__, "conversion specifier unsupported");
386 }
388 /* if we are here, 'str' points to the content that must be
389 * outputted. handle padding and alignment now */
391 slen = strlen(str);
393 if (sign != '\0' || prec != -1) {
394 __assert(__FILE__, __LINE__, "sign/precision unsupported");
395 }
397 if (slen < width && !padLeft) {
398 char padChar = padZero ? '0' : ' ';
399 SendRepeat(o, padChar, width - slen);
400 }
402 o.Send(str, slen);
404 if (slen < width && padLeft) {
405 char padChar = padZero ? '0' : ' ';
406 SendRepeat(o, padChar, width - slen);
407 }
408 }
409 }
411 int __libc_format_buffer(char* buffer, size_t buffer_size, const char* format, ...) {
412 BufferOutputStream os(buffer, buffer_size);
413 va_list args;
414 va_start(args, format);
415 out_vformat(os, format, args);
416 va_end(args);
417 return os.total;
418 }
420 int __libc_format_fd(int fd, const char* format, ...) {
421 FdOutputStream os(fd);
422 va_list args;
423 va_start(args, format);
424 out_vformat(os, format, args);
425 va_end(args);
426 return os.total;
427 }
429 static int __libc_write_stderr(const char* tag, const char* msg) {
430 int fd = TEMP_FAILURE_RETRY(open("/dev/stderr", O_CLOEXEC | O_WRONLY));
431 if (fd == -1) {
432 return -1;
433 }
435 iovec vec[4];
436 vec[0].iov_base = const_cast<char*>(tag);
437 vec[0].iov_len = strlen(tag);
438 vec[1].iov_base = const_cast<char*>(": ");
439 vec[1].iov_len = 2;
440 vec[2].iov_base = const_cast<char*>(msg);
441 vec[2].iov_len = strlen(msg) + 1;
442 vec[3].iov_base = const_cast<char*>("\n");
443 vec[3].iov_len = 1;
445 int result = TEMP_FAILURE_RETRY(writev(fd, vec, 4));
446 close(fd);
447 return result;
448 }
450 #ifdef TARGET_USES_LOGD
451 static int __libc_open_log_socket()
452 {
453 // ToDo: Ideally we want this to fail if the gid of the current
454 // process is AID_LOGD, but will have to wait until we have
455 // registered this in private/android_filesystem_config.h. We have
456 // found that all logd crashes thus far have had no problem stuffing
457 // the UNIX domain socket and moving on so not critical *today*.
459 int log_fd = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0));
460 if (log_fd < 0) {
461 return -1;
462 }
464 if (fcntl(log_fd, F_SETFL, O_NONBLOCK) == -1) {
465 close(log_fd);
466 return -1;
467 }
469 union {
470 struct sockaddr addr;
471 struct sockaddr_un addrUn;
472 } u;
473 memset(&u, 0, sizeof(u));
474 u.addrUn.sun_family = AF_UNIX;
475 strlcpy(u.addrUn.sun_path, "/dev/socket/logdw", sizeof(u.addrUn.sun_path));
477 if (TEMP_FAILURE_RETRY(connect(log_fd, &u.addr, sizeof(u.addrUn))) != 0) {
478 close(log_fd);
479 return -1;
480 }
482 return log_fd;
483 }
485 struct log_time { // Wire format
486 uint32_t tv_sec;
487 uint32_t tv_nsec;
488 };
489 #endif
491 static int __libc_write_log(int priority, const char* tag, const char* msg) {
492 #ifdef TARGET_USES_LOGD
493 int main_log_fd = __libc_open_log_socket();
495 if (main_log_fd == -1) {
496 // Try stderr instead.
497 return __libc_write_stderr(tag, msg);
498 }
500 iovec vec[6];
501 char log_id = (priority == ANDROID_LOG_FATAL) ? LOG_ID_CRASH : LOG_ID_MAIN;
502 vec[0].iov_base = &log_id;
503 vec[0].iov_len = sizeof(log_id);
504 uint16_t tid = gettid();
505 vec[1].iov_base = &tid;
506 vec[1].iov_len = sizeof(tid);
507 timespec ts;
508 clock_gettime(CLOCK_REALTIME, &ts);
509 log_time realtime_ts;
510 realtime_ts.tv_sec = ts.tv_sec;
511 realtime_ts.tv_nsec = ts.tv_nsec;
512 vec[2].iov_base = &realtime_ts;
513 vec[2].iov_len = sizeof(realtime_ts);
515 vec[3].iov_base = &priority;
516 vec[3].iov_len = 1;
517 vec[4].iov_base = const_cast<char*>(tag);
518 vec[4].iov_len = strlen(tag) + 1;
519 vec[5].iov_base = const_cast<char*>(msg);
520 vec[5].iov_len = strlen(msg) + 1;
521 #else
522 int main_log_fd = TEMP_FAILURE_RETRY(open("/dev/log/main", O_CLOEXEC | O_WRONLY));
523 if (main_log_fd == -1) {
524 if (errno == ENOTDIR) {
525 // /dev/log isn't a directory? Maybe we're running on the host? Try stderr instead.
526 return __libc_write_stderr(tag, msg);
527 }
528 return -1;
529 }
531 iovec vec[3];
532 vec[0].iov_base = &priority;
533 vec[0].iov_len = 1;
534 vec[1].iov_base = const_cast<char*>(tag);
535 vec[1].iov_len = strlen(tag) + 1;
536 vec[2].iov_base = const_cast<char*>(msg);
537 vec[2].iov_len = strlen(msg) + 1;
538 #endif
540 int result = TEMP_FAILURE_RETRY(writev(main_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
541 close(main_log_fd);
542 return result;
543 }
545 int __libc_format_log_va_list(int priority, const char* tag, const char* format, va_list args) {
546 char buffer[1024];
547 BufferOutputStream os(buffer, sizeof(buffer));
548 out_vformat(os, format, args);
549 return __libc_write_log(priority, tag, buffer);
550 }
552 int __libc_format_log(int priority, const char* tag, const char* format, ...) {
553 va_list args;
554 va_start(args, format);
555 int result = __libc_format_log_va_list(priority, tag, format, args);
556 va_end(args);
557 return result;
558 }
560 static int __libc_android_log_event(int32_t tag, char type, const void* payload, size_t len) {
561 #ifdef TARGET_USES_LOGD
562 iovec vec[6];
563 char log_id = LOG_ID_EVENTS;
564 vec[0].iov_base = &log_id;
565 vec[0].iov_len = sizeof(log_id);
566 uint16_t tid = gettid();
567 vec[1].iov_base = &tid;
568 vec[1].iov_len = sizeof(tid);
569 timespec ts;
570 clock_gettime(CLOCK_REALTIME, &ts);
571 log_time realtime_ts;
572 realtime_ts.tv_sec = ts.tv_sec;
573 realtime_ts.tv_nsec = ts.tv_nsec;
574 vec[2].iov_base = &realtime_ts;
575 vec[2].iov_len = sizeof(realtime_ts);
577 vec[3].iov_base = &tag;
578 vec[3].iov_len = sizeof(tag);
579 vec[4].iov_base = &type;
580 vec[4].iov_len = sizeof(type);
581 vec[5].iov_base = const_cast<void*>(payload);
582 vec[5].iov_len = len;
584 int event_log_fd = __libc_open_log_socket();
585 #else
586 iovec vec[3];
587 vec[0].iov_base = &tag;
588 vec[0].iov_len = sizeof(tag);
589 vec[1].iov_base = &type;
590 vec[1].iov_len = sizeof(type);
591 vec[2].iov_base = const_cast<void*>(payload);
592 vec[2].iov_len = len;
594 int event_log_fd = TEMP_FAILURE_RETRY(open("/dev/log/events", O_CLOEXEC | O_WRONLY));
595 #endif
597 if (event_log_fd == -1) {
598 return -1;
599 }
600 int result = TEMP_FAILURE_RETRY(writev(event_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
601 close(event_log_fd);
602 return result;
603 }
605 void __libc_android_log_event_int(int32_t tag, int value) {
606 __libc_android_log_event(tag, EVENT_TYPE_INT, &value, sizeof(value));
607 }
609 void __libc_android_log_event_uid(int32_t tag) {
610 __libc_android_log_event_int(tag, getuid());
611 }
613 void __fortify_chk_fail(const char* msg, uint32_t tag) {
614 if (tag != 0) {
615 __libc_android_log_event_uid(tag);
616 }
617 __libc_fatal("FORTIFY_SOURCE: %s. Calling abort().", msg);
618 }
620 static void __libc_fatal(const char* format, va_list args) {
621 char msg[1024];
622 BufferOutputStream os(msg, sizeof(msg));
623 out_vformat(os, format, args);
625 // log to stderr for the benefit of "adb shell" users.
626 struct iovec iov[2] = {
627 {msg, strlen(msg)},
628 {const_cast<void*>(static_cast<const void*>("\n")), 1},
629 };
630 writev(2, iov, 2);
632 // Log to the log for the benefit of regular app developers (whose stdout and stderr are closed).
633 __libc_write_log(ANDROID_LOG_FATAL, "libc", msg);
635 android_set_abort_message(msg);
636 }
638 void __libc_fatal_no_abort(const char* format, ...) {
639 va_list args;
640 va_start(args, format);
641 __libc_fatal(format, args);
642 va_end(args);
643 }
645 void __libc_fatal(const char* format, ...) {
646 va_list args;
647 va_start(args, format);
648 __libc_fatal(format, args);
649 va_end(args);
650 abort();
651 }
653 void android_set_abort_message(const char* msg) {
654 ScopedPthreadMutexLocker locker(&g_abort_msg_lock);
656 if (__abort_message_ptr == NULL) {
657 // We must have crashed _very_ early.
658 return;
659 }
661 if (*__abort_message_ptr != NULL) {
662 // We already have an abort message.
663 // Assume that the first crash is the one most worth reporting.
664 return;
665 }
667 size_t size = sizeof(abort_msg_t) + strlen(msg) + 1;
668 void* map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
669 if (map == MAP_FAILED) {
670 return;
671 }
673 // TODO: if we stick to the current "one-shot" scheme, we can remove this code and
674 // stop storing the size.
675 if (*__abort_message_ptr != NULL) {
676 munmap(*__abort_message_ptr, (*__abort_message_ptr)->size);
677 }
678 abort_msg_t* new_abort_message = reinterpret_cast<abort_msg_t*>(map);
679 new_abort_message->size = size;
680 strcpy(new_abort_message->msg, msg);
681 *__abort_message_ptr = new_abort_message;
682 }