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 //===----------------------------------------------------------------------===//
17 #include "sanitizer_common.h"
18 #include "sanitizer_flags.h"
19 #include "sanitizer_libc.h"
24 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 && \
26 # define va_copy(dst, src) ((dst) = (src))
29 namespace __sanitizer {
31 StaticSpinMutex CommonSanitizerReportMutex;
33 static int AppendChar(char **buff, const char *buff_end, char c) {
34 if (*buff < buff_end) {
41 // Appends number in a given base to buffer. If its length is less than
42 // |minimal_num_length|, it is padded with leading zeroes or spaces, depending
43 // on the value of |pad_with_zero|.
44 static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
45 u8 base, u8 minimal_num_length, bool pad_with_zero,
46 bool negative, bool uppercase) {
47 uptr const kMaxLen = 30;
48 RAW_CHECK(base == 10 || base == 16);
49 RAW_CHECK(base == 10 || !negative);
50 RAW_CHECK(absolute_value || !negative);
51 RAW_CHECK(minimal_num_length < kMaxLen);
53 if (negative && minimal_num_length)
55 if (negative && pad_with_zero)
56 result += AppendChar(buff, buff_end, '-');
57 uptr num_buffer[kMaxLen];
60 RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
61 num_buffer[pos++] = absolute_value % base;
62 absolute_value /= base;
63 } while (absolute_value > 0);
64 if (pos < minimal_num_length) {
65 // Make sure compiler doesn't insert call to memset here.
66 internal_memset(&num_buffer[pos], 0,
67 sizeof(num_buffer[0]) * (minimal_num_length - pos));
68 pos = minimal_num_length;
72 for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
73 char c = (pad_with_zero || pos == 0) ? '0' : ' ';
74 result += AppendChar(buff, buff_end, c);
76 if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
77 for (; pos >= 0; pos--) {
78 char digit = static_cast<char>(num_buffer[pos]);
79 digit = (digit < 10) ? '0' + digit : (uppercase ? 'A' : 'a') + digit - 10;
80 result += AppendChar(buff, buff_end, digit);
85 static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
86 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 */, uppercase);
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,
97 false /* uppercase */);
100 static int AppendString(char **buff, const char *buff_end, int precision,
106 if (precision >= 0 && result >= precision)
108 result += AppendChar(buff, buff_end, *s);
113 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
115 result += AppendString(buff, buff_end, -1, "0x");
116 result += AppendUnsigned(buff, buff_end, ptr_value, 16,
117 SANITIZER_POINTER_FORMAT_LENGTH,
118 true /* pad_with_zero */, false /* uppercase */);
122 int VSNPrintf(char *buff, int buff_length,
123 const char *format, va_list args) {
124 static const char *kPrintfFormatsHelp =
125 "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x,X}; %p; %(\\.\\*)?s; "
128 RAW_CHECK(buff_length > 0);
129 const char *buff_end = &buff[buff_length - 1];
130 const char *cur = format;
132 for (; *cur; cur++) {
134 result += AppendChar(&buff, buff_end, *cur);
138 bool have_width = (*cur >= '0' && *cur <= '9');
139 bool pad_with_zero = (*cur == '0');
142 while (*cur >= '0' && *cur <= '9') {
143 width = width * 10 + *cur++ - '0';
146 bool have_precision = (cur[0] == '.' && cur[1] == '*');
148 if (have_precision) {
150 precision = va_arg(args, int);
152 bool have_z = (*cur == 'z');
154 bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
158 bool have_flags = have_width | have_z | have_ll;
159 // Only %s supports precision for now
160 CHECK(!(precision >= 0 && *cur != 's'));
163 dval = have_ll ? va_arg(args, s64)
164 : have_z ? va_arg(args, sptr)
166 result += AppendSignedDecimal(&buff, buff_end, dval, width,
173 uval = have_ll ? va_arg(args, u64)
174 : have_z ? va_arg(args, uptr)
175 : va_arg(args, unsigned);
176 bool uppercase = (*cur == 'X');
177 result += AppendUnsigned(&buff, buff_end, uval, (*cur == 'u') ? 10 : 16,
178 width, pad_with_zero, uppercase);
182 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
183 result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
187 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
188 result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
192 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
193 result += AppendChar(&buff, buff_end, va_arg(args, int));
197 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
198 result += AppendChar(&buff, buff_end, '%');
202 RAW_CHECK_MSG(false, kPrintfFormatsHelp);
206 RAW_CHECK(buff <= buff_end);
207 AppendChar(&buff, buff_end + 1, '\0');
211 static void (*PrintfAndReportCallback)(const char *);
212 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
213 PrintfAndReportCallback = callback;
216 // Can be overriden in frontend.
217 #if SANITIZER_GO && defined(TSAN_EXTERNAL_HOOKS)
218 // Implementation must be defined in frontend.
219 extern "C" void OnPrint(const char *str);
221 SANITIZER_INTERFACE_WEAK_DEF(void, OnPrint, const char *str) {
226 static void CallPrintfAndReportCallback(const char *str) {
228 if (PrintfAndReportCallback)
229 PrintfAndReportCallback(str);
232 static void SharedPrintfCode(bool append_pid, const char *format,
235 va_copy(args2, args);
236 const int kLen = 16 * 1024;
237 // |local_buffer| is small enough not to overflow the stack and/or violate
238 // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
239 // hand, the bigger the buffer is, the more the chance the error report will
241 char local_buffer[400];
243 char *buffer = local_buffer;
244 int buffer_size = ARRAY_SIZE(local_buffer);
245 // First try to print a message using a local buffer, and then fall back to
247 for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
250 va_copy(args, args2);
251 buffer = (char*)MmapOrDie(kLen, "Report");
255 // Check that data fits into the current buffer.
256 # define CHECK_NEEDED_LENGTH \
257 if (needed_length >= buffer_size) { \
258 if (!use_mmap) continue; \
259 RAW_CHECK_MSG(needed_length < kLen, \
260 "Buffer in Report is too short!\n"); \
263 int pid = internal_getpid();
264 const char *exe_name = GetProcessName();
265 if (common_flags()->log_exe_name && exe_name) {
266 needed_length += internal_snprintf(buffer, buffer_size,
270 needed_length += internal_snprintf(buffer + needed_length,
271 buffer_size - needed_length,
275 needed_length += VSNPrintf(buffer + needed_length,
276 buffer_size - needed_length, format, args);
278 // If the message fit into the buffer, print it and exit.
280 # undef CHECK_NEEDED_LENGTH
284 // Remove color sequences from the message.
285 RemoveANSIEscapeSequencesFromString(buffer);
286 CallPrintfAndReportCallback(buffer);
287 LogMessageOnPrintf(buffer);
289 // If we had mapped any memory, clean up.
290 if (buffer != local_buffer)
291 UnmapOrDie((void *)buffer, buffer_size);
296 void Printf(const char *format, ...) {
298 va_start(args, format);
299 SharedPrintfCode(false, format, args);
303 // Like Printf, but prints the current PID before the output string.
305 void Report(const char *format, ...) {
307 va_start(args, format);
308 SharedPrintfCode(true, format, args);
312 // Writes at most "length" symbols to "buffer" (including trailing '\0').
313 // Returns the number of symbols that should have been written to buffer
314 // (not including trailing '\0'). Thus, the string is truncated
315 // iff return value is not less than "length".
317 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
319 va_start(args, format);
320 int needed_length = VSNPrintf(buffer, length, format, args);
322 return needed_length;
326 void InternalScopedString::append(const char *format, ...) {
327 CHECK_LT(length_, size());
329 va_start(args, format);
330 VSNPrintf(data() + length_, size() - length_, format, args);
332 length_ += internal_strlen(data() + length_);
333 CHECK_LT(length_, size());
336 } // namespace __sanitizer