sanitizer_printf.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. #include "sanitizer_common.h"
  15. #include "sanitizer_flags.h"
  16. #include "sanitizer_libc.h"
  17. #include <stdio.h>
  18. #include <stdarg.h>
  19. #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 && \
  20. !defined(va_copy)
  21. # define va_copy(dst, src) ((dst) = (src))
  22. #endif
  23. namespace __sanitizer {
  24. StaticSpinMutex CommonSanitizerReportMutex;
  25. static int AppendChar(char **buff, const char *buff_end, char c) {
  26. if (*buff < buff_end) {
  27. **buff = c;
  28. (*buff)++;
  29. }
  30. return 1;
  31. }
  32. // Appends number in a given base to buffer. If its length is less than
  33. // |minimal_num_length|, it is padded with leading zeroes or spaces, depending
  34. // on the value of |pad_with_zero|.
  35. static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
  36. u8 base, u8 minimal_num_length, bool pad_with_zero,
  37. bool negative) {
  38. uptr const kMaxLen = 30;
  39. RAW_CHECK(base == 10 || base == 16);
  40. RAW_CHECK(base == 10 || !negative);
  41. RAW_CHECK(absolute_value || !negative);
  42. RAW_CHECK(minimal_num_length < kMaxLen);
  43. int result = 0;
  44. if (negative && minimal_num_length)
  45. --minimal_num_length;
  46. if (negative && pad_with_zero)
  47. result += AppendChar(buff, buff_end, '-');
  48. uptr num_buffer[kMaxLen];
  49. int pos = 0;
  50. do {
  51. RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
  52. num_buffer[pos++] = absolute_value % base;
  53. absolute_value /= base;
  54. } while (absolute_value > 0);
  55. if (pos < minimal_num_length) {
  56. // Make sure compiler doesn't insert call to memset here.
  57. internal_memset(&num_buffer[pos], 0,
  58. sizeof(num_buffer[0]) * (minimal_num_length - pos));
  59. pos = minimal_num_length;
  60. }
  61. RAW_CHECK(pos > 0);
  62. pos--;
  63. for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
  64. char c = (pad_with_zero || pos == 0) ? '0' : ' ';
  65. result += AppendChar(buff, buff_end, c);
  66. }
  67. if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
  68. for (; pos >= 0; pos--) {
  69. char digit = static_cast<char>(num_buffer[pos]);
  70. result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
  71. : 'a' + digit - 10);
  72. }
  73. return result;
  74. }
  75. static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
  76. u8 minimal_num_length, bool pad_with_zero) {
  77. return AppendNumber(buff, buff_end, num, base, minimal_num_length,
  78. pad_with_zero, false /* negative */);
  79. }
  80. static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
  81. u8 minimal_num_length, bool pad_with_zero) {
  82. bool negative = (num < 0);
  83. return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
  84. minimal_num_length, pad_with_zero, negative);
  85. }
  86. static int AppendString(char **buff, const char *buff_end, int precision,
  87. const char *s) {
  88. if (s == 0)
  89. s = "<null>";
  90. int result = 0;
  91. for (; *s; s++) {
  92. if (precision >= 0 && result >= precision)
  93. break;
  94. result += AppendChar(buff, buff_end, *s);
  95. }
  96. return result;
  97. }
  98. static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
  99. int result = 0;
  100. result += AppendString(buff, buff_end, -1, "0x");
  101. result += AppendUnsigned(buff, buff_end, ptr_value, 16,
  102. SANITIZER_POINTER_FORMAT_LENGTH, true);
  103. return result;
  104. }
  105. int VSNPrintf(char *buff, int buff_length,
  106. const char *format, va_list args) {
  107. static const char *kPrintfFormatsHelp =
  108. "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %(\\.\\*)?s; %c\n";
  109. RAW_CHECK(format);
  110. RAW_CHECK(buff_length > 0);
  111. const char *buff_end = &buff[buff_length - 1];
  112. const char *cur = format;
  113. int result = 0;
  114. for (; *cur; cur++) {
  115. if (*cur != '%') {
  116. result += AppendChar(&buff, buff_end, *cur);
  117. continue;
  118. }
  119. cur++;
  120. bool have_width = (*cur >= '0' && *cur <= '9');
  121. bool pad_with_zero = (*cur == '0');
  122. int width = 0;
  123. if (have_width) {
  124. while (*cur >= '0' && *cur <= '9') {
  125. width = width * 10 + *cur++ - '0';
  126. }
  127. }
  128. bool have_precision = (cur[0] == '.' && cur[1] == '*');
  129. int precision = -1;
  130. if (have_precision) {
  131. cur += 2;
  132. precision = va_arg(args, int);
  133. }
  134. bool have_z = (*cur == 'z');
  135. cur += have_z;
  136. bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
  137. cur += have_ll * 2;
  138. s64 dval;
  139. u64 uval;
  140. bool have_flags = have_width | have_z | have_ll;
  141. // Only %s supports precision for now
  142. CHECK(!(precision >= 0 && *cur != 's'));
  143. switch (*cur) {
  144. case 'd': {
  145. dval = have_ll ? va_arg(args, s64)
  146. : have_z ? va_arg(args, sptr)
  147. : va_arg(args, int);
  148. result += AppendSignedDecimal(&buff, buff_end, dval, width,
  149. pad_with_zero);
  150. break;
  151. }
  152. case 'u':
  153. case 'x': {
  154. uval = have_ll ? va_arg(args, u64)
  155. : have_z ? va_arg(args, uptr)
  156. : va_arg(args, unsigned);
  157. result += AppendUnsigned(&buff, buff_end, uval,
  158. (*cur == 'u') ? 10 : 16, width, pad_with_zero);
  159. break;
  160. }
  161. case 'p': {
  162. RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
  163. result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
  164. break;
  165. }
  166. case 's': {
  167. RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
  168. result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
  169. break;
  170. }
  171. case 'c': {
  172. RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
  173. result += AppendChar(&buff, buff_end, va_arg(args, int));
  174. break;
  175. }
  176. case '%' : {
  177. RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
  178. result += AppendChar(&buff, buff_end, '%');
  179. break;
  180. }
  181. default: {
  182. RAW_CHECK_MSG(false, kPrintfFormatsHelp);
  183. }
  184. }
  185. }
  186. RAW_CHECK(buff <= buff_end);
  187. AppendChar(&buff, buff_end + 1, '\0');
  188. return result;
  189. }
  190. static void (*PrintfAndReportCallback)(const char *);
  191. void SetPrintfAndReportCallback(void (*callback)(const char *)) {
  192. PrintfAndReportCallback = callback;
  193. }
  194. // Can be overriden in frontend.
  195. #if SANITIZER_SUPPORTS_WEAK_HOOKS
  196. SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
  197. void OnPrint(const char *str) {
  198. (void)str;
  199. }
  200. #elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
  201. void OnPrint(const char *str);
  202. #else
  203. void OnPrint(const char *str) {
  204. (void)str;
  205. }
  206. #endif
  207. static void CallPrintfAndReportCallback(const char *str) {
  208. OnPrint(str);
  209. if (PrintfAndReportCallback)
  210. PrintfAndReportCallback(str);
  211. }
  212. static void SharedPrintfCode(bool append_pid, const char *format,
  213. va_list args) {
  214. va_list args2;
  215. va_copy(args2, args);
  216. const int kLen = 16 * 1024;
  217. // |local_buffer| is small enough not to overflow the stack and/or violate
  218. // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
  219. // hand, the bigger the buffer is, the more the chance the error report will
  220. // fit into it.
  221. char local_buffer[400];
  222. int needed_length;
  223. char *buffer = local_buffer;
  224. int buffer_size = ARRAY_SIZE(local_buffer);
  225. // First try to print a message using a local buffer, and then fall back to
  226. // mmaped buffer.
  227. for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
  228. if (use_mmap) {
  229. va_end(args);
  230. va_copy(args, args2);
  231. buffer = (char*)MmapOrDie(kLen, "Report");
  232. buffer_size = kLen;
  233. }
  234. needed_length = 0;
  235. if (append_pid) {
  236. int pid = internal_getpid();
  237. needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
  238. if (needed_length >= buffer_size) {
  239. // The pid doesn't fit into the current buffer.
  240. if (!use_mmap)
  241. continue;
  242. RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
  243. }
  244. }
  245. needed_length += VSNPrintf(buffer + needed_length,
  246. buffer_size - needed_length, format, args);
  247. if (needed_length >= buffer_size) {
  248. // The message doesn't fit into the current buffer.
  249. if (!use_mmap)
  250. continue;
  251. RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
  252. }
  253. // If the message fit into the buffer, print it and exit.
  254. break;
  255. }
  256. RawWrite(buffer);
  257. AndroidLogWrite(buffer);
  258. CallPrintfAndReportCallback(buffer);
  259. // If we had mapped any memory, clean up.
  260. if (buffer != local_buffer)
  261. UnmapOrDie((void *)buffer, buffer_size);
  262. va_end(args2);
  263. }
  264. FORMAT(1, 2)
  265. void Printf(const char *format, ...) {
  266. va_list args;
  267. va_start(args, format);
  268. SharedPrintfCode(false, format, args);
  269. va_end(args);
  270. }
  271. // Like Printf, but prints the current PID before the output string.
  272. FORMAT(1, 2)
  273. void Report(const char *format, ...) {
  274. va_list args;
  275. va_start(args, format);
  276. SharedPrintfCode(true, format, args);
  277. va_end(args);
  278. }
  279. // Writes at most "length" symbols to "buffer" (including trailing '\0').
  280. // Returns the number of symbols that should have been written to buffer
  281. // (not including trailing '\0'). Thus, the string is truncated
  282. // iff return value is not less than "length".
  283. FORMAT(3, 4)
  284. int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
  285. va_list args;
  286. va_start(args, format);
  287. int needed_length = VSNPrintf(buffer, length, format, args);
  288. va_end(args);
  289. return needed_length;
  290. }
  291. FORMAT(2, 3)
  292. void InternalScopedString::append(const char *format, ...) {
  293. CHECK_LT(length_, size());
  294. va_list args;
  295. va_start(args, format);
  296. VSNPrintf(data() + length_, size() - length_, format, args);
  297. va_end(args);
  298. length_ += internal_strlen(data() + length_);
  299. CHECK_LT(length_, size());
  300. }
  301. } // namespace __sanitizer