* Add missing ChangeLog entry.
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_printf.cc
blobfc0c357ba86cca243d8956c4bad4a28466aa546f
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 //===----------------------------------------------------------------------===//
16 #include "sanitizer_common.h"
17 #include "sanitizer_flags.h"
18 #include "sanitizer_libc.h"
20 #include <stdio.h>
21 #include <stdarg.h>
23 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 && \
24 !defined(va_copy)
25 # define va_copy(dst, src) ((dst) = (src))
26 #endif
28 namespace __sanitizer {
30 StaticSpinMutex CommonSanitizerReportMutex;
32 static int AppendChar(char **buff, const char *buff_end, char c) {
33 if (*buff < buff_end) {
34 **buff = c;
35 (*buff)++;
37 return 1;
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;
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);
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);
81 return result;
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 */);
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);
97 static int AppendString(char **buff, const char *buff_end, int precision,
98 const char *s) {
99 if (s == 0)
100 s = "<null>";
101 int result = 0;
102 for (; *s; s++) {
103 if (precision >= 0 && result >= precision)
104 break;
105 result += AppendChar(buff, buff_end, *s);
107 return result;
110 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
111 int result = 0;
112 result += AppendString(buff, buff_end, -1, "0x");
113 result += AppendUnsigned(buff, buff_end, ptr_value, 16,
114 (SANITIZER_WORDSIZE == 64) ? 12 : 8, true);
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}; %p; %(\\.\\*)?s; %c\n";
122 RAW_CHECK(format);
123 RAW_CHECK(buff_length > 0);
124 const char *buff_end = &buff[buff_length - 1];
125 const char *cur = format;
126 int result = 0;
127 for (; *cur; cur++) {
128 if (*cur != '%') {
129 result += AppendChar(&buff, buff_end, *cur);
130 continue;
132 cur++;
133 bool have_width = (*cur >= '0' && *cur <= '9');
134 bool pad_with_zero = (*cur == '0');
135 int width = 0;
136 if (have_width) {
137 while (*cur >= '0' && *cur <= '9') {
138 width = width * 10 + *cur++ - '0';
141 bool have_precision = (cur[0] == '.' && cur[1] == '*');
142 int precision = -1;
143 if (have_precision) {
144 cur += 2;
145 precision = va_arg(args, int);
147 bool have_z = (*cur == 'z');
148 cur += have_z;
149 bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
150 cur += have_ll * 2;
151 s64 dval;
152 u64 uval;
153 bool have_flags = have_width | have_z | have_ll;
154 // Only %s supports precision for now
155 CHECK(!(precision >= 0 && *cur != 's'));
156 switch (*cur) {
157 case 'd': {
158 dval = have_ll ? va_arg(args, s64)
159 : have_z ? va_arg(args, sptr)
160 : va_arg(args, int);
161 result += AppendSignedDecimal(&buff, buff_end, dval, width,
162 pad_with_zero);
163 break;
165 case 'u':
166 case 'x': {
167 uval = have_ll ? va_arg(args, u64)
168 : have_z ? va_arg(args, uptr)
169 : va_arg(args, unsigned);
170 result += AppendUnsigned(&buff, buff_end, uval,
171 (*cur == 'u') ? 10 : 16, width, pad_with_zero);
172 break;
174 case 'p': {
175 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
176 result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
177 break;
179 case 's': {
180 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
181 result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
182 break;
184 case 'c': {
185 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
186 result += AppendChar(&buff, buff_end, va_arg(args, int));
187 break;
189 case '%' : {
190 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
191 result += AppendChar(&buff, buff_end, '%');
192 break;
194 default: {
195 RAW_CHECK_MSG(false, kPrintfFormatsHelp);
199 RAW_CHECK(buff <= buff_end);
200 AppendChar(&buff, buff_end + 1, '\0');
201 return result;
204 static void (*PrintfAndReportCallback)(const char *);
205 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
206 PrintfAndReportCallback = callback;
209 // Can be overriden in frontend.
210 #if SANITIZER_SUPPORTS_WEAK_HOOKS
211 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
212 void OnPrint(const char *str) {
213 (void)str;
215 #elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
216 void OnPrint(const char *str);
217 #else
218 void OnPrint(const char *str) {
219 (void)str;
221 #endif
223 static void CallPrintfAndReportCallback(const char *str) {
224 OnPrint(str);
225 if (PrintfAndReportCallback)
226 PrintfAndReportCallback(str);
229 static void SharedPrintfCode(bool append_pid, const char *format,
230 va_list args) {
231 va_list args2;
232 va_copy(args2, args);
233 const int kLen = 16 * 1024;
234 // |local_buffer| is small enough not to overflow the stack and/or violate
235 // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
236 // hand, the bigger the buffer is, the more the chance the error report will
237 // fit into it.
238 char local_buffer[400];
239 int needed_length;
240 char *buffer = local_buffer;
241 int buffer_size = ARRAY_SIZE(local_buffer);
242 // First try to print a message using a local buffer, and then fall back to
243 // mmaped buffer.
244 for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
245 if (use_mmap) {
246 va_end(args);
247 va_copy(args, args2);
248 buffer = (char*)MmapOrDie(kLen, "Report");
249 buffer_size = kLen;
251 needed_length = 0;
252 if (append_pid) {
253 int pid = internal_getpid();
254 needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
255 if (needed_length >= buffer_size) {
256 // The pid doesn't fit into the current buffer.
257 if (!use_mmap)
258 continue;
259 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
262 needed_length += VSNPrintf(buffer + needed_length,
263 buffer_size - needed_length, format, args);
264 if (needed_length >= buffer_size) {
265 // The message doesn't fit into the current buffer.
266 if (!use_mmap)
267 continue;
268 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
270 // If the message fit into the buffer, print it and exit.
271 break;
273 RawWrite(buffer);
274 AndroidLogWrite(buffer);
275 CallPrintfAndReportCallback(buffer);
276 // If we had mapped any memory, clean up.
277 if (buffer != local_buffer)
278 UnmapOrDie((void *)buffer, buffer_size);
279 va_end(args2);
282 FORMAT(1, 2)
283 void Printf(const char *format, ...) {
284 va_list args;
285 va_start(args, format);
286 SharedPrintfCode(false, format, args);
287 va_end(args);
290 // Like Printf, but prints the current PID before the output string.
291 FORMAT(1, 2)
292 void Report(const char *format, ...) {
293 va_list args;
294 va_start(args, format);
295 SharedPrintfCode(true, format, args);
296 va_end(args);
299 // Writes at most "length" symbols to "buffer" (including trailing '\0').
300 // Returns the number of symbols that should have been written to buffer
301 // (not including trailing '\0'). Thus, the string is truncated
302 // iff return value is not less than "length".
303 FORMAT(3, 4)
304 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
305 va_list args;
306 va_start(args, format);
307 int needed_length = VSNPrintf(buffer, length, format, args);
308 va_end(args);
309 return needed_length;
312 FORMAT(2, 3)
313 void InternalScopedString::append(const char *format, ...) {
314 CHECK_LT(length_, size());
315 va_list args;
316 va_start(args, format);
317 VSNPrintf(data() + length_, size() - length_, format, args);
318 va_end(args);
319 length_ += internal_strlen(data() + length_);
320 CHECK_LT(length_, size());
323 } // namespace __sanitizer