ubsan_diag.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. //===-- ubsan_diag.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. // Diagnostic reporting for the UBSan runtime.
  9. //
  10. //===----------------------------------------------------------------------===//
  11. #include "ubsan_diag.h"
  12. #include "ubsan_init.h"
  13. #include "ubsan_flags.h"
  14. #include "sanitizer_common/sanitizer_report_decorator.h"
  15. #include "sanitizer_common/sanitizer_stacktrace.h"
  16. #include "sanitizer_common/sanitizer_stacktrace_printer.h"
  17. #include "sanitizer_common/sanitizer_symbolizer.h"
  18. #include <stdio.h>
  19. using namespace __ubsan;
  20. static void MaybePrintStackTrace(uptr pc, uptr bp) {
  21. // We assume that flags are already parsed: InitIfNecessary
  22. // will definitely be called when we print the first diagnostics message.
  23. if (!flags()->print_stacktrace)
  24. return;
  25. // We can only use slow unwind, as we don't have any information about stack
  26. // top/bottom.
  27. // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
  28. // fetch stack top/bottom information if we have it (e.g. if we're running
  29. // under ASan).
  30. if (StackTrace::WillUseFastUnwind(false))
  31. return;
  32. BufferedStackTrace stack;
  33. stack.Unwind(kStackTraceMax, pc, bp, 0, 0, 0, false);
  34. stack.Print();
  35. }
  36. static void MaybeReportErrorSummary(Location Loc) {
  37. if (!common_flags()->print_summary)
  38. return;
  39. // Don't try to unwind the stack trace in UBSan summaries: just use the
  40. // provided location.
  41. if (Loc.isSourceLocation()) {
  42. SourceLocation SLoc = Loc.getSourceLocation();
  43. if (!SLoc.isInvalid()) {
  44. ReportErrorSummary("undefined-behavior", SLoc.getFilename(),
  45. SLoc.getLine(), "");
  46. return;
  47. }
  48. }
  49. ReportErrorSummary("undefined-behavior");
  50. }
  51. namespace {
  52. class Decorator : public SanitizerCommonDecorator {
  53. public:
  54. Decorator() : SanitizerCommonDecorator() {}
  55. const char *Highlight() const { return Green(); }
  56. const char *EndHighlight() const { return Default(); }
  57. const char *Note() const { return Black(); }
  58. const char *EndNote() const { return Default(); }
  59. };
  60. }
  61. Location __ubsan::getCallerLocation(uptr CallerLoc) {
  62. if (!CallerLoc)
  63. return Location();
  64. uptr Loc = StackTrace::GetPreviousInstructionPc(CallerLoc);
  65. return getFunctionLocation(Loc, 0);
  66. }
  67. Location __ubsan::getFunctionLocation(uptr Loc, const char **FName) {
  68. if (!Loc)
  69. return Location();
  70. InitIfNecessary();
  71. AddressInfo Info;
  72. if (!Symbolizer::GetOrInit()->SymbolizePC(Loc, &Info, 1) || !Info.module ||
  73. !*Info.module)
  74. return Location(Loc);
  75. if (FName && Info.function)
  76. *FName = Info.function;
  77. if (!Info.file)
  78. return ModuleLocation(Info.module, Info.module_offset);
  79. return SourceLocation(Info.file, Info.line, Info.column);
  80. }
  81. Diag &Diag::operator<<(const TypeDescriptor &V) {
  82. return AddArg(V.getTypeName());
  83. }
  84. Diag &Diag::operator<<(const Value &V) {
  85. if (V.getType().isSignedIntegerTy())
  86. AddArg(V.getSIntValue());
  87. else if (V.getType().isUnsignedIntegerTy())
  88. AddArg(V.getUIntValue());
  89. else if (V.getType().isFloatTy())
  90. AddArg(V.getFloatValue());
  91. else
  92. AddArg("<unknown>");
  93. return *this;
  94. }
  95. /// Hexadecimal printing for numbers too large for Printf to handle directly.
  96. static void PrintHex(UIntMax Val) {
  97. #if HAVE_INT128_T
  98. Printf("0x%08x%08x%08x%08x",
  99. (unsigned int)(Val >> 96),
  100. (unsigned int)(Val >> 64),
  101. (unsigned int)(Val >> 32),
  102. (unsigned int)(Val));
  103. #else
  104. UNREACHABLE("long long smaller than 64 bits?");
  105. #endif
  106. }
  107. static void renderLocation(Location Loc) {
  108. InternalScopedString LocBuffer(1024);
  109. switch (Loc.getKind()) {
  110. case Location::LK_Source: {
  111. SourceLocation SLoc = Loc.getSourceLocation();
  112. if (SLoc.isInvalid())
  113. LocBuffer.append("<unknown>");
  114. else
  115. RenderSourceLocation(&LocBuffer, SLoc.getFilename(), SLoc.getLine(),
  116. SLoc.getColumn(), common_flags()->strip_path_prefix);
  117. break;
  118. }
  119. case Location::LK_Module: {
  120. ModuleLocation MLoc = Loc.getModuleLocation();
  121. RenderModuleLocation(&LocBuffer, MLoc.getModuleName(), MLoc.getOffset(),
  122. common_flags()->strip_path_prefix);
  123. break;
  124. }
  125. case Location::LK_Memory:
  126. LocBuffer.append("%p", Loc.getMemoryLocation());
  127. break;
  128. case Location::LK_Null:
  129. LocBuffer.append("<unknown>");
  130. break;
  131. }
  132. Printf("%s:", LocBuffer.data());
  133. }
  134. static void renderText(const char *Message, const Diag::Arg *Args) {
  135. for (const char *Msg = Message; *Msg; ++Msg) {
  136. if (*Msg != '%') {
  137. char Buffer[64];
  138. unsigned I;
  139. for (I = 0; Msg[I] && Msg[I] != '%' && I != 63; ++I)
  140. Buffer[I] = Msg[I];
  141. Buffer[I] = '\0';
  142. Printf(Buffer);
  143. Msg += I - 1;
  144. } else {
  145. const Diag::Arg &A = Args[*++Msg - '0'];
  146. switch (A.Kind) {
  147. case Diag::AK_String:
  148. Printf("%s", A.String);
  149. break;
  150. case Diag::AK_Mangled: {
  151. Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
  152. break;
  153. }
  154. case Diag::AK_SInt:
  155. // 'long long' is guaranteed to be at least 64 bits wide.
  156. if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
  157. Printf("%lld", (long long)A.SInt);
  158. else
  159. PrintHex(A.SInt);
  160. break;
  161. case Diag::AK_UInt:
  162. if (A.UInt <= UINT64_MAX)
  163. Printf("%llu", (unsigned long long)A.UInt);
  164. else
  165. PrintHex(A.UInt);
  166. break;
  167. case Diag::AK_Float: {
  168. // FIXME: Support floating-point formatting in sanitizer_common's
  169. // printf, and stop using snprintf here.
  170. char Buffer[32];
  171. snprintf(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float);
  172. Printf("%s", Buffer);
  173. break;
  174. }
  175. case Diag::AK_Pointer:
  176. Printf("%p", A.Pointer);
  177. break;
  178. }
  179. }
  180. }
  181. }
  182. /// Find the earliest-starting range in Ranges which ends after Loc.
  183. static Range *upperBound(MemoryLocation Loc, Range *Ranges,
  184. unsigned NumRanges) {
  185. Range *Best = 0;
  186. for (unsigned I = 0; I != NumRanges; ++I)
  187. if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
  188. (!Best ||
  189. Best->getStart().getMemoryLocation() >
  190. Ranges[I].getStart().getMemoryLocation()))
  191. Best = &Ranges[I];
  192. return Best;
  193. }
  194. static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
  195. return (LHS < RHS) ? 0 : LHS - RHS;
  196. }
  197. static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
  198. const uptr Limit = (uptr)-1;
  199. return (LHS > Limit - RHS) ? Limit : LHS + RHS;
  200. }
  201. /// Render a snippet of the address space near a location.
  202. static void renderMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
  203. Range *Ranges, unsigned NumRanges,
  204. const Diag::Arg *Args) {
  205. // Show at least the 8 bytes surrounding Loc.
  206. const unsigned MinBytesNearLoc = 4;
  207. MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
  208. MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
  209. MemoryLocation OrigMin = Min;
  210. for (unsigned I = 0; I < NumRanges; ++I) {
  211. Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
  212. Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
  213. }
  214. // If we have too many interesting bytes, prefer to show bytes after Loc.
  215. const unsigned BytesToShow = 32;
  216. if (Max - Min > BytesToShow)
  217. Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
  218. Max = addNoOverflow(Min, BytesToShow);
  219. if (!IsAccessibleMemoryRange(Min, Max - Min)) {
  220. Printf("<memory cannot be printed>\n");
  221. return;
  222. }
  223. // Emit data.
  224. for (uptr P = Min; P != Max; ++P) {
  225. unsigned char C = *reinterpret_cast<const unsigned char*>(P);
  226. Printf("%s%02x", (P % 8 == 0) ? " " : " ", C);
  227. }
  228. Printf("\n");
  229. // Emit highlights.
  230. Printf(Decor.Highlight());
  231. Range *InRange = upperBound(Min, Ranges, NumRanges);
  232. for (uptr P = Min; P != Max; ++P) {
  233. char Pad = ' ', Byte = ' ';
  234. if (InRange && InRange->getEnd().getMemoryLocation() == P)
  235. InRange = upperBound(P, Ranges, NumRanges);
  236. if (!InRange && P > Loc)
  237. break;
  238. if (InRange && InRange->getStart().getMemoryLocation() < P)
  239. Pad = '~';
  240. if (InRange && InRange->getStart().getMemoryLocation() <= P)
  241. Byte = '~';
  242. char Buffer[] = { Pad, Pad, P == Loc ? '^' : Byte, Byte, 0 };
  243. Printf((P % 8 == 0) ? Buffer : &Buffer[1]);
  244. }
  245. Printf("%s\n", Decor.EndHighlight());
  246. // Go over the line again, and print names for the ranges.
  247. InRange = 0;
  248. unsigned Spaces = 0;
  249. for (uptr P = Min; P != Max; ++P) {
  250. if (!InRange || InRange->getEnd().getMemoryLocation() == P)
  251. InRange = upperBound(P, Ranges, NumRanges);
  252. if (!InRange)
  253. break;
  254. Spaces += (P % 8) == 0 ? 2 : 1;
  255. if (InRange && InRange->getStart().getMemoryLocation() == P) {
  256. while (Spaces--)
  257. Printf(" ");
  258. renderText(InRange->getText(), Args);
  259. Printf("\n");
  260. // FIXME: We only support naming one range for now!
  261. break;
  262. }
  263. Spaces += 2;
  264. }
  265. // FIXME: Print names for anything we can identify within the line:
  266. //
  267. // * If we can identify the memory itself as belonging to a particular
  268. // global, stack variable, or dynamic allocation, then do so.
  269. //
  270. // * If we have a pointer-size, pointer-aligned range highlighted,
  271. // determine whether the value of that range is a pointer to an
  272. // entity which we can name, and if so, print that name.
  273. //
  274. // This needs an external symbolizer, or (preferably) ASan instrumentation.
  275. }
  276. Diag::~Diag() {
  277. // All diagnostics should be printed under report mutex.
  278. CommonSanitizerReportMutex.CheckLocked();
  279. Decorator Decor;
  280. Printf(Decor.Bold());
  281. renderLocation(Loc);
  282. switch (Level) {
  283. case DL_Error:
  284. Printf("%s runtime error: %s%s",
  285. Decor.Warning(), Decor.EndWarning(), Decor.Bold());
  286. break;
  287. case DL_Note:
  288. Printf("%s note: %s", Decor.Note(), Decor.EndNote());
  289. break;
  290. }
  291. renderText(Message, Args);
  292. Printf("%s\n", Decor.Default());
  293. if (Loc.isMemoryLocation())
  294. renderMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges,
  295. NumRanges, Args);
  296. }
  297. ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc)
  298. : Opts(Opts), SummaryLoc(SummaryLoc) {
  299. InitIfNecessary();
  300. CommonSanitizerReportMutex.Lock();
  301. }
  302. ScopedReport::~ScopedReport() {
  303. MaybePrintStackTrace(Opts.pc, Opts.bp);
  304. MaybeReportErrorSummary(SummaryLoc);
  305. CommonSanitizerReportMutex.Unlock();
  306. if (Opts.DieAfterReport || flags()->halt_on_error)
  307. Die();
  308. }
  309. bool __ubsan::MatchSuppression(const char *Str, SuppressionType Type) {
  310. Suppression *s;
  311. // If .preinit_array is not used, it is possible that the UBSan runtime is not
  312. // initialized.
  313. if (!SANITIZER_CAN_USE_PREINIT_ARRAY)
  314. InitIfNecessary();
  315. return SuppressionContext::Get()->Match(Str, Type, &s);
  316. }