2017-05-11 François Dumont <fdumont@gcc.gnu.org>
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_printf.cc
blobc11113da244ee58de5d729cbb3783c481a4c33e8
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 StaticSpinMutex CommonSanitizerReportMutex;
31 static int AppendChar(char **buff, const char *buff_end, char c) {
32 if (*buff < buff_end) {
33 **buff = c;
34 (*buff)++;
36 return 1;
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) {
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;
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);
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 result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
78 : 'a' + digit - 10);
80 return result;
83 static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
84 u8 minimal_num_length, bool pad_with_zero) {
85 return AppendNumber(buff, buff_end, num, base, minimal_num_length,
86 pad_with_zero, false /* negative */);
89 static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
90 u8 minimal_num_length, bool pad_with_zero) {
91 bool negative = (num < 0);
92 return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
93 minimal_num_length, pad_with_zero, negative);
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, true);
114 return result;
117 int VSNPrintf(char *buff, int buff_length,
118 const char *format, va_list args) {
119 static const char *kPrintfFormatsHelp =
120 "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %(\\.\\*)?s; %c\n";
121 RAW_CHECK(format);
122 RAW_CHECK(buff_length > 0);
123 const char *buff_end = &buff[buff_length - 1];
124 const char *cur = format;
125 int result = 0;
126 for (; *cur; cur++) {
127 if (*cur != '%') {
128 result += AppendChar(&buff, buff_end, *cur);
129 continue;
131 cur++;
132 bool have_width = (*cur >= '0' && *cur <= '9');
133 bool pad_with_zero = (*cur == '0');
134 int width = 0;
135 if (have_width) {
136 while (*cur >= '0' && *cur <= '9') {
137 width = width * 10 + *cur++ - '0';
140 bool have_precision = (cur[0] == '.' && cur[1] == '*');
141 int precision = -1;
142 if (have_precision) {
143 cur += 2;
144 precision = va_arg(args, int);
146 bool have_z = (*cur == 'z');
147 cur += have_z;
148 bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
149 cur += have_ll * 2;
150 s64 dval;
151 u64 uval;
152 bool have_flags = have_width | have_z | have_ll;
153 // Only %s supports precision for now
154 CHECK(!(precision >= 0 && *cur != 's'));
155 switch (*cur) {
156 case 'd': {
157 dval = have_ll ? va_arg(args, s64)
158 : have_z ? va_arg(args, sptr)
159 : va_arg(args, int);
160 result += AppendSignedDecimal(&buff, buff_end, dval, width,
161 pad_with_zero);
162 break;
164 case 'u':
165 case 'x': {
166 uval = have_ll ? va_arg(args, u64)
167 : have_z ? va_arg(args, uptr)
168 : va_arg(args, unsigned);
169 result += AppendUnsigned(&buff, buff_end, uval,
170 (*cur == 'u') ? 10 : 16, width, pad_with_zero);
171 break;
173 case 'p': {
174 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
175 result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
176 break;
178 case 's': {
179 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
180 result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
181 break;
183 case 'c': {
184 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
185 result += AppendChar(&buff, buff_end, va_arg(args, int));
186 break;
188 case '%' : {
189 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
190 result += AppendChar(&buff, buff_end, '%');
191 break;
193 default: {
194 RAW_CHECK_MSG(false, kPrintfFormatsHelp);
198 RAW_CHECK(buff <= buff_end);
199 AppendChar(&buff, buff_end + 1, '\0');
200 return result;
203 static void (*PrintfAndReportCallback)(const char *);
204 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
205 PrintfAndReportCallback = callback;
208 // Can be overriden in frontend.
209 #if SANITIZER_SUPPORTS_WEAK_HOOKS
210 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
211 void OnPrint(const char *str) {
212 (void)str;
214 #elif SANITIZER_GO && defined(TSAN_EXTERNAL_HOOKS)
215 void OnPrint(const char *str);
216 #else
217 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 SharedPrintfCode(bool append_pid, const char *format,
229 va_list args) {
230 va_list args2;
231 va_copy(args2, args);
232 const int kLen = 16 * 1024;
233 // |local_buffer| is small enough not to overflow the stack and/or violate
234 // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
235 // hand, the bigger the buffer is, the more the chance the error report will
236 // fit into it.
237 char local_buffer[400];
238 int needed_length;
239 char *buffer = local_buffer;
240 int buffer_size = ARRAY_SIZE(local_buffer);
241 // First try to print a message using a local buffer, and then fall back to
242 // mmaped buffer.
243 for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
244 if (use_mmap) {
245 va_end(args);
246 va_copy(args, args2);
247 buffer = (char*)MmapOrDie(kLen, "Report");
248 buffer_size = kLen;
250 needed_length = 0;
251 // Check that data fits into the current buffer.
252 # define CHECK_NEEDED_LENGTH \
253 if (needed_length >= buffer_size) { \
254 if (!use_mmap) continue; \
255 RAW_CHECK_MSG(needed_length < kLen, \
256 "Buffer in Report is too short!\n"); \
258 if (append_pid) {
259 int pid = internal_getpid();
260 const char *exe_name = GetProcessName();
261 if (common_flags()->log_exe_name && exe_name) {
262 needed_length += internal_snprintf(buffer, buffer_size,
263 "==%s", exe_name);
264 CHECK_NEEDED_LENGTH
266 needed_length += internal_snprintf(buffer + needed_length,
267 buffer_size - needed_length,
268 "==%d==", pid);
269 CHECK_NEEDED_LENGTH
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
278 RawWrite(buffer);
280 // Remove color sequences from the message.
281 RemoveANSIEscapeSequencesFromString(buffer);
282 CallPrintfAndReportCallback(buffer);
283 LogMessageOnPrintf(buffer);
285 // If we had mapped any memory, clean up.
286 if (buffer != local_buffer)
287 UnmapOrDie((void *)buffer, buffer_size);
288 va_end(args2);
291 FORMAT(1, 2)
292 void Printf(const char *format, ...) {
293 va_list args;
294 va_start(args, format);
295 SharedPrintfCode(false, format, args);
296 va_end(args);
299 // Like Printf, but prints the current PID before the output string.
300 FORMAT(1, 2)
301 void Report(const char *format, ...) {
302 va_list args;
303 va_start(args, format);
304 SharedPrintfCode(true, format, args);
305 va_end(args);
308 // Writes at most "length" symbols to "buffer" (including trailing '\0').
309 // Returns the number of symbols that should have been written to buffer
310 // (not including trailing '\0'). Thus, the string is truncated
311 // iff return value is not less than "length".
312 FORMAT(3, 4)
313 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
314 va_list args;
315 va_start(args, format);
316 int needed_length = VSNPrintf(buffer, length, format, args);
317 va_end(args);
318 return needed_length;
321 FORMAT(2, 3)
322 void InternalScopedString::append(const char *format, ...) {
323 CHECK_LT(length_, size());
324 va_list args;
325 va_start(args, format);
326 VSNPrintf(data() + length_, size() - length_, format, args);
327 va_end(args);
328 length_ += internal_strlen(data() + length_);
329 CHECK_LT(length_, size());
332 } // namespace __sanitizer