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