1 //===-- sanitizer_printf.cc -----------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is shared between AddressSanitizer and ThreadSanitizer.
11 //
12 // Internal printf function, used inside run-time libraries.
13 // We can't use libc printf because we intercept some of the functions used
14 // inside it.
15 //===----------------------------------------------------------------------===//
16
17
18 #include "sanitizer_common.h"
19 #include "sanitizer_flags.h"
20 #include "sanitizer_libc.h"
21
22 #include <stdio.h>
23 #include <stdarg.h>
24
25 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 && \
26 !defined(va_copy)
27 # define va_copy(dst, src) ((dst) = (src))
28 #endif
29
30 namespace __sanitizer {
31
32 StaticSpinMutex CommonSanitizerReportMutex;
33
AppendChar(char ** buff,const char * buff_end,char c)34 static int AppendChar(char **buff, const char *buff_end, char c) {
35 if (*buff < buff_end) {
36 **buff = c;
37 (*buff)++;
38 }
39 return 1;
40 }
41
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|.
AppendNumber(char ** buff,const char * buff_end,u64 absolute_value,u8 base,u8 minimal_num_length,bool pad_with_zero,bool negative)45 static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
46 u8 base, u8 minimal_num_length, bool pad_with_zero,
47 bool negative) {
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);
53 int result = 0;
54 if (negative && minimal_num_length)
55 --minimal_num_length;
56 if (negative && pad_with_zero)
57 result += AppendChar(buff, buff_end, '-');
58 uptr num_buffer[kMaxLen];
59 int pos = 0;
60 do {
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;
70 }
71 RAW_CHECK(pos > 0);
72 pos--;
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);
76 }
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
81 : 'a' + digit - 10);
82 }
83 return result;
84 }
85
AppendUnsigned(char ** buff,const char * buff_end,u64 num,u8 base,u8 minimal_num_length,bool pad_with_zero)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 */);
90 }
91
AppendSignedDecimal(char ** buff,const char * buff_end,s64 num,u8 minimal_num_length,bool pad_with_zero)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 }
98
AppendString(char ** buff,const char * buff_end,int precision,const char * s)99 static int AppendString(char **buff, const char *buff_end, int precision,
100 const char *s) {
101 if (s == 0)
102 s = "<null>";
103 int result = 0;
104 for (; *s; s++) {
105 if (precision >= 0 && result >= precision)
106 break;
107 result += AppendChar(buff, buff_end, *s);
108 }
109 return result;
110 }
111
AppendPointer(char ** buff,const char * buff_end,u64 ptr_value)112 static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
113 int result = 0;
114 result += AppendString(buff, buff_end, -1, "0x");
115 result += AppendUnsigned(buff, buff_end, ptr_value, 16,
116 SANITIZER_POINTER_FORMAT_LENGTH, true);
117 return result;
118 }
119
VSNPrintf(char * buff,int buff_length,const char * format,va_list args)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";
124 RAW_CHECK(format);
125 RAW_CHECK(buff_length > 0);
126 const char *buff_end = &buff[buff_length - 1];
127 const char *cur = format;
128 int result = 0;
129 for (; *cur; cur++) {
130 if (*cur != '%') {
131 result += AppendChar(&buff, buff_end, *cur);
132 continue;
133 }
134 cur++;
135 bool have_width = (*cur >= '0' && *cur <= '9');
136 bool pad_with_zero = (*cur == '0');
137 int width = 0;
138 if (have_width) {
139 while (*cur >= '0' && *cur <= '9') {
140 width = width * 10 + *cur++ - '0';
141 }
142 }
143 bool have_precision = (cur[0] == '.' && cur[1] == '*');
144 int precision = -1;
145 if (have_precision) {
146 cur += 2;
147 precision = va_arg(args, int);
148 }
149 bool have_z = (*cur == 'z');
150 cur += have_z;
151 bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
152 cur += have_ll * 2;
153 s64 dval;
154 u64 uval;
155 bool have_flags = have_width | have_z | have_ll;
156 // Only %s supports precision for now
157 CHECK(!(precision >= 0 && *cur != 's'));
158 switch (*cur) {
159 case 'd': {
160 dval = have_ll ? va_arg(args, s64)
161 : have_z ? va_arg(args, sptr)
162 : va_arg(args, int);
163 result += AppendSignedDecimal(&buff, buff_end, dval, width,
164 pad_with_zero);
165 break;
166 }
167 case 'u':
168 case 'x': {
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);
174 break;
175 }
176 case 'p': {
177 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
178 result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
179 break;
180 }
181 case 's': {
182 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
183 result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
184 break;
185 }
186 case 'c': {
187 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
188 result += AppendChar(&buff, buff_end, va_arg(args, int));
189 break;
190 }
191 case '%' : {
192 RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
193 result += AppendChar(&buff, buff_end, '%');
194 break;
195 }
196 default: {
197 RAW_CHECK_MSG(false, kPrintfFormatsHelp);
198 }
199 }
200 }
201 RAW_CHECK(buff <= buff_end);
202 AppendChar(&buff, buff_end + 1, '\0');
203 return result;
204 }
205
206 static void (*PrintfAndReportCallback)(const char *);
SetPrintfAndReportCallback(void (* callback)(const char *))207 void SetPrintfAndReportCallback(void (*callback)(const char *)) {
208 PrintfAndReportCallback = callback;
209 }
210
211 // Can be overriden in frontend.
212 #if SANITIZER_SUPPORTS_WEAK_HOOKS
213 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
OnPrint(const char * str)214 void OnPrint(const char *str) {
215 (void)str;
216 }
217 #elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
218 void OnPrint(const char *str);
219 #else
OnPrint(const char * str)220 void OnPrint(const char *str) {
221 (void)str;
222 }
223 #endif
224
CallPrintfAndReportCallback(const char * str)225 static void CallPrintfAndReportCallback(const char *str) {
226 OnPrint(str);
227 if (PrintfAndReportCallback)
228 PrintfAndReportCallback(str);
229 }
230
SharedPrintfCode(bool append_pid,const char * format,va_list args)231 static void SharedPrintfCode(bool append_pid, const char *format,
232 va_list args) {
233 va_list args2;
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
239 // fit into it.
240 char local_buffer[400];
241 int needed_length;
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
245 // mmaped buffer.
246 for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
247 if (use_mmap) {
248 va_end(args);
249 va_copy(args, args2);
250 buffer = (char*)MmapOrDie(kLen, "Report");
251 buffer_size = kLen;
252 }
253 needed_length = 0;
254 if (append_pid) {
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.
259 if (!use_mmap)
260 continue;
261 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
262 }
263 }
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.
268 if (!use_mmap)
269 continue;
270 RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
271 }
272 // If the message fit into the buffer, print it and exit.
273 break;
274 }
275 RawWrite(buffer);
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);
281 va_end(args2);
282 }
283
284 FORMAT(1, 2)
Printf(const char * format,...)285 void Printf(const char *format, ...) {
286 va_list args;
287 va_start(args, format);
288 SharedPrintfCode(false, format, args);
289 va_end(args);
290 }
291
292 // Like Printf, but prints the current PID before the output string.
293 FORMAT(1, 2)
Report(const char * format,...)294 void Report(const char *format, ...) {
295 va_list args;
296 va_start(args, format);
297 SharedPrintfCode(true, format, args);
298 va_end(args);
299 }
300
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".
305 FORMAT(3, 4)
internal_snprintf(char * buffer,uptr length,const char * format,...)306 int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
307 va_list args;
308 va_start(args, format);
309 int needed_length = VSNPrintf(buffer, length, format, args);
310 va_end(args);
311 return needed_length;
312 }
313
314 FORMAT(2, 3)
append(const char * format,...)315 void InternalScopedString::append(const char *format, ...) {
316 CHECK_LT(length_, size());
317 va_list args;
318 va_start(args, format);
319 VSNPrintf(data() + length_, size() - length_, format, args);
320 va_end(args);
321 length_ += internal_strlen(data() + length_);
322 CHECK_LT(length_, size());
323 }
324
325 } // namespace __sanitizer
326