• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 namespace __sanitizer {
25 
AppendChar(char ** buff,const char * buff_end,char c)26 static int AppendChar(char **buff, const char *buff_end, char c) {
27   if (*buff < buff_end) {
28     **buff = c;
29     (*buff)++;
30   }
31   return 1;
32 }
33 
34 // Appends number in a given base to buffer. If its length is less than
35 // "minimal_num_length", it is padded with leading zeroes.
AppendUnsigned(char ** buff,const char * buff_end,u64 num,u8 base,u8 minimal_num_length)36 static int AppendUnsigned(char **buff, const char *buff_end, u64 num,
37                           u8 base, u8 minimal_num_length) {
38   uptr const kMaxLen = 30;
39   RAW_CHECK(base == 10 || base == 16);
40   RAW_CHECK(minimal_num_length < kMaxLen);
41   uptr num_buffer[kMaxLen];
42   uptr pos = 0;
43   do {
44     RAW_CHECK_MSG(pos < kMaxLen, "appendNumber buffer overflow");
45     num_buffer[pos++] = num % base;
46     num /= base;
47   } while (num > 0);
48   if (pos < minimal_num_length) {
49     // Make sure compiler doesn't insert call to memset here.
50     internal_memset(&num_buffer[pos], 0,
51                     sizeof(num_buffer[0]) * (minimal_num_length - pos));
52     pos = minimal_num_length;
53   }
54   int result = 0;
55   while (pos-- > 0) {
56     uptr digit = num_buffer[pos];
57     result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
58                                                       : 'a' + digit - 10);
59   }
60   return result;
61 }
62 
AppendSignedDecimal(char ** buff,const char * buff_end,s64 num,u8 minimal_num_length)63 static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
64                                u8 minimal_num_length) {
65   int result = 0;
66   if (num < 0) {
67     result += AppendChar(buff, buff_end, '-');
68     num = -num;
69     if (minimal_num_length)
70       --minimal_num_length;
71   }
72   result += AppendUnsigned(buff, buff_end, (u64)num, 10, minimal_num_length);
73   return result;
74 }
75 
AppendString(char ** buff,const char * buff_end,const char * s)76 static int AppendString(char **buff, const char *buff_end, const char *s) {
77   if (s == 0)
78     s = "<null>";
79   int result = 0;
80   for (; *s; s++) {
81     result += AppendChar(buff, buff_end, *s);
82   }
83   return result;
84 }
85 
AppendPointer(char ** buff,const char * buff_end,u64 ptr_value)86 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
87   int result = 0;
88   result += AppendString(buff, buff_end, "0x");
89   result += AppendUnsigned(buff, buff_end, ptr_value, 16,
90                            (SANITIZER_WORDSIZE == 64) ? 12 : 8);
91   return result;
92 }
93 
VSNPrintf(char * buff,int buff_length,const char * format,va_list args)94 int VSNPrintf(char *buff, int buff_length,
95               const char *format, va_list args) {
96   static const char *kPrintfFormatsHelp =
97     "Supported Printf formats: %(0[0-9]*)?(z|ll)?{d,u,x}; %p; %s; %c\n";
98   RAW_CHECK(format);
99   RAW_CHECK(buff_length > 0);
100   const char *buff_end = &buff[buff_length - 1];
101   const char *cur = format;
102   int result = 0;
103   for (; *cur; cur++) {
104     if (*cur != '%') {
105       result += AppendChar(&buff, buff_end, *cur);
106       continue;
107     }
108     cur++;
109     bool have_width = (*cur == '0');
110     int width = 0;
111     if (have_width) {
112       while (*cur >= '0' && *cur <= '9') {
113         have_width = true;
114         width = width * 10 + *cur++ - '0';
115       }
116     }
117     bool have_z = (*cur == 'z');
118     cur += have_z;
119     bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
120     cur += have_ll * 2;
121     s64 dval;
122     u64 uval;
123     bool have_flags = have_width | have_z | have_ll;
124     switch (*cur) {
125       case 'd': {
126         dval = have_ll ? va_arg(args, s64)
127              : have_z ? va_arg(args, sptr)
128              : va_arg(args, int);
129         result += AppendSignedDecimal(&buff, buff_end, dval, width);
130         break;
131       }
132       case 'u':
133       case 'x': {
134         uval = have_ll ? va_arg(args, u64)
135              : have_z ? va_arg(args, uptr)
136              : va_arg(args, unsigned);
137         result += AppendUnsigned(&buff, buff_end, uval,
138                                  (*cur == 'u') ? 10 : 16, width);
139         break;
140       }
141       case 'p': {
142         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
143         result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
144         break;
145       }
146       case 's': {
147         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
148         result += AppendString(&buff, buff_end, va_arg(args, char*));
149         break;
150       }
151       case 'c': {
152         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
153         result += AppendChar(&buff, buff_end, va_arg(args, int));
154         break;
155       }
156       case '%' : {
157         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
158         result += AppendChar(&buff, buff_end, '%');
159         break;
160       }
161       default: {
162         RAW_CHECK_MSG(false, kPrintfFormatsHelp);
163       }
164     }
165   }
166   RAW_CHECK(buff <= buff_end);
167   AppendChar(&buff, buff_end + 1, '\0');
168   return result;
169 }
170 
171 static void (*PrintfAndReportCallback)(const char *);
SetPrintfAndReportCallback(void (* callback)(const char *))172 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
173   PrintfAndReportCallback = callback;
174 }
175 
Printf(const char * format,...)176 void Printf(const char *format, ...) {
177   const int kLen = 16 * 1024;
178   InternalScopedBuffer<char> buffer(kLen);
179   va_list args;
180   va_start(args, format);
181   int needed_length = VSNPrintf(buffer.data(), kLen, format, args);
182   va_end(args);
183   RAW_CHECK_MSG(needed_length < kLen, "Buffer in Printf is too short!\n");
184   RawWrite(buffer.data());
185   if (PrintfAndReportCallback)
186     PrintfAndReportCallback(buffer.data());
187 }
188 
189 // Writes at most "length" symbols to "buffer" (including trailing '\0').
190 // Returns the number of symbols that should have been written to buffer
191 // (not including trailing '\0'). Thus, the string is truncated
192 // iff return value is not less than "length".
internal_snprintf(char * buffer,uptr length,const char * format,...)193 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
194   va_list args;
195   va_start(args, format);
196   int needed_length = VSNPrintf(buffer, length, format, args);
197   va_end(args);
198   return needed_length;
199 }
200 
201 // Like Printf, but prints the current PID before the output string.
Report(const char * format,...)202 void Report(const char *format, ...) {
203   const int kLen = 16 * 1024;
204   // |local_buffer| is small enough not to overflow the stack and/or violate
205   // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
206   // hand, the bigger the buffer is, the more the chance the error report will
207   // fit into it.
208   char local_buffer[400];
209   int needed_length;
210   int pid = GetPid();
211   char *buffer = local_buffer;
212   int cur_size = sizeof(local_buffer) / sizeof(char);
213   for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
214     needed_length = internal_snprintf(buffer, cur_size,
215                                       "==%d==", pid);
216     if (needed_length >= cur_size) {
217       if (use_mmap) {
218         RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
219       } else {
220         // The pid doesn't fit into the local buffer.
221         continue;
222       }
223     }
224     va_list args;
225     va_start(args, format);
226     needed_length += VSNPrintf(buffer + needed_length,
227                                cur_size - needed_length, format, args);
228     va_end(args);
229     if (needed_length >= cur_size) {
230       if (use_mmap) {
231         RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
232       } else {
233         // The error message doesn't fit into the local buffer - allocate a
234         // bigger one.
235         buffer = (char*)MmapOrDie(kLen, "Report");
236         cur_size = kLen;
237         continue;
238       }
239     } else {
240       RawWrite(buffer);
241       if (PrintfAndReportCallback)
242         PrintfAndReportCallback(buffer);
243       // Don't do anything for the second time if the first iteration
244       // succeeded.
245       break;
246     }
247   }
248   // If we had mapped any memory, clean up.
249   if (buffer != local_buffer) UnmapOrDie((void*)buffer, cur_size);
250 }
251 
252 }  // namespace __sanitizer
253