]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_printf.cc
Merge OpenSSL 1.1.1a.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_printf.cc
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 #include "sanitizer_common.h"
18 #include "sanitizer_flags.h"
19 #include "sanitizer_libc.h"
20
21 #include <stdio.h>
22 #include <stdarg.h>
23
24 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 &&               \
25       !defined(va_copy)
26 # define va_copy(dst, src) ((dst) = (src))
27 #endif
28
29 namespace __sanitizer {
30
31 static int AppendChar(char **buff, const char *buff_end, char c) {
32   if (*buff < buff_end) {
33     **buff = c;
34     (*buff)++;
35   }
36   return 1;
37 }
38
39 // Appends number in a given base to buffer. If its length is less than
40 // |minimal_num_length|, it is padded with leading zeroes or spaces, depending
41 // on the value of |pad_with_zero|.
42 static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
43                         u8 base, u8 minimal_num_length, bool pad_with_zero,
44                         bool negative, bool uppercase) {
45   uptr const kMaxLen = 30;
46   RAW_CHECK(base == 10 || base == 16);
47   RAW_CHECK(base == 10 || !negative);
48   RAW_CHECK(absolute_value || !negative);
49   RAW_CHECK(minimal_num_length < kMaxLen);
50   int result = 0;
51   if (negative && minimal_num_length)
52     --minimal_num_length;
53   if (negative && pad_with_zero)
54     result += AppendChar(buff, buff_end, '-');
55   uptr num_buffer[kMaxLen];
56   int pos = 0;
57   do {
58     RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
59     num_buffer[pos++] = absolute_value % base;
60     absolute_value /= base;
61   } while (absolute_value > 0);
62   if (pos < minimal_num_length) {
63     // Make sure compiler doesn't insert call to memset here.
64     internal_memset(&num_buffer[pos], 0,
65                     sizeof(num_buffer[0]) * (minimal_num_length - pos));
66     pos = minimal_num_length;
67   }
68   RAW_CHECK(pos > 0);
69   pos--;
70   for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
71     char c = (pad_with_zero || pos == 0) ? '0' : ' ';
72     result += AppendChar(buff, buff_end, c);
73   }
74   if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
75   for (; pos >= 0; pos--) {
76     char digit = static_cast<char>(num_buffer[pos]);
77     digit = (digit < 10) ? '0' + digit : (uppercase ? 'A' : 'a') + digit - 10;
78     result += AppendChar(buff, buff_end, digit);
79   }
80   return result;
81 }
82
83 static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
84                           u8 minimal_num_length, bool pad_with_zero,
85                           bool uppercase) {
86   return AppendNumber(buff, buff_end, num, base, minimal_num_length,
87                       pad_with_zero, false /* negative */, uppercase);
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                       false /* uppercase */);
96 }
97
98 static int AppendString(char **buff, const char *buff_end, int precision,
99                         const char *s) {
100   if (!s)
101     s = "<null>";
102   int result = 0;
103   for (; *s; s++) {
104     if (precision >= 0 && result >= precision)
105       break;
106     result += AppendChar(buff, buff_end, *s);
107   }
108   return result;
109 }
110
111 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
112   int result = 0;
113   result += AppendString(buff, buff_end, -1, "0x");
114   result += AppendUnsigned(buff, buff_end, ptr_value, 16,
115                            SANITIZER_POINTER_FORMAT_LENGTH,
116                            true /* pad_with_zero */, false /* uppercase */);
117   return result;
118 }
119
120 int VSNPrintf(char *buff, int buff_length,
121               const char *format, va_list args) {
122   static const char *kPrintfFormatsHelp =
123       "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x,X}; %p; %(\\.\\*)?s; "
124       "%c\n";
125   RAW_CHECK(format);
126   RAW_CHECK(buff_length > 0);
127   const char *buff_end = &buff[buff_length - 1];
128   const char *cur = format;
129   int result = 0;
130   for (; *cur; cur++) {
131     if (*cur != '%') {
132       result += AppendChar(&buff, buff_end, *cur);
133       continue;
134     }
135     cur++;
136     bool have_width = (*cur >= '0' && *cur <= '9');
137     bool pad_with_zero = (*cur == '0');
138     int width = 0;
139     if (have_width) {
140       while (*cur >= '0' && *cur <= '9') {
141         width = width * 10 + *cur++ - '0';
142       }
143     }
144     bool have_precision = (cur[0] == '.' && cur[1] == '*');
145     int precision = -1;
146     if (have_precision) {
147       cur += 2;
148       precision = va_arg(args, int);
149     }
150     bool have_z = (*cur == 'z');
151     cur += have_z;
152     bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
153     cur += have_ll * 2;
154     s64 dval;
155     u64 uval;
156     bool have_flags = have_width | have_z | have_ll;
157     // Only %s supports precision for now
158     CHECK(!(precision >= 0 && *cur != 's'));
159     switch (*cur) {
160       case 'd': {
161         dval = have_ll ? va_arg(args, s64)
162              : have_z ? va_arg(args, sptr)
163              : va_arg(args, int);
164         result += AppendSignedDecimal(&buff, buff_end, dval, width,
165                                       pad_with_zero);
166         break;
167       }
168       case 'u':
169       case 'x':
170       case 'X': {
171         uval = have_ll ? va_arg(args, u64)
172              : have_z ? va_arg(args, uptr)
173              : va_arg(args, unsigned);
174         bool uppercase = (*cur == 'X');
175         result += AppendUnsigned(&buff, buff_end, uval, (*cur == 'u') ? 10 : 16,
176                                  width, pad_with_zero, uppercase);
177         break;
178       }
179       case 'p': {
180         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
181         result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
182         break;
183       }
184       case 's': {
185         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
186         result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
187         break;
188       }
189       case 'c': {
190         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
191         result += AppendChar(&buff, buff_end, va_arg(args, int));
192         break;
193       }
194       case '%' : {
195         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
196         result += AppendChar(&buff, buff_end, '%');
197         break;
198       }
199       default: {
200         RAW_CHECK_MSG(false, kPrintfFormatsHelp);
201       }
202     }
203   }
204   RAW_CHECK(buff <= buff_end);
205   AppendChar(&buff, buff_end + 1, '\0');
206   return result;
207 }
208
209 static void (*PrintfAndReportCallback)(const char *);
210 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
211   PrintfAndReportCallback = callback;
212 }
213
214 // Can be overriden in frontend.
215 #if SANITIZER_GO && defined(TSAN_EXTERNAL_HOOKS)
216 // Implementation must be defined in frontend.
217 extern "C" void OnPrint(const char *str);
218 #else
219 SANITIZER_INTERFACE_WEAK_DEF(void, OnPrint, const char *str) {
220   (void)str;
221 }
222 #endif
223
224 static void CallPrintfAndReportCallback(const char *str) {
225   OnPrint(str);
226   if (PrintfAndReportCallback)
227     PrintfAndReportCallback(str);
228 }
229
230 static void NOINLINE SharedPrintfCodeNoBuffer(bool append_pid,
231                                               char *local_buffer,
232                                               int buffer_size,
233                                               const char *format,
234                                               va_list args) {
235   va_list args2;
236   va_copy(args2, args);
237   const int kLen = 16 * 1024;
238   int needed_length;
239   char *buffer = local_buffer;
240   // First try to print a message using a local buffer, and then fall back to
241   // mmaped buffer.
242   for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
243     if (use_mmap) {
244       va_end(args);
245       va_copy(args, args2);
246       buffer = (char*)MmapOrDie(kLen, "Report");
247       buffer_size = kLen;
248     }
249     needed_length = 0;
250     // Check that data fits into the current buffer.
251 #   define CHECK_NEEDED_LENGTH \
252       if (needed_length >= buffer_size) { \
253         if (!use_mmap) continue; \
254         RAW_CHECK_MSG(needed_length < kLen, \
255                       "Buffer in Report is too short!\n"); \
256       }
257     // Fuchsia's logging infrastructure always keeps track of the logging
258     // process, thread, and timestamp, so never prepend such information.
259     if (!SANITIZER_FUCHSIA && append_pid) {
260       int pid = internal_getpid();
261       const char *exe_name = GetProcessName();
262       if (common_flags()->log_exe_name && exe_name) {
263         needed_length += internal_snprintf(buffer, buffer_size,
264                                            "==%s", exe_name);
265         CHECK_NEEDED_LENGTH
266       }
267       needed_length += internal_snprintf(
268           buffer + needed_length, buffer_size - needed_length, "==%d==", pid);
269       CHECK_NEEDED_LENGTH
270     }
271     needed_length += VSNPrintf(buffer + needed_length,
272                                buffer_size - needed_length, format, args);
273     CHECK_NEEDED_LENGTH
274     // If the message fit into the buffer, print it and exit.
275     break;
276 #   undef CHECK_NEEDED_LENGTH
277   }
278   RawWrite(buffer);
279
280   // Remove color sequences from the message.
281   RemoveANSIEscapeSequencesFromString(buffer);
282   CallPrintfAndReportCallback(buffer);
283   LogMessageOnPrintf(buffer);
284
285   // If we had mapped any memory, clean up.
286   if (buffer != local_buffer)
287     UnmapOrDie((void *)buffer, buffer_size);
288   va_end(args2);
289 }
290
291 static void NOINLINE SharedPrintfCode(bool append_pid, const char *format,
292                                       va_list args) {
293   // |local_buffer| is small enough not to overflow the stack and/or violate
294   // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
295   // hand, the bigger the buffer is, the more the chance the error report will
296   // fit into it.
297   char local_buffer[400];
298   SharedPrintfCodeNoBuffer(append_pid, local_buffer, ARRAY_SIZE(local_buffer),
299                            format, args);
300 }
301
302 FORMAT(1, 2)
303 void Printf(const char *format, ...) {
304   va_list args;
305   va_start(args, format);
306   SharedPrintfCode(false, format, args);
307   va_end(args);
308 }
309
310 // Like Printf, but prints the current PID before the output string.
311 FORMAT(1, 2)
312 void Report(const char *format, ...) {
313   va_list args;
314   va_start(args, format);
315   SharedPrintfCode(true, format, args);
316   va_end(args);
317 }
318
319 // Writes at most "length" symbols to "buffer" (including trailing '\0').
320 // Returns the number of symbols that should have been written to buffer
321 // (not including trailing '\0'). Thus, the string is truncated
322 // iff return value is not less than "length".
323 FORMAT(3, 4)
324 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
325   va_list args;
326   va_start(args, format);
327   int needed_length = VSNPrintf(buffer, length, format, args);
328   va_end(args);
329   return needed_length;
330 }
331
332 FORMAT(2, 3)
333 void InternalScopedString::append(const char *format, ...) {
334   CHECK_LT(length_, size());
335   va_list args;
336   va_start(args, format);
337   VSNPrintf(data() + length_, size() - length_, format, args);
338   va_end(args);
339   length_ += internal_strlen(data() + length_);
340   CHECK_LT(length_, size());
341 }
342
343 } // namespace __sanitizer