1 //===-- sanitizer_printf.cpp ----------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file is shared between AddressSanitizer and ThreadSanitizer.
11 // Internal printf function, used inside run-time libraries.
12 // We can't use libc printf because we intercept some of the functions used
14 //===----------------------------------------------------------------------===//
16 #include "sanitizer_common.h"
17 #include "sanitizer_flags.h"
18 #include "sanitizer_libc.h"
23 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 && \
25 # define va_copy(dst, src) ((dst) = (src))
28 namespace __sanitizer
{
30 static int AppendChar(char **buff
, const char *buff_end
, char c
) {
31 if (*buff
< buff_end
) {
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
, bool uppercase
) {
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
);
50 if (negative
&& minimal_num_length
)
52 if (negative
&& pad_with_zero
)
53 result
+= AppendChar(buff
, buff_end
, '-');
54 uptr num_buffer
[kMaxLen
];
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
;
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 digit
= (digit
< 10) ? '0' + digit
: (uppercase
? 'A' : 'a') + digit
- 10;
77 result
+= AppendChar(buff
, buff_end
, digit
);
82 static int AppendUnsigned(char **buff
, const char *buff_end
, u64 num
, u8 base
,
83 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 */, uppercase
);
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
,
94 false /* uppercase */);
98 // Use the fact that explicitly requesting 0 width (%0s) results in UB and
99 // interpret width == 0 as "no width requested":
100 // width == 0 - no width requested
101 // width < 0 - left-justify s within and pad it to -width chars, if necessary
102 // width > 0 - right-justify s, not implemented yet
103 static int AppendString(char **buff
, const char *buff_end
, int width
,
104 int max_chars
, const char *s
) {
109 if (max_chars
>= 0 && result
>= max_chars
)
111 result
+= AppendChar(buff
, buff_end
, *s
);
113 // Only the left justified strings are supported.
114 while (width
< -result
)
115 result
+= AppendChar(buff
, buff_end
, ' ');
119 static int AppendPointer(char **buff
, const char *buff_end
, u64 ptr_value
) {
121 result
+= AppendString(buff
, buff_end
, 0, -1, "0x");
122 result
+= AppendUnsigned(buff
, buff_end
, ptr_value
, 16,
123 SANITIZER_POINTER_FORMAT_LENGTH
,
124 true /* pad_with_zero */, false /* uppercase */);
128 int VSNPrintf(char *buff
, int buff_length
,
129 const char *format
, va_list args
) {
130 static const char *kPrintfFormatsHelp
=
131 "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x,X}; %p; "
132 "%[-]([0-9]*)?(\\.\\*)?s; %c\n";
134 RAW_CHECK(buff_length
> 0);
135 const char *buff_end
= &buff
[buff_length
- 1];
136 const char *cur
= format
;
138 for (; *cur
; cur
++) {
140 result
+= AppendChar(&buff
, buff_end
, *cur
);
144 bool left_justified
= *cur
== '-';
147 bool have_width
= (*cur
>= '0' && *cur
<= '9');
148 bool pad_with_zero
= (*cur
== '0');
151 while (*cur
>= '0' && *cur
<= '9') {
152 width
= width
* 10 + *cur
++ - '0';
155 bool have_precision
= (cur
[0] == '.' && cur
[1] == '*');
157 if (have_precision
) {
159 precision
= va_arg(args
, int);
161 bool have_z
= (*cur
== 'z');
163 bool have_ll
= !have_z
&& (cur
[0] == 'l' && cur
[1] == 'l');
167 const bool have_length
= have_z
|| have_ll
;
168 const bool have_flags
= have_width
|| have_length
;
169 // At the moment only %s supports precision and left-justification.
170 CHECK(!((precision
>= 0 || left_justified
) && *cur
!= 's'));
173 dval
= have_ll
? va_arg(args
, s64
)
174 : have_z
? va_arg(args
, sptr
)
176 result
+= AppendSignedDecimal(&buff
, buff_end
, dval
, width
,
183 uval
= have_ll
? va_arg(args
, u64
)
184 : have_z
? va_arg(args
, uptr
)
185 : va_arg(args
, unsigned);
186 bool uppercase
= (*cur
== 'X');
187 result
+= AppendUnsigned(&buff
, buff_end
, uval
, (*cur
== 'u') ? 10 : 16,
188 width
, pad_with_zero
, uppercase
);
192 RAW_CHECK_MSG(!have_flags
, kPrintfFormatsHelp
);
193 result
+= AppendPointer(&buff
, buff_end
, va_arg(args
, uptr
));
197 RAW_CHECK_MSG(!have_length
, kPrintfFormatsHelp
);
198 // Only left-justified width is supported.
199 CHECK(!have_width
|| left_justified
);
200 result
+= AppendString(&buff
, buff_end
, left_justified
? -width
: width
,
201 precision
, va_arg(args
, char*));
205 RAW_CHECK_MSG(!have_flags
, kPrintfFormatsHelp
);
206 result
+= AppendChar(&buff
, buff_end
, va_arg(args
, int));
210 RAW_CHECK_MSG(!have_flags
, kPrintfFormatsHelp
);
211 result
+= AppendChar(&buff
, buff_end
, '%');
215 RAW_CHECK_MSG(false, kPrintfFormatsHelp
);
219 RAW_CHECK(buff
<= buff_end
);
220 AppendChar(&buff
, buff_end
+ 1, '\0');
224 static void (*PrintfAndReportCallback
)(const char *);
225 void SetPrintfAndReportCallback(void (*callback
)(const char *)) {
226 PrintfAndReportCallback
= callback
;
229 // Can be overriden in frontend.
230 #if SANITIZER_GO && defined(TSAN_EXTERNAL_HOOKS)
231 // Implementation must be defined in frontend.
232 extern "C" void __sanitizer_on_print(const char *str
);
234 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_on_print
, const char *str
) {
239 static void CallPrintfAndReportCallback(const char *str
) {
240 __sanitizer_on_print(str
);
241 if (PrintfAndReportCallback
)
242 PrintfAndReportCallback(str
);
245 static void NOINLINE
SharedPrintfCodeNoBuffer(bool append_pid
,
251 va_copy(args2
, args
);
252 const int kLen
= 16 * 1024;
254 char *buffer
= local_buffer
;
255 // First try to print a message using a local buffer, and then fall back to
257 for (int use_mmap
= 0; use_mmap
< 2; use_mmap
++) {
260 va_copy(args
, args2
);
261 buffer
= (char*)MmapOrDie(kLen
, "Report");
265 // Check that data fits into the current buffer.
266 # define CHECK_NEEDED_LENGTH \
267 if (needed_length >= buffer_size) { \
268 if (!use_mmap) continue; \
269 RAW_CHECK_MSG(needed_length < kLen, \
270 "Buffer in Report is too short!\n"); \
272 // Fuchsia's logging infrastructure always keeps track of the logging
273 // process, thread, and timestamp, so never prepend such information.
274 if (!SANITIZER_FUCHSIA
&& append_pid
) {
275 int pid
= internal_getpid();
276 const char *exe_name
= GetProcessName();
277 if (common_flags()->log_exe_name
&& exe_name
) {
278 needed_length
+= internal_snprintf(buffer
, buffer_size
,
282 needed_length
+= internal_snprintf(
283 buffer
+ needed_length
, buffer_size
- needed_length
, "==%d==", pid
);
286 needed_length
+= VSNPrintf(buffer
+ needed_length
,
287 buffer_size
- needed_length
, format
, args
);
289 // If the message fit into the buffer, print it and exit.
291 # undef CHECK_NEEDED_LENGTH
295 // Remove color sequences from the message.
296 RemoveANSIEscapeSequencesFromString(buffer
);
297 CallPrintfAndReportCallback(buffer
);
298 LogMessageOnPrintf(buffer
);
300 // If we had mapped any memory, clean up.
301 if (buffer
!= local_buffer
)
302 UnmapOrDie((void *)buffer
, buffer_size
);
306 static void NOINLINE
SharedPrintfCode(bool append_pid
, const char *format
,
308 // |local_buffer| is small enough not to overflow the stack and/or violate
309 // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
310 // hand, the bigger the buffer is, the more the chance the error report will
312 char local_buffer
[400];
313 SharedPrintfCodeNoBuffer(append_pid
, local_buffer
, ARRAY_SIZE(local_buffer
),
318 void Printf(const char *format
, ...) {
320 va_start(args
, format
);
321 SharedPrintfCode(false, format
, args
);
325 // Like Printf, but prints the current PID before the output string.
327 void Report(const char *format
, ...) {
329 va_start(args
, format
);
330 SharedPrintfCode(true, format
, args
);
334 // Writes at most "length" symbols to "buffer" (including trailing '\0').
335 // Returns the number of symbols that should have been written to buffer
336 // (not including trailing '\0'). Thus, the string is truncated
337 // iff return value is not less than "length".
339 int internal_snprintf(char *buffer
, uptr length
, const char *format
, ...) {
341 va_start(args
, format
);
342 int needed_length
= VSNPrintf(buffer
, length
, format
, args
);
344 return needed_length
;
348 void InternalScopedString::append(const char *format
, ...) {
349 CHECK_LT(length_
, size());
351 va_start(args
, format
);
352 VSNPrintf(data() + length_
, size() - length_
, format
, args
);
354 length_
+= internal_strlen(data() + length_
);
355 CHECK_LT(length_
, size());
358 } // namespace __sanitizer