Home | History | Annotate | Download | only in sanitizer_common
      1 //===-- sanitizer_printf.cc -----------------------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file is shared between AddressSanitizer and ThreadSanitizer.
     11 //
     12 // Internal printf function, used inside run-time libraries.
     13 // We can't use libc printf because we intercept some of the functions used
     14 // inside it.
     15 //===----------------------------------------------------------------------===//
     16 
     17 
     18 #include "sanitizer_common.h"
     19 #include "sanitizer_libc.h"
     20 
     21 #include <stdio.h>
     22 #include <stdarg.h>
     23 
     24 #if SANITIZER_WINDOWS && !defined(va_copy)
     25 # define va_copy(dst, src) ((dst) = (src))
     26 #endif
     27 
     28 namespace __sanitizer {
     29 
     30 StaticSpinMutex CommonSanitizerReportMutex;
     31 
     32 static int AppendChar(char **buff, const char *buff_end, char c) {
     33   if (*buff < buff_end) {
     34     **buff = c;
     35     (*buff)++;
     36   }
     37   return 1;
     38 }
     39 
     40 // Appends number in a given base to buffer. If its length is less than
     41 // |minimal_num_length|, it is padded with leading zeroes or spaces, depending
     42 // on the value of |pad_with_zero|.
     43 static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
     44                         u8 base, u8 minimal_num_length, bool pad_with_zero,
     45                         bool negative) {
     46   uptr const kMaxLen = 30;
     47   RAW_CHECK(base == 10 || base == 16);
     48   RAW_CHECK(base == 10 || !negative);
     49   RAW_CHECK(absolute_value || !negative);
     50   RAW_CHECK(minimal_num_length < kMaxLen);
     51   int result = 0;
     52   if (negative && minimal_num_length)
     53     --minimal_num_length;
     54   if (negative && pad_with_zero)
     55     result += AppendChar(buff, buff_end, '-');
     56   uptr num_buffer[kMaxLen];
     57   int pos = 0;
     58   do {
     59     RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
     60     num_buffer[pos++] = absolute_value % base;
     61     absolute_value /= base;
     62   } while (absolute_value > 0);
     63   if (pos < minimal_num_length) {
     64     // Make sure compiler doesn't insert call to memset here.
     65     internal_memset(&num_buffer[pos], 0,
     66                     sizeof(num_buffer[0]) * (minimal_num_length - pos));
     67     pos = minimal_num_length;
     68   }
     69   RAW_CHECK(pos > 0);
     70   pos--;
     71   for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
     72     char c = (pad_with_zero || pos == 0) ? '0' : ' ';
     73     result += AppendChar(buff, buff_end, c);
     74   }
     75   if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
     76   for (; pos >= 0; pos--) {
     77     char digit = static_cast<char>(num_buffer[pos]);
     78     result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
     79                                                       : 'a' + digit - 10);
     80   }
     81   return result;
     82 }
     83 
     84 static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
     85                           u8 minimal_num_length, bool pad_with_zero) {
     86   return AppendNumber(buff, buff_end, num, base, minimal_num_length,
     87                       pad_with_zero, false /* negative */);
     88 }
     89 
     90 static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
     91                                u8 minimal_num_length, bool pad_with_zero) {
     92   bool negative = (num < 0);
     93   return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
     94                       minimal_num_length, pad_with_zero, negative);
     95 }
     96 
     97 static int AppendString(char **buff, const char *buff_end, const char *s) {
     98   if (s == 0)
     99     s = "<null>";
    100   int result = 0;
    101   for (; *s; s++) {
    102     result += AppendChar(buff, buff_end, *s);
    103   }
    104   return result;
    105 }
    106 
    107 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
    108   int result = 0;
    109   result += AppendString(buff, buff_end, "0x");
    110   result += AppendUnsigned(buff, buff_end, ptr_value, 16,
    111                            (SANITIZER_WORDSIZE == 64) ? 12 : 8, true);
    112   return result;
    113 }
    114 
    115 int VSNPrintf(char *buff, int buff_length,
    116               const char *format, va_list args) {
    117   static const char *kPrintfFormatsHelp =
    118     "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %s; %c\n";
    119   RAW_CHECK(format);
    120   RAW_CHECK(buff_length > 0);
    121   const char *buff_end = &buff[buff_length - 1];
    122   const char *cur = format;
    123   int result = 0;
    124   for (; *cur; cur++) {
    125     if (*cur != '%') {
    126       result += AppendChar(&buff, buff_end, *cur);
    127       continue;
    128     }
    129     cur++;
    130     bool have_width = (*cur >= '0' && *cur <= '9');
    131     bool pad_with_zero = (*cur == '0');
    132     int width = 0;
    133     if (have_width) {
    134       while (*cur >= '0' && *cur <= '9') {
    135         width = width * 10 + *cur++ - '0';
    136       }
    137     }
    138     bool have_z = (*cur == 'z');
    139     cur += have_z;
    140     bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
    141     cur += have_ll * 2;
    142     s64 dval;
    143     u64 uval;
    144     bool have_flags = have_width | have_z | have_ll;
    145     switch (*cur) {
    146       case 'd': {
    147         dval = have_ll ? va_arg(args, s64)
    148              : have_z ? va_arg(args, sptr)
    149              : va_arg(args, int);
    150         result += AppendSignedDecimal(&buff, buff_end, dval, width,
    151                                       pad_with_zero);
    152         break;
    153       }
    154       case 'u':
    155       case 'x': {
    156         uval = have_ll ? va_arg(args, u64)
    157              : have_z ? va_arg(args, uptr)
    158              : va_arg(args, unsigned);
    159         result += AppendUnsigned(&buff, buff_end, uval,
    160                                  (*cur == 'u') ? 10 : 16, width, pad_with_zero);
    161         break;
    162       }
    163       case 'p': {
    164         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
    165         result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
    166         break;
    167       }
    168       case 's': {
    169         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
    170         result += AppendString(&buff, buff_end, va_arg(args, char*));
    171         break;
    172       }
    173       case 'c': {
    174         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
    175         result += AppendChar(&buff, buff_end, va_arg(args, int));
    176         break;
    177       }
    178       case '%' : {
    179         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
    180         result += AppendChar(&buff, buff_end, '%');
    181         break;
    182       }
    183       default: {
    184         RAW_CHECK_MSG(false, kPrintfFormatsHelp);
    185       }
    186     }
    187   }
    188   RAW_CHECK(buff <= buff_end);
    189   AppendChar(&buff, buff_end + 1, '\0');
    190   return result;
    191 }
    192 
    193 static void (*PrintfAndReportCallback)(const char *);
    194 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
    195   PrintfAndReportCallback = callback;
    196 }
    197 
    198 #if SANITIZER_SUPPORTS_WEAK_HOOKS
    199 // Can be overriden in frontend.
    200 SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
    201 void OnPrint(const char *str);
    202 #endif
    203 
    204 static void CallPrintfAndReportCallback(const char *str) {
    205 #if SANITIZER_SUPPORTS_WEAK_HOOKS
    206   if (&OnPrint != NULL)
    207     OnPrint(str);
    208 #endif
    209   if (PrintfAndReportCallback)
    210     PrintfAndReportCallback(str);
    211 }
    212 
    213 static void SharedPrintfCode(bool append_pid, const char *format,
    214                              va_list args) {
    215   va_list args2;
    216   va_copy(args2, args);
    217   const int kLen = 16 * 1024;
    218   // |local_buffer| is small enough not to overflow the stack and/or violate
    219   // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
    220   // hand, the bigger the buffer is, the more the chance the error report will
    221   // fit into it.
    222   char local_buffer[400];
    223   int needed_length;
    224   char *buffer = local_buffer;
    225   int buffer_size = ARRAY_SIZE(local_buffer);
    226   // First try to print a message using a local buffer, and then fall back to
    227   // mmaped buffer.
    228   for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
    229     if (use_mmap) {
    230       va_end(args);
    231       va_copy(args, args2);
    232       buffer = (char*)MmapOrDie(kLen, "Report");
    233       buffer_size = kLen;
    234     }
    235     needed_length = 0;
    236     if (append_pid) {
    237       int pid = internal_getpid();
    238       needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
    239       if (needed_length >= buffer_size) {
    240         // The pid doesn't fit into the current buffer.
    241         if (!use_mmap)
    242           continue;
    243         RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
    244       }
    245     }
    246     needed_length += VSNPrintf(buffer + needed_length,
    247                                buffer_size - needed_length, format, args);
    248     if (needed_length >= buffer_size) {
    249       // The message doesn't fit into the current buffer.
    250       if (!use_mmap)
    251         continue;
    252       RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
    253     }
    254     // If the message fit into the buffer, print it and exit.
    255     break;
    256   }
    257   RawWrite(buffer);
    258   CallPrintfAndReportCallback(buffer);
    259   // If we had mapped any memory, clean up.
    260   if (buffer != local_buffer)
    261     UnmapOrDie((void *)buffer, buffer_size);
    262   va_end(args2);
    263 }
    264 
    265 void Printf(const char *format, ...) {
    266   va_list args;
    267   va_start(args, format);
    268   SharedPrintfCode(false, format, args);
    269   va_end(args);
    270 }
    271 
    272 // Like Printf, but prints the current PID before the output string.
    273 void Report(const char *format, ...) {
    274   va_list args;
    275   va_start(args, format);
    276   SharedPrintfCode(true, format, args);
    277   va_end(args);
    278 }
    279 
    280 // Writes at most "length" symbols to "buffer" (including trailing '\0').
    281 // Returns the number of symbols that should have been written to buffer
    282 // (not including trailing '\0'). Thus, the string is truncated
    283 // iff return value is not less than "length".
    284 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
    285   va_list args;
    286   va_start(args, format);
    287   int needed_length = VSNPrintf(buffer, length, format, args);
    288   va_end(args);
    289   return needed_length;
    290 }
    291 
    292 }  // namespace __sanitizer
    293