2014-01-30 Alangi Derick <alangiderick@gmail.com>
[official-gcc.git] / libsanitizer / sanitizer_common / sanitizer_printf.cc
blob08951c7e24733c8c0b0bcd849a128bf633eddc8f
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_libc.h"
19 #include <stdio.h>
20 #include <stdarg.h>
22 #if SANITIZER_WINDOWS && !defined(va_copy)
23 # define va_copy(dst, src) ((dst) = (src))
24 #endif
26 namespace __sanitizer {
28 StaticSpinMutex CommonSanitizerReportMutex;
30 static int AppendChar(char **buff, const char *buff_end, char c) {
31 if (*buff < buff_end) {
32 **buff = c;
33 (*buff)++;
35 return 1;
38 // Appends number in a given base to buffer. If its length is less than
39 // |minimal_num_length|, it is padded with leading zeroes or spaces, depending
40 // on the value of |pad_with_zero|.
41 static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
42 u8 base, u8 minimal_num_length, bool pad_with_zero,
43 bool negative) {
44 uptr const kMaxLen = 30;
45 RAW_CHECK(base == 10 || base == 16);
46 RAW_CHECK(base == 10 || !negative);
47 RAW_CHECK(absolute_value || !negative);
48 RAW_CHECK(minimal_num_length < kMaxLen);
49 int result = 0;
50 if (negative && minimal_num_length)
51 --minimal_num_length;
52 if (negative && pad_with_zero)
53 result += AppendChar(buff, buff_end, '-');
54 uptr num_buffer[kMaxLen];
55 int pos = 0;
56 do {
57 RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
58 num_buffer[pos++] = absolute_value % base;
59 absolute_value /= base;
60 } while (absolute_value > 0);
61 if (pos < minimal_num_length) {
62 // Make sure compiler doesn't insert call to memset here.
63 internal_memset(&num_buffer[pos], 0,
64 sizeof(num_buffer[0]) * (minimal_num_length - pos));
65 pos = minimal_num_length;
67 RAW_CHECK(pos > 0);
68 pos--;
69 for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
70 char c = (pad_with_zero || pos == 0) ? '0' : ' ';
71 result += AppendChar(buff, buff_end, c);
73 if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
74 for (; pos >= 0; pos--) {
75 char digit = static_cast<char>(num_buffer[pos]);
76 result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
77 : 'a' + digit - 10);
79 return result;
82 static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
83 u8 minimal_num_length, bool pad_with_zero) {
84 return AppendNumber(buff, buff_end, num, base, minimal_num_length,
85 pad_with_zero, false /* negative */);
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);
95 static int AppendString(char **buff, const char *buff_end, const char *s) {
96 if (s == 0)
97 s = "<null>";
98 int result = 0;
99 for (; *s; s++) {
100 result += AppendChar(buff, buff_end, *s);
102 return result;
105 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
106 int result = 0;
107 result += AppendString(buff, buff_end, "0x");
108 result += AppendUnsigned(buff, buff_end, ptr_value, 16,
109 (SANITIZER_WORDSIZE == 64) ? 12 : 8, true);
110 return result;
113 int VSNPrintf(char *buff, int buff_length,
114 const char *format, va_list args) {
115 static const char *kPrintfFormatsHelp =
116 "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %s; %c\n";
117 RAW_CHECK(format);
118 RAW_CHECK(buff_length > 0);
119 const char *buff_end = &buff[buff_length - 1];
120 const char *cur = format;
121 int result = 0;
122 for (; *cur; cur++) {
123 if (*cur != '%') {
124 result += AppendChar(&buff, buff_end, *cur);
125 continue;
127 cur++;
128 bool have_width = (*cur >= '0' && *cur <= '9');
129 bool pad_with_zero = (*cur == '0');
130 int width = 0;
131 if (have_width) {
132 while (*cur >= '0' && *cur <= '9') {
133 width = width * 10 + *cur++ - '0';
136 bool have_z = (*cur == 'z');
137 cur += have_z;
138 bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
139 cur += have_ll * 2;
140 s64 dval;
141 u64 uval;
142 bool have_flags = have_width | have_z | have_ll;
143 switch (*cur) {
144 case 'd': {
145 dval = have_ll ? va_arg(args, s64)
146 : have_z ? va_arg(args, sptr)
147 : va_arg(args, int);
148 result += AppendSignedDecimal(&buff, buff_end, dval, width,
149 pad_with_zero);
150 break;
152 case 'u':
153 case 'x': {
154 uval = have_ll ? va_arg(args, u64)
155 : have_z ? va_arg(args, uptr)
156 : va_arg(args, unsigned);
157 result += AppendUnsigned(&buff, buff_end, uval,
158 (*cur == 'u') ? 10 : 16, width, pad_with_zero);
159 break;
161 case 'p': {
162 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
163 result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
164 break;
166 case 's': {
167 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
168 result += AppendString(&buff, buff_end, va_arg(args, char*));
169 break;
171 case 'c': {
172 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
173 result += AppendChar(&buff, buff_end, va_arg(args, int));
174 break;
176 case '%' : {
177 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
178 result += AppendChar(&buff, buff_end, '%');
179 break;
181 default: {
182 RAW_CHECK_MSG(false, kPrintfFormatsHelp);
186 RAW_CHECK(buff <= buff_end);
187 AppendChar(&buff, buff_end + 1, '\0');
188 return result;
191 static void (*PrintfAndReportCallback)(const char *);
192 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
193 PrintfAndReportCallback = callback;
196 // Can be overriden in frontend.
197 #if SANITIZER_SUPPORTS_WEAK_HOOKS
198 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
199 void OnPrint(const char *str) {
200 (void)str;
202 #elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
203 void OnPrint(const char *str);
204 #else
205 void OnPrint(const char *str) {
206 (void)str;
208 #endif
210 static void CallPrintfAndReportCallback(const char *str) {
211 OnPrint(str);
212 if (PrintfAndReportCallback)
213 PrintfAndReportCallback(str);
216 static void SharedPrintfCode(bool append_pid, const char *format,
217 va_list args) {
218 va_list args2;
219 va_copy(args2, args);
220 const int kLen = 16 * 1024;
221 // |local_buffer| is small enough not to overflow the stack and/or violate
222 // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
223 // hand, the bigger the buffer is, the more the chance the error report will
224 // fit into it.
225 char local_buffer[400];
226 int needed_length;
227 char *buffer = local_buffer;
228 int buffer_size = ARRAY_SIZE(local_buffer);
229 // First try to print a message using a local buffer, and then fall back to
230 // mmaped buffer.
231 for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
232 if (use_mmap) {
233 va_end(args);
234 va_copy(args, args2);
235 buffer = (char*)MmapOrDie(kLen, "Report");
236 buffer_size = kLen;
238 needed_length = 0;
239 if (append_pid) {
240 int pid = internal_getpid();
241 needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
242 if (needed_length >= buffer_size) {
243 // The pid doesn't fit into the current buffer.
244 if (!use_mmap)
245 continue;
246 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
249 needed_length += VSNPrintf(buffer + needed_length,
250 buffer_size - needed_length, format, args);
251 if (needed_length >= buffer_size) {
252 // The message doesn't fit into the current buffer.
253 if (!use_mmap)
254 continue;
255 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
257 // If the message fit into the buffer, print it and exit.
258 break;
260 RawWrite(buffer);
261 CallPrintfAndReportCallback(buffer);
262 // If we had mapped any memory, clean up.
263 if (buffer != local_buffer)
264 UnmapOrDie((void *)buffer, buffer_size);
265 va_end(args2);
268 void Printf(const char *format, ...) {
269 va_list args;
270 va_start(args, format);
271 SharedPrintfCode(false, format, args);
272 va_end(args);
275 // Like Printf, but prints the current PID before the output string.
276 void Report(const char *format, ...) {
277 va_list args;
278 va_start(args, format);
279 SharedPrintfCode(true, format, args);
280 va_end(args);
283 // Writes at most "length" symbols to "buffer" (including trailing '\0').
284 // Returns the number of symbols that should have been written to buffer
285 // (not including trailing '\0'). Thus, the string is truncated
286 // iff return value is not less than "length".
287 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
288 va_list args;
289 va_start(args, format);
290 int needed_length = VSNPrintf(buffer, length, format, args);
291 va_end(args);
292 return needed_length;
295 void InternalScopedString::append(const char *format, ...) {
296 CHECK_LT(length_, size());
297 va_list args;
298 va_start(args, format);
299 VSNPrintf(data() + length_, size() - length_, format, args);
300 va_end(args);
301 length_ += internal_strlen(data() + length_);
304 } // namespace __sanitizer