2 * Copyright (C) 2010 The Android Open Source Project
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
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
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>
43 #include <sys/socket.h>
44 #include <sys/types.h>
50 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
51 #include <sys/_system_properties.h>
53 static pthread_mutex_t g_abort_msg_lock = PTHREAD_MUTEX_INITIALIZER;
55 __LIBC_HIDDEN__ abort_msg_t** __abort_message_ptr; // Accessible to __libc_init_common.
57 // Must be kept in sync with frameworks/base/core/java/android/util/EventLog.java.
58 enum AndroidEventLogType {
61 EVENT_TYPE_STRING = 2,
66 struct BufferOutputStream {
68 BufferOutputStream(char* buffer, size_t size) : total(0) {
70 end_ = buffer + size - 1;
75 ~BufferOutputStream() {
78 void Send(const char* data, int len) {
86 int avail = end_ - pos_;
93 memcpy(pos_, data, avail);
108 struct FdOutputStream {
110 explicit FdOutputStream(int fd) : total(0), fd_(fd) {
113 void Send(const char* data, int len) {
121 int rc = TEMP_FAILURE_RETRY(write(fd_, data, len));
136 /*** formatted output implementation
139 /* Parse a decimal string from 'format + *ppos',
140 * return the value, and writes the new position past
141 * the decimal string in '*ppos' on exit.
143 * NOTE: Does *not* handle a sign prefix.
145 static unsigned parse_decimal(const char *format, int *ppos) {
146 const char* p = format + *ppos;
151 unsigned d = static_cast<unsigned>(ch - '0');
157 result = result*10 + d;
164 // Writes number 'value' in base 'base' into buffer 'buf' of size 'buf_size' bytes.
165 // Assumes that buf_size > 0.
166 static void format_unsigned(char* buf, size_t buf_size, uint64_t value, int base, bool caps) {
168 char* end = buf + buf_size - 1;
170 // Generate digit string in reverse order.
172 unsigned d = value % base;
179 ch = (caps ? 'A' : 'a') + (d - 10);
185 // Special case for 0.
193 // Reverse digit string in-place.
194 size_t length = p - buf;
195 for (size_t i = 0, j = length - 1; i < j; ++i, --j) {
202 static void format_integer(char* buf, size_t buf_size, uint64_t value, char conversion) {
203 // Decode the conversion specifier.
204 int is_signed = (conversion == 'd' || conversion == 'i' || conversion == 'o');
206 if (conversion == 'x' || conversion == 'X') {
208 } else if (conversion == 'o') {
211 bool caps = (conversion == 'X');
213 if (is_signed && static_cast<int64_t>(value) < 0) {
217 value = static_cast<uint64_t>(-static_cast<int64_t>(value));
219 format_unsigned(buf, buf_size, value, base, caps);
222 template <typename Out>
223 static void SendRepeat(Out& o, char ch, int count) {
225 memset(pad, ch, sizeof(pad));
227 const int pad_size = static_cast<int>(sizeof(pad));
230 if (avail > pad_size) {
238 /* Perform formatted output to an output target 'o' */
239 template <typename Out>
240 static void out_vformat(Out& o, const char* format, va_list args) {
250 size_t bytelen = sizeof(int);
252 char buffer[32]; /* temporary buffer used to format numbers */
256 /* first, find all characters that are not 0 or '%' */
257 /* then send them to the output directly */
261 if (c == '\0' || c == '%')
267 o.Send(format+nn, mm-nn);
271 /* is this it ? then exit */
275 /* nope, we are at a '%' modifier */
281 if (c == '\0') { /* single trailing '%' ? */
294 else if (c == ' ' || c == '+') {
301 /* parse field width */
302 if ((c >= '0' && c <= '9')) {
304 width = static_cast<int>(parse_decimal(format, &nn));
308 /* parse precision */
310 prec = static_cast<int>(parse_decimal(format, &nn));
314 /* length modifier */
317 bytelen = sizeof(short);
318 if (format[nn] == 'h') {
319 bytelen = sizeof(char);
325 bytelen = sizeof(long);
326 if (format[nn] == 'l') {
327 bytelen = sizeof(long long);
333 bytelen = sizeof(size_t);
337 bytelen = sizeof(ptrdiff_t);
344 /* conversion specifier */
345 const char* str = buffer;
348 str = va_arg(args, const char*);
352 } else if (c == 'c') {
354 /* NOTE: char is promoted to int when passed through the stack */
355 buffer[0] = static_cast<char>(va_arg(args, int));
357 } else if (c == 'p') {
358 uint64_t value = reinterpret_cast<uintptr_t>(va_arg(args, void*));
361 format_integer(buffer + 2, sizeof(buffer) - 2, value, 'x');
362 } else if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X') {
363 /* integers - first read value from stack */
365 int is_signed = (c == 'd' || c == 'i' || c == 'o');
367 /* NOTE: int8_t and int16_t are promoted to int when passed
371 case 1: value = static_cast<uint8_t>(va_arg(args, int)); break;
372 case 2: value = static_cast<uint16_t>(va_arg(args, int)); break;
373 case 4: value = va_arg(args, uint32_t); break;
374 case 8: value = va_arg(args, uint64_t); break;
375 default: return; /* should not happen */
378 /* sign extension, if needed */
380 int shift = 64 - 8*bytelen;
381 value = static_cast<uint64_t>((static_cast<int64_t>(value << shift)) >> shift);
384 /* format the number properly into our buffer */
385 format_integer(buffer, sizeof(buffer), value, c);
386 } else if (c == '%') {
390 __assert(__FILE__, __LINE__, "conversion specifier unsupported");
393 /* if we are here, 'str' points to the content that must be
394 * outputted. handle padding and alignment now */
398 if (sign != '\0' || prec != -1) {
399 __assert(__FILE__, __LINE__, "sign/precision unsupported");
402 if (slen < width && !padLeft) {
403 char padChar = padZero ? '0' : ' ';
404 SendRepeat(o, padChar, width - slen);
409 if (slen < width && padLeft) {
410 char padChar = padZero ? '0' : ' ';
411 SendRepeat(o, padChar, width - slen);
416 int __libc_format_buffer(char* buffer, size_t buffer_size, const char* format, ...) {
417 BufferOutputStream os(buffer, buffer_size);
419 va_start(args, format);
420 out_vformat(os, format, args);
425 int __libc_format_buffer_va_list(char* buffer, size_t buffer_size, const char* format,
427 BufferOutputStream os(buffer, buffer_size);
428 out_vformat(os, format, args);
432 int __libc_format_fd(int fd, const char* format, ...) {
433 FdOutputStream os(fd);
435 va_start(args, format);
436 out_vformat(os, format, args);
441 static int __libc_write_stderr(const char* tag, const char* msg) {
443 vec[0].iov_base = const_cast<char*>(tag);
444 vec[0].iov_len = strlen(tag);
445 vec[1].iov_base = const_cast<char*>(": ");
447 vec[2].iov_base = const_cast<char*>(msg);
448 vec[2].iov_len = strlen(msg);
449 vec[3].iov_base = const_cast<char*>("\n");
452 int result = TEMP_FAILURE_RETRY(writev(STDERR_FILENO, vec, 4));
456 static int __libc_open_log_socket() {
457 // ToDo: Ideally we want this to fail if the gid of the current
458 // process is AID_LOGD, but will have to wait until we have
459 // registered this in private/android_filesystem_config.h. We have
460 // found that all logd crashes thus far have had no problem stuffing
461 // the UNIX domain socket and moving on so not critical *today*.
463 int log_fd = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
469 struct sockaddr addr;
470 struct sockaddr_un addrUn;
472 memset(&u, 0, sizeof(u));
473 u.addrUn.sun_family = AF_UNIX;
474 strlcpy(u.addrUn.sun_path, "/dev/socket/logdw", sizeof(u.addrUn.sun_path));
476 if (TEMP_FAILURE_RETRY(connect(log_fd, &u.addr, sizeof(u.addrUn))) != 0) {
485 const prop_info* pinfo;
490 static void refresh_cache(struct cache *cache, const char *key)
493 cache->pinfo = __system_property_find(key);
498 uint32_t serial = __system_property_serial(cache->pinfo);
499 if (serial == cache->serial) {
502 cache->serial = serial;
504 char buf[PROP_VALUE_MAX];
505 __system_property_read(cache->pinfo, 0, buf);
509 // Timestamp state generally remains constant, since a change is
510 // rare, we can accept a trylock failure gracefully.
511 static pthread_mutex_t lock_clockid = PTHREAD_MUTEX_INITIALIZER;
513 static clockid_t __android_log_clockid()
515 static struct cache r_time_cache = { NULL, static_cast<uint32_t>(-1), 0 };
516 static struct cache p_time_cache = { NULL, static_cast<uint32_t>(-1), 0 };
519 if (pthread_mutex_trylock(&lock_clockid)) {
520 // We are willing to accept some race in this context
521 if (!(c = p_time_cache.c)) {
525 static uint32_t serial;
526 uint32_t current_serial = __system_property_area_serial();
527 if (current_serial != serial) {
528 refresh_cache(&r_time_cache, "ro.logd.timestamp");
529 refresh_cache(&p_time_cache, "persist.logd.timestamp");
530 serial = current_serial;
532 if (!(c = p_time_cache.c)) {
536 pthread_mutex_unlock(&lock_clockid);
539 return (tolower(c) == 'm') ? CLOCK_MONOTONIC : CLOCK_REALTIME;
542 struct log_time { // Wire format
547 int __libc_write_log(int priority, const char* tag, const char* msg) {
548 int main_log_fd = __libc_open_log_socket();
549 if (main_log_fd == -1) {
550 // Try stderr instead.
551 return __libc_write_stderr(tag, msg);
555 char log_id = (priority == ANDROID_LOG_FATAL) ? LOG_ID_CRASH : LOG_ID_MAIN;
556 vec[0].iov_base = &log_id;
557 vec[0].iov_len = sizeof(log_id);
558 uint16_t tid = gettid();
559 vec[1].iov_base = &tid;
560 vec[1].iov_len = sizeof(tid);
562 clock_gettime(__android_log_clockid(), &ts);
563 log_time realtime_ts;
564 realtime_ts.tv_sec = ts.tv_sec;
565 realtime_ts.tv_nsec = ts.tv_nsec;
566 vec[2].iov_base = &realtime_ts;
567 vec[2].iov_len = sizeof(realtime_ts);
569 vec[3].iov_base = &priority;
571 vec[4].iov_base = const_cast<char*>(tag);
572 vec[4].iov_len = strlen(tag) + 1;
573 vec[5].iov_base = const_cast<char*>(msg);
574 vec[5].iov_len = strlen(msg) + 1;
576 int result = TEMP_FAILURE_RETRY(writev(main_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
581 int __libc_format_log_va_list(int priority, const char* tag, const char* format, va_list args) {
583 BufferOutputStream os(buffer, sizeof(buffer));
584 out_vformat(os, format, args);
585 return __libc_write_log(priority, tag, buffer);
588 int __libc_format_log(int priority, const char* tag, const char* format, ...) {
590 va_start(args, format);
591 int result = __libc_format_log_va_list(priority, tag, format, args);
596 static void __libc_fatal_va_list(const char* prefix, const char* format, va_list args) {
598 BufferOutputStream os(msg, sizeof(msg));
601 os.Send(prefix, strlen(prefix));
605 out_vformat(os, format, args);
607 // Log to stderr for the benefit of "adb shell" users and gtests.
608 struct iovec iov[2] = {
610 { const_cast<char*>("\n"), 1 },
612 TEMP_FAILURE_RETRY(writev(2, iov, 2));
614 // Log to the log for the benefit of regular app developers (whose stdout and stderr are closed).
615 __libc_write_log(ANDROID_LOG_FATAL, "libc", msg);
617 android_set_abort_message(msg);
620 void __libc_fatal(const char* fmt, ...) {
623 __libc_fatal_va_list(nullptr, fmt, args);
628 void __fortify_fatal(const char* fmt, ...) {
631 __libc_fatal_va_list("FORTIFY", fmt, args);
636 void android_set_abort_message(const char* msg) {
637 ScopedPthreadMutexLocker locker(&g_abort_msg_lock);
639 if (__abort_message_ptr == NULL) {
640 // We must have crashed _very_ early.
644 if (*__abort_message_ptr != NULL) {
645 // We already have an abort message.
646 // Assume that the first crash is the one most worth reporting.
650 size_t size = sizeof(abort_msg_t) + strlen(msg) + 1;
651 void* map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
652 if (map == MAP_FAILED) {
656 // TODO: if we stick to the current "one-shot" scheme, we can remove this code and
657 // stop storing the size.
658 if (*__abort_message_ptr != NULL) {
659 munmap(*__abort_message_ptr, (*__abort_message_ptr)->size);
661 abort_msg_t* new_abort_message = reinterpret_cast<abort_msg_t*>(map);
662 new_abort_message->size = size;
663 strcpy(new_abort_message->msg, msg);
664 *__abort_message_ptr = new_abort_message;