Home | History | Annotate | Download | only in async_safe
      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  */
     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/syscall.h>
     41 #include <sys/types.h>
     42 #include <sys/uio.h>
     43 #include <sys/un.h>
     44 #include <time.h>
     45 #include <unistd.h>
     46 
     47 #include <android/set_abort_message.h>
     48 #include <async_safe/log.h>
     49 
     50 #include "private/CachedProperty.h"
     51 #include "private/ErrnoRestorer.h"
     52 #include "private/ScopedPthreadMutexLocker.h"
     53 
     54 // Don't call libc's close, since it might call back into us as a result of fdsan.
     55 #pragma GCC poison close
     56 static int __close(int fd) {
     57   return syscall(__NR_close, fd);
     58 }
     59 
     60 // Must be kept in sync with frameworks/base/core/java/android/util/EventLog.java.
     61 enum AndroidEventLogType {
     62   EVENT_TYPE_INT = 0,
     63   EVENT_TYPE_LONG = 1,
     64   EVENT_TYPE_STRING = 2,
     65   EVENT_TYPE_LIST = 3,
     66   EVENT_TYPE_FLOAT = 4,
     67 };
     68 
     69 struct BufferOutputStream {
     70  public:
     71   BufferOutputStream(char* buffer, size_t size) : total(0), pos_(buffer), avail_(size) {
     72     if (avail_ > 0) pos_[0] = '\0';
     73   }
     74   ~BufferOutputStream() = default;
     75 
     76   void Send(const char* data, int len) {
     77     if (len < 0) {
     78       len = strlen(data);
     79     }
     80     total += len;
     81 
     82     if (avail_ <= 1) {
     83       // No space to put anything else.
     84       return;
     85     }
     86 
     87     if (static_cast<size_t>(len) >= avail_) {
     88       len = avail_ - 1;
     89     }
     90     memcpy(pos_, data, len);
     91     pos_ += len;
     92     pos_[0] = '\0';
     93     avail_ -= len;
     94   }
     95 
     96   size_t total;
     97 
     98  private:
     99   char* pos_;
    100   size_t avail_;
    101 };
    102 
    103 struct FdOutputStream {
    104  public:
    105   explicit FdOutputStream(int fd) : total(0), fd_(fd) {}
    106 
    107   void Send(const char* data, int len) {
    108     if (len < 0) {
    109       len = strlen(data);
    110     }
    111     total += len;
    112 
    113     while (len > 0) {
    114       ssize_t bytes = TEMP_FAILURE_RETRY(write(fd_, data, len));
    115       if (bytes == -1) {
    116         return;
    117       }
    118       data += bytes;
    119       len -= bytes;
    120     }
    121   }
    122 
    123   size_t total;
    124 
    125  private:
    126   int fd_;
    127 };
    128 
    129 /*** formatted output implementation
    130  ***/
    131 
    132 /* Parse a decimal string from 'format + *ppos',
    133  * return the value, and writes the new position past
    134  * the decimal string in '*ppos' on exit.
    135  *
    136  * NOTE: Does *not* handle a sign prefix.
    137  */
    138 static unsigned parse_decimal(const char* format, int* ppos) {
    139   const char* p = format + *ppos;
    140   unsigned result = 0;
    141 
    142   for (;;) {
    143     int ch = *p;
    144     unsigned d = static_cast<unsigned>(ch - '0');
    145 
    146     if (d >= 10U) {
    147       break;
    148     }
    149 
    150     result = result * 10 + d;
    151     p++;
    152   }
    153   *ppos = p - format;
    154   return result;
    155 }
    156 
    157 // Writes number 'value' in base 'base' into buffer 'buf' of size 'buf_size' bytes.
    158 // Assumes that buf_size > 0.
    159 static void format_unsigned(char* buf, size_t buf_size, uint64_t value, int base, bool caps) {
    160   char* p = buf;
    161   char* end = buf + buf_size - 1;
    162 
    163   // Generate digit string in reverse order.
    164   while (value) {
    165     unsigned d = value % base;
    166     value /= base;
    167     if (p != end) {
    168       char ch;
    169       if (d < 10) {
    170         ch = '0' + d;
    171       } else {
    172         ch = (caps ? 'A' : 'a') + (d - 10);
    173       }
    174       *p++ = ch;
    175     }
    176   }
    177 
    178   // Special case for 0.
    179   if (p == buf) {
    180     if (p != end) {
    181       *p++ = '0';
    182     }
    183   }
    184   *p = '\0';
    185 
    186   // Reverse digit string in-place.
    187   size_t length = p - buf;
    188   for (size_t i = 0, j = length - 1; i < j; ++i, --j) {
    189     char ch = buf[i];
    190     buf[i] = buf[j];
    191     buf[j] = ch;
    192   }
    193 }
    194 
    195 static void format_integer(char* buf, size_t buf_size, uint64_t value, char conversion) {
    196   // Decode the conversion specifier.
    197   int is_signed = (conversion == 'd' || conversion == 'i' || conversion == 'o');
    198   int base = 10;
    199   if (conversion == 'x' || conversion == 'X') {
    200     base = 16;
    201   } else if (conversion == 'o') {
    202     base = 8;
    203   }
    204   bool caps = (conversion == 'X');
    205 
    206   if (is_signed && static_cast<int64_t>(value) < 0) {
    207     buf[0] = '-';
    208     buf += 1;
    209     buf_size -= 1;
    210     value = static_cast<uint64_t>(-static_cast<int64_t>(value));
    211   }
    212   format_unsigned(buf, buf_size, value, base, caps);
    213 }
    214 
    215 template <typename Out>
    216 static void SendRepeat(Out& o, char ch, int count) {
    217   char pad[8];
    218   memset(pad, ch, sizeof(pad));
    219 
    220   const int pad_size = static_cast<int>(sizeof(pad));
    221   while (count > 0) {
    222     int avail = count;
    223     if (avail > pad_size) {
    224       avail = pad_size;
    225     }
    226     o.Send(pad, avail);
    227     count -= avail;
    228   }
    229 }
    230 
    231 /* Perform formatted output to an output target 'o' */
    232 template <typename Out>
    233 static void out_vformat(Out& o, const char* format, va_list args) {
    234   int nn = 0;
    235 
    236   for (;;) {
    237     int mm;
    238     int padZero = 0;
    239     int padLeft = 0;
    240     char sign = '\0';
    241     int width = -1;
    242     int prec = -1;
    243     size_t bytelen = sizeof(int);
    244     int slen;
    245     char buffer[32]; /* temporary buffer used to format numbers */
    246 
    247     char c;
    248 
    249     /* first, find all characters that are not 0 or '%' */
    250     /* then send them to the output directly */
    251     mm = nn;
    252     do {
    253       c = format[mm];
    254       if (c == '\0' || c == '%') break;
    255       mm++;
    256     } while (1);
    257 
    258     if (mm > nn) {
    259       o.Send(format + nn, mm - nn);
    260       nn = mm;
    261     }
    262 
    263     /* is this it ? then exit */
    264     if (c == '\0') break;
    265 
    266     /* nope, we are at a '%' modifier */
    267     nn++;  // skip it
    268 
    269     /* parse flags */
    270     for (;;) {
    271       c = format[nn++];
    272       if (c == '\0') { /* single trailing '%' ? */
    273         c = '%';
    274         o.Send(&c, 1);
    275         return;
    276       } else if (c == '0') {
    277         padZero = 1;
    278         continue;
    279       } else if (c == '-') {
    280         padLeft = 1;
    281         continue;
    282       } else if (c == ' ' || c == '+') {
    283         sign = c;
    284         continue;
    285       }
    286       break;
    287     }
    288 
    289     /* parse field width */
    290     if ((c >= '0' && c <= '9')) {
    291       nn--;
    292       width = static_cast<int>(parse_decimal(format, &nn));
    293       c = format[nn++];
    294     }
    295 
    296     /* parse precision */
    297     if (c == '.') {
    298       prec = static_cast<int>(parse_decimal(format, &nn));
    299       c = format[nn++];
    300     }
    301 
    302     /* length modifier */
    303     switch (c) {
    304       case 'h':
    305         bytelen = sizeof(short);
    306         if (format[nn] == 'h') {
    307           bytelen = sizeof(char);
    308           nn += 1;
    309         }
    310         c = format[nn++];
    311         break;
    312       case 'l':
    313         bytelen = sizeof(long);
    314         if (format[nn] == 'l') {
    315           bytelen = sizeof(long long);
    316           nn += 1;
    317         }
    318         c = format[nn++];
    319         break;
    320       case 'z':
    321         bytelen = sizeof(size_t);
    322         c = format[nn++];
    323         break;
    324       case 't':
    325         bytelen = sizeof(ptrdiff_t);
    326         c = format[nn++];
    327         break;
    328       default:;
    329     }
    330 
    331     /* conversion specifier */
    332     const char* str = buffer;
    333     if (c == 's') {
    334       /* string */
    335       str = va_arg(args, const char*);
    336       if (str == nullptr) {
    337         str = "(null)";
    338       }
    339     } else if (c == 'c') {
    340       /* character */
    341       /* NOTE: char is promoted to int when passed through the stack */
    342       buffer[0] = static_cast<char>(va_arg(args, int));
    343       buffer[1] = '\0';
    344     } else if (c == 'p') {
    345       uint64_t value = reinterpret_cast<uintptr_t>(va_arg(args, void*));
    346       buffer[0] = '0';
    347       buffer[1] = 'x';
    348       format_integer(buffer + 2, sizeof(buffer) - 2, value, 'x');
    349     } else if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X') {
    350       /* integers - first read value from stack */
    351       uint64_t value;
    352       int is_signed = (c == 'd' || c == 'i' || c == 'o');
    353 
    354       /* NOTE: int8_t and int16_t are promoted to int when passed
    355        *       through the stack
    356        */
    357       switch (bytelen) {
    358         case 1:
    359           value = static_cast<uint8_t>(va_arg(args, int));
    360           break;
    361         case 2:
    362           value = static_cast<uint16_t>(va_arg(args, int));
    363           break;
    364         case 4:
    365           value = va_arg(args, uint32_t);
    366           break;
    367         case 8:
    368           value = va_arg(args, uint64_t);
    369           break;
    370         default:
    371           return; /* should not happen */
    372       }
    373 
    374       /* sign extension, if needed */
    375       if (is_signed) {
    376         int shift = 64 - 8 * bytelen;
    377         value = static_cast<uint64_t>((static_cast<int64_t>(value << shift)) >> shift);
    378       }
    379 
    380       /* format the number properly into our buffer */
    381       format_integer(buffer, sizeof(buffer), value, c);
    382     } else if (c == '%') {
    383       buffer[0] = '%';
    384       buffer[1] = '\0';
    385     } else {
    386       __assert(__FILE__, __LINE__, "conversion specifier unsupported");
    387     }
    388 
    389     /* if we are here, 'str' points to the content that must be
    390      * outputted. handle padding and alignment now */
    391 
    392     slen = strlen(str);
    393 
    394     if (sign != '\0' || prec != -1) {
    395       __assert(__FILE__, __LINE__, "sign/precision unsupported");
    396     }
    397 
    398     if (slen < width && !padLeft) {
    399       char padChar = padZero ? '0' : ' ';
    400       SendRepeat(o, padChar, width - slen);
    401     }
    402 
    403     o.Send(str, slen);
    404 
    405     if (slen < width && padLeft) {
    406       char padChar = padZero ? '0' : ' ';
    407       SendRepeat(o, padChar, width - slen);
    408     }
    409   }
    410 }
    411 
    412 int async_safe_format_buffer_va_list(char* buffer, size_t buffer_size, const char* format,
    413                                      va_list args) {
    414   BufferOutputStream os(buffer, buffer_size);
    415   out_vformat(os, format, args);
    416   return os.total;
    417 }
    418 
    419 int async_safe_format_buffer(char* buffer, size_t buffer_size, const char* format, ...) {
    420   va_list args;
    421   va_start(args, format);
    422   int buffer_len = async_safe_format_buffer_va_list(buffer, buffer_size, format, args);
    423   va_end(args);
    424   return buffer_len;
    425 }
    426 
    427 int async_safe_format_fd_va_list(int fd, const char* format, va_list args) {
    428   FdOutputStream os(fd);
    429   out_vformat(os, format, args);
    430   return os.total;
    431 }
    432 
    433 int async_safe_format_fd(int fd, const char* format, ...) {
    434   va_list args;
    435   va_start(args, format);
    436   int result = async_safe_format_fd_va_list(fd, format, args);
    437   va_end(args);
    438   return result;
    439 }
    440 
    441 static int write_stderr(const char* tag, const char* msg) {
    442   iovec vec[4];
    443   vec[0].iov_base = const_cast<char*>(tag);
    444   vec[0].iov_len = strlen(tag);
    445   vec[1].iov_base = const_cast<char*>(": ");
    446   vec[1].iov_len = 2;
    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");
    450   vec[3].iov_len = 1;
    451 
    452   int result = TEMP_FAILURE_RETRY(writev(STDERR_FILENO, vec, 4));
    453   return result;
    454 }
    455 
    456 static int 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*.
    462 
    463   int log_fd = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
    464   if (log_fd == -1) {
    465     return -1;
    466   }
    467 
    468   union {
    469     struct sockaddr addr;
    470     struct sockaddr_un addrUn;
    471   } u;
    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));
    475 
    476   if (TEMP_FAILURE_RETRY(connect(log_fd, &u.addr, sizeof(u.addrUn))) != 0) {
    477     __close(log_fd);
    478     return -1;
    479   }
    480 
    481   return log_fd;
    482 }
    483 
    484 struct log_time {  // Wire format
    485   uint32_t tv_sec;
    486   uint32_t tv_nsec;
    487 };
    488 
    489 int async_safe_write_log(int priority, const char* tag, const char* msg) {
    490   int main_log_fd = open_log_socket();
    491   if (main_log_fd == -1) {
    492     // Try stderr instead.
    493     return write_stderr(tag, msg);
    494   }
    495 
    496   iovec vec[6];
    497   char log_id = (priority == ANDROID_LOG_FATAL) ? LOG_ID_CRASH : LOG_ID_MAIN;
    498   vec[0].iov_base = &log_id;
    499   vec[0].iov_len = sizeof(log_id);
    500   uint16_t tid = gettid();
    501   vec[1].iov_base = &tid;
    502   vec[1].iov_len = sizeof(tid);
    503   timespec ts;
    504   clock_gettime(CLOCK_REALTIME, &ts);
    505   log_time realtime_ts;
    506   realtime_ts.tv_sec = ts.tv_sec;
    507   realtime_ts.tv_nsec = ts.tv_nsec;
    508   vec[2].iov_base = &realtime_ts;
    509   vec[2].iov_len = sizeof(realtime_ts);
    510 
    511   vec[3].iov_base = &priority;
    512   vec[3].iov_len = 1;
    513   vec[4].iov_base = const_cast<char*>(tag);
    514   vec[4].iov_len = strlen(tag) + 1;
    515   vec[5].iov_base = const_cast<char*>(msg);
    516   vec[5].iov_len = strlen(msg) + 1;
    517 
    518   int result = TEMP_FAILURE_RETRY(writev(main_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
    519   __close(main_log_fd);
    520   return result;
    521 }
    522 
    523 int async_safe_format_log_va_list(int priority, const char* tag, const char* format, va_list args) {
    524   ErrnoRestorer errno_restorer;
    525   char buffer[1024];
    526   BufferOutputStream os(buffer, sizeof(buffer));
    527   out_vformat(os, format, args);
    528   return async_safe_write_log(priority, tag, buffer);
    529 }
    530 
    531 int async_safe_format_log(int priority, const char* tag, const char* format, ...) {
    532   va_list args;
    533   va_start(args, format);
    534   int result = async_safe_format_log_va_list(priority, tag, format, args);
    535   va_end(args);
    536   return result;
    537 }
    538 
    539 void async_safe_fatal_va_list(const char* prefix, const char* format, va_list args) {
    540   char msg[1024];
    541   BufferOutputStream os(msg, sizeof(msg));
    542 
    543   if (prefix) {
    544     os.Send(prefix, strlen(prefix));
    545     os.Send(": ", 2);
    546   }
    547 
    548   out_vformat(os, format, args);
    549 
    550   // Log to stderr for the benefit of "adb shell" users and gtests.
    551   struct iovec iov[2] = {
    552       {msg, strlen(msg)}, {const_cast<char*>("\n"), 1},
    553   };
    554   TEMP_FAILURE_RETRY(writev(2, iov, 2));
    555 
    556   // Log to the log for the benefit of regular app developers (whose stdout and stderr are closed).
    557   async_safe_write_log(ANDROID_LOG_FATAL, "libc", msg);
    558 
    559   android_set_abort_message(msg);
    560 }
    561 
    562 void async_safe_fatal_no_abort(const char* fmt, ...) {
    563   va_list args;
    564   va_start(args, fmt);
    565   async_safe_fatal_va_list(nullptr, fmt, args);
    566   va_end(args);
    567 }
    568