1 //===-- sanitizer_printf.cc -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer.
12 // Internal printf function, used inside run-time libraries.
13 // We can't use libc printf because we intercept some of the functions used
15 //===----------------------------------------------------------------------===//
18 #include "sanitizer_common.h"
19 #include "sanitizer_flags.h"
20 #include "sanitizer_libc.h"
25 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 && \
27 # define va_copy(dst, src) ((dst) = (src))
30 namespace __sanitizer {
32 StaticSpinMutex CommonSanitizerReportMutex;
34 static int AppendChar(char **buff, const char *buff_end, char c) {
35 if (*buff < buff_end) {
42 // Appends number in a given base to buffer. If its length is less than
43 // |minimal_num_length|, it is padded with leading zeroes or spaces, depending
44 // on the value of |pad_with_zero|.
45 static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
46 u8 base, u8 minimal_num_length, bool pad_with_zero,
48 uptr const kMaxLen = 30;
49 RAW_CHECK(base == 10 || base == 16);
50 RAW_CHECK(base == 10 || !negative);
51 RAW_CHECK(absolute_value || !negative);
52 RAW_CHECK(minimal_num_length < kMaxLen);
54 if (negative && minimal_num_length)
56 if (negative && pad_with_zero)
57 result += AppendChar(buff, buff_end, '-');
58 uptr num_buffer[kMaxLen];
61 RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
62 num_buffer[pos++] = absolute_value % base;
63 absolute_value /= base;
64 } while (absolute_value > 0);
65 if (pos < minimal_num_length) {
66 // Make sure compiler doesn't insert call to memset here.
67 internal_memset(&num_buffer[pos], 0,
68 sizeof(num_buffer[0]) * (minimal_num_length - pos));
69 pos = minimal_num_length;
73 for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
74 char c = (pad_with_zero || pos == 0) ? '0' : ' ';
75 result += AppendChar(buff, buff_end, c);
77 if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
78 for (; pos >= 0; pos--) {
79 char digit = static_cast<char>(num_buffer[pos]);
80 result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
86 static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
87 u8 minimal_num_length, bool pad_with_zero) {
88 return AppendNumber(buff, buff_end, num, base, minimal_num_length,
89 pad_with_zero, false /* negative */);
92 static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
93 u8 minimal_num_length, bool pad_with_zero) {
94 bool negative = (num < 0);
95 return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
96 minimal_num_length, pad_with_zero, negative);
99 static int AppendString(char **buff, const char *buff_end, int precision,
105 if (precision >= 0 && result >= precision)
107 result += AppendChar(buff, buff_end, *s);
112 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
114 result += AppendString(buff, buff_end, -1, "0x");
115 result += AppendUnsigned(buff, buff_end, ptr_value, 16,
116 SANITIZER_POINTER_FORMAT_LENGTH, true);
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}; %p; %(\\.\\*)?s; %c\n";
125 RAW_CHECK(buff_length > 0);
126 const char *buff_end = &buff[buff_length - 1];
127 const char *cur = format;
129 for (; *cur; cur++) {
131 result += AppendChar(&buff, buff_end, *cur);
135 bool have_width = (*cur >= '0' && *cur <= '9');
136 bool pad_with_zero = (*cur == '0');
139 while (*cur >= '0' && *cur <= '9') {
140 width = width * 10 + *cur++ - '0';
143 bool have_precision = (cur[0] == '.' && cur[1] == '*');
145 if (have_precision) {
147 precision = va_arg(args, int);
149 bool have_z = (*cur == 'z');
151 bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
155 bool have_flags = have_width | have_z | have_ll;
156 // Only %s supports precision for now
157 CHECK(!(precision >= 0 && *cur != 's'));
160 dval = have_ll ? va_arg(args, s64)
161 : have_z ? va_arg(args, sptr)
163 result += AppendSignedDecimal(&buff, buff_end, dval, width,
169 uval = have_ll ? va_arg(args, u64)
170 : have_z ? va_arg(args, uptr)
171 : va_arg(args, unsigned);
172 result += AppendUnsigned(&buff, buff_end, uval,
173 (*cur == 'u') ? 10 : 16, width, pad_with_zero);
177 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
178 result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
182 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
183 result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
187 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
188 result += AppendChar(&buff, buff_end, va_arg(args, int));
192 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
193 result += AppendChar(&buff, buff_end, '%');
197 RAW_CHECK_MSG(false, kPrintfFormatsHelp);
201 RAW_CHECK(buff <= buff_end);
202 AppendChar(&buff, buff_end + 1, '\0');
206 static void (*PrintfAndReportCallback)(const char *);
207 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
208 PrintfAndReportCallback = callback;
211 // Can be overriden in frontend.
212 #if SANITIZER_SUPPORTS_WEAK_HOOKS
213 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
214 void OnPrint(const char *str) {
217 #elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
218 void OnPrint(const char *str);
220 void OnPrint(const char *str) {
225 static void CallPrintfAndReportCallback(const char *str) {
227 if (PrintfAndReportCallback)
228 PrintfAndReportCallback(str);
231 static void SharedPrintfCode(bool append_pid, const char *format,
234 va_copy(args2, args);
235 const int kLen = 16 * 1024;
236 // |local_buffer| is small enough not to overflow the stack and/or violate
237 // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
238 // hand, the bigger the buffer is, the more the chance the error report will
240 char local_buffer[400];
242 char *buffer = local_buffer;
243 int buffer_size = ARRAY_SIZE(local_buffer);
244 // First try to print a message using a local buffer, and then fall back to
246 for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
249 va_copy(args, args2);
250 buffer = (char*)MmapOrDie(kLen, "Report");
255 int pid = internal_getpid();
256 needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
257 if (needed_length >= buffer_size) {
258 // The pid doesn't fit into the current buffer.
261 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
264 needed_length += VSNPrintf(buffer + needed_length,
265 buffer_size - needed_length, format, args);
266 if (needed_length >= buffer_size) {
267 // The message doesn't fit into the current buffer.
270 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
272 // If the message fit into the buffer, print it and exit.
276 AndroidLogWrite(buffer);
277 CallPrintfAndReportCallback(buffer);
278 // If we had mapped any memory, clean up.
279 if (buffer != local_buffer)
280 UnmapOrDie((void *)buffer, buffer_size);
285 void Printf(const char *format, ...) {
287 va_start(args, format);
288 SharedPrintfCode(false, format, args);
292 // Like Printf, but prints the current PID before the output string.
294 void Report(const char *format, ...) {
296 va_start(args, format);
297 SharedPrintfCode(true, format, args);
301 // Writes at most "length" symbols to "buffer" (including trailing '\0').
302 // Returns the number of symbols that should have been written to buffer
303 // (not including trailing '\0'). Thus, the string is truncated
304 // iff return value is not less than "length".
306 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
308 va_start(args, format);
309 int needed_length = VSNPrintf(buffer, length, format, args);
311 return needed_length;
315 void InternalScopedString::append(const char *format, ...) {
316 CHECK_LT(length_, size());
318 va_start(args, format);
319 VSNPrintf(data() + length_, size() - length_, format, args);
321 length_ += internal_strlen(data() + length_);
322 CHECK_LT(length_, size());
325 } // namespace __sanitizer