]> git.ipfire.org Git - thirdparty/gcc.git/blob - libsanitizer/sanitizer_common/sanitizer_printf.cc
5da8c5f189d2b2d48f0ccd0ebc0957d27782d0b6
[thirdparty/gcc.git] / libsanitizer / sanitizer_common / sanitizer_printf.cc
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 //===----------------------------------------------------------------------===//
14
15 #include "sanitizer_common.h"
16 #include "sanitizer_flags.h"
17 #include "sanitizer_libc.h"
18
19 #include <stdio.h>
20 #include <stdarg.h>
21
22 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 && \
23 !defined(va_copy)
24 # define va_copy(dst, src) ((dst) = (src))
25 #endif
26
27 namespace __sanitizer {
28
29 static int AppendChar(char **buff, const char *buff_end, char c) {
30 if (*buff < buff_end) {
31 **buff = c;
32 (*buff)++;
33 }
34 return 1;
35 }
36
37 // Appends number in a given base to buffer. If its length is less than
38 // |minimal_num_length|, it is padded with leading zeroes or spaces, depending
39 // on the value of |pad_with_zero|.
40 static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
41 u8 base, u8 minimal_num_length, bool pad_with_zero,
42 bool negative, bool uppercase) {
43 uptr const kMaxLen = 30;
44 RAW_CHECK(base == 10 || base == 16);
45 RAW_CHECK(base == 10 || !negative);
46 RAW_CHECK(absolute_value || !negative);
47 RAW_CHECK(minimal_num_length < kMaxLen);
48 int result = 0;
49 if (negative && minimal_num_length)
50 --minimal_num_length;
51 if (negative && pad_with_zero)
52 result += AppendChar(buff, buff_end, '-');
53 uptr num_buffer[kMaxLen];
54 int pos = 0;
55 do {
56 RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
57 num_buffer[pos++] = absolute_value % base;
58 absolute_value /= base;
59 } while (absolute_value > 0);
60 if (pos < minimal_num_length) {
61 // Make sure compiler doesn't insert call to memset here.
62 internal_memset(&num_buffer[pos], 0,
63 sizeof(num_buffer[0]) * (minimal_num_length - pos));
64 pos = minimal_num_length;
65 }
66 RAW_CHECK(pos > 0);
67 pos--;
68 for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
69 char c = (pad_with_zero || pos == 0) ? '0' : ' ';
70 result += AppendChar(buff, buff_end, c);
71 }
72 if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
73 for (; pos >= 0; pos--) {
74 char digit = static_cast<char>(num_buffer[pos]);
75 digit = (digit < 10) ? '0' + digit : (uppercase ? 'A' : 'a') + digit - 10;
76 result += AppendChar(buff, buff_end, digit);
77 }
78 return result;
79 }
80
81 static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
82 u8 minimal_num_length, bool pad_with_zero,
83 bool uppercase) {
84 return AppendNumber(buff, buff_end, num, base, minimal_num_length,
85 pad_with_zero, false /* negative */, uppercase);
86 }
87
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,
93 false /* uppercase */);
94 }
95
96
97 // Use the fact that explicitly requesting 0 width (%0s) results in UB and
98 // interpret width == 0 as "no width requested":
99 // width == 0 - no width requested
100 // width < 0 - left-justify s within and pad it to -width chars, if necessary
101 // width > 0 - right-justify s, not implemented yet
102 static int AppendString(char **buff, const char *buff_end, int width,
103 int max_chars, const char *s) {
104 if (!s)
105 s = "<null>";
106 int result = 0;
107 for (; *s; s++) {
108 if (max_chars >= 0 && result >= max_chars)
109 break;
110 result += AppendChar(buff, buff_end, *s);
111 }
112 // Only the left justified strings are supported.
113 while (width < -result)
114 result += AppendChar(buff, buff_end, ' ');
115 return result;
116 }
117
118 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
119 int result = 0;
120 result += AppendString(buff, buff_end, 0, -1, "0x");
121 result += AppendUnsigned(buff, buff_end, ptr_value, 16,
122 SANITIZER_POINTER_FORMAT_LENGTH,
123 true /* pad_with_zero */, false /* uppercase */);
124 return result;
125 }
126
127 int VSNPrintf(char *buff, int buff_length,
128 const char *format, va_list args) {
129 static const char *kPrintfFormatsHelp =
130 "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x,X}; %p; "
131 "%[-]([0-9]*)?(\\.\\*)?s; %c\n";
132 RAW_CHECK(format);
133 RAW_CHECK(buff_length > 0);
134 const char *buff_end = &buff[buff_length - 1];
135 const char *cur = format;
136 int result = 0;
137 for (; *cur; cur++) {
138 if (*cur != '%') {
139 result += AppendChar(&buff, buff_end, *cur);
140 continue;
141 }
142 cur++;
143 bool left_justified = *cur == '-';
144 if (left_justified)
145 cur++;
146 bool have_width = (*cur >= '0' && *cur <= '9');
147 bool pad_with_zero = (*cur == '0');
148 int width = 0;
149 if (have_width) {
150 while (*cur >= '0' && *cur <= '9') {
151 width = width * 10 + *cur++ - '0';
152 }
153 }
154 bool have_precision = (cur[0] == '.' && cur[1] == '*');
155 int precision = -1;
156 if (have_precision) {
157 cur += 2;
158 precision = va_arg(args, int);
159 }
160 bool have_z = (*cur == 'z');
161 cur += have_z;
162 bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
163 cur += have_ll * 2;
164 s64 dval;
165 u64 uval;
166 const bool have_length = have_z || have_ll;
167 const bool have_flags = have_width || have_length;
168 // At the moment only %s supports precision and left-justification.
169 CHECK(!((precision >= 0 || left_justified) && *cur != 's'));
170 switch (*cur) {
171 case 'd': {
172 dval = have_ll ? va_arg(args, s64)
173 : have_z ? va_arg(args, sptr)
174 : va_arg(args, int);
175 result += AppendSignedDecimal(&buff, buff_end, dval, width,
176 pad_with_zero);
177 break;
178 }
179 case 'u':
180 case 'x':
181 case 'X': {
182 uval = have_ll ? va_arg(args, u64)
183 : have_z ? va_arg(args, uptr)
184 : va_arg(args, unsigned);
185 bool uppercase = (*cur == 'X');
186 result += AppendUnsigned(&buff, buff_end, uval, (*cur == 'u') ? 10 : 16,
187 width, pad_with_zero, uppercase);
188 break;
189 }
190 case 'p': {
191 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
192 result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
193 break;
194 }
195 case 's': {
196 RAW_CHECK_MSG(!have_length, kPrintfFormatsHelp);
197 // Only left-justified width is supported.
198 CHECK(!have_width || left_justified);
199 result += AppendString(&buff, buff_end, left_justified ? -width : width,
200 precision, va_arg(args, char*));
201 break;
202 }
203 case 'c': {
204 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
205 result += AppendChar(&buff, buff_end, va_arg(args, int));
206 break;
207 }
208 case '%' : {
209 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
210 result += AppendChar(&buff, buff_end, '%');
211 break;
212 }
213 default: {
214 RAW_CHECK_MSG(false, kPrintfFormatsHelp);
215 }
216 }
217 }
218 RAW_CHECK(buff <= buff_end);
219 AppendChar(&buff, buff_end + 1, '\0');
220 return result;
221 }
222
223 static void (*PrintfAndReportCallback)(const char *);
224 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
225 PrintfAndReportCallback = callback;
226 }
227
228 // Can be overriden in frontend.
229 #if SANITIZER_GO && defined(TSAN_EXTERNAL_HOOKS)
230 // Implementation must be defined in frontend.
231 extern "C" void OnPrint(const char *str);
232 #else
233 SANITIZER_INTERFACE_WEAK_DEF(void, OnPrint, const char *str) {
234 (void)str;
235 }
236 #endif
237
238 static void CallPrintfAndReportCallback(const char *str) {
239 OnPrint(str);
240 if (PrintfAndReportCallback)
241 PrintfAndReportCallback(str);
242 }
243
244 static void NOINLINE SharedPrintfCodeNoBuffer(bool append_pid,
245 char *local_buffer,
246 int buffer_size,
247 const char *format,
248 va_list args) {
249 va_list args2;
250 va_copy(args2, args);
251 const int kLen = 16 * 1024;
252 int needed_length;
253 char *buffer = local_buffer;
254 // First try to print a message using a local buffer, and then fall back to
255 // mmaped buffer.
256 for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
257 if (use_mmap) {
258 va_end(args);
259 va_copy(args, args2);
260 buffer = (char*)MmapOrDie(kLen, "Report");
261 buffer_size = kLen;
262 }
263 needed_length = 0;
264 // Check that data fits into the current buffer.
265 # define CHECK_NEEDED_LENGTH \
266 if (needed_length >= buffer_size) { \
267 if (!use_mmap) continue; \
268 RAW_CHECK_MSG(needed_length < kLen, \
269 "Buffer in Report is too short!\n"); \
270 }
271 // Fuchsia's logging infrastructure always keeps track of the logging
272 // process, thread, and timestamp, so never prepend such information.
273 if (!SANITIZER_FUCHSIA && append_pid) {
274 int pid = internal_getpid();
275 const char *exe_name = GetProcessName();
276 if (common_flags()->log_exe_name && exe_name) {
277 needed_length += internal_snprintf(buffer, buffer_size,
278 "==%s", exe_name);
279 CHECK_NEEDED_LENGTH
280 }
281 needed_length += internal_snprintf(
282 buffer + needed_length, buffer_size - needed_length, "==%d==", pid);
283 CHECK_NEEDED_LENGTH
284 }
285 needed_length += VSNPrintf(buffer + needed_length,
286 buffer_size - needed_length, format, args);
287 CHECK_NEEDED_LENGTH
288 // If the message fit into the buffer, print it and exit.
289 break;
290 # undef CHECK_NEEDED_LENGTH
291 }
292 RawWrite(buffer);
293
294 // Remove color sequences from the message.
295 RemoveANSIEscapeSequencesFromString(buffer);
296 CallPrintfAndReportCallback(buffer);
297 LogMessageOnPrintf(buffer);
298
299 // If we had mapped any memory, clean up.
300 if (buffer != local_buffer)
301 UnmapOrDie((void *)buffer, buffer_size);
302 va_end(args2);
303 }
304
305 static void NOINLINE SharedPrintfCode(bool append_pid, const char *format,
306 va_list args) {
307 // |local_buffer| is small enough not to overflow the stack and/or violate
308 // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
309 // hand, the bigger the buffer is, the more the chance the error report will
310 // fit into it.
311 char local_buffer[400];
312 SharedPrintfCodeNoBuffer(append_pid, local_buffer, ARRAY_SIZE(local_buffer),
313 format, args);
314 }
315
316 FORMAT(1, 2)
317 void Printf(const char *format, ...) {
318 va_list args;
319 va_start(args, format);
320 SharedPrintfCode(false, format, args);
321 va_end(args);
322 }
323
324 // Like Printf, but prints the current PID before the output string.
325 FORMAT(1, 2)
326 void Report(const char *format, ...) {
327 va_list args;
328 va_start(args, format);
329 SharedPrintfCode(true, format, args);
330 va_end(args);
331 }
332
333 // Writes at most "length" symbols to "buffer" (including trailing '\0').
334 // Returns the number of symbols that should have been written to buffer
335 // (not including trailing '\0'). Thus, the string is truncated
336 // iff return value is not less than "length".
337 FORMAT(3, 4)
338 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
339 va_list args;
340 va_start(args, format);
341 int needed_length = VSNPrintf(buffer, length, format, args);
342 va_end(args);
343 return needed_length;
344 }
345
346 FORMAT(2, 3)
347 void InternalScopedString::append(const char *format, ...) {
348 CHECK_LT(length_, size());
349 va_list args;
350 va_start(args, format);
351 VSNPrintf(data() + length_, size() - length_, format, args);
352 va_end(args);
353 length_ += internal_strlen(data() + length_);
354 CHECK_LT(length_, size());
355 }
356
357 } // namespace __sanitizer