ubsan_diag.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //===-- ubsan_diag.cpp ----------------------------------------------------===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Diagnostic reporting for the UBSan runtime.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ubsan_platform.h"
  13. #if CAN_SANITIZE_UB
  14. #include "ubsan_diag.h"
  15. #include "ubsan_init.h"
  16. #include "ubsan_flags.h"
  17. #include "ubsan_monitor.h"
  18. #include "sanitizer_common/sanitizer_placement_new.h"
  19. #include "sanitizer_common/sanitizer_report_decorator.h"
  20. #include "sanitizer_common/sanitizer_stacktrace.h"
  21. #include "sanitizer_common/sanitizer_stacktrace_printer.h"
  22. #include "sanitizer_common/sanitizer_suppressions.h"
  23. #include "sanitizer_common/sanitizer_symbolizer.h"
  24. #include <stdio.h>
  25. using namespace __ubsan;
  26. // UBSan is combined with runtimes that already provide this functionality
  27. // (e.g., ASan) as well as runtimes that lack it (e.g., scudo). Tried to use
  28. // weak linkage to resolve this issue which is not portable and breaks on
  29. // Windows.
  30. // TODO(yln): This is a temporary workaround. GetStackTrace functions will be
  31. // removed in the future.
  32. void ubsan_GetStackTrace(BufferedStackTrace *stack, uptr max_depth, uptr pc,
  33. uptr bp, void *context, bool request_fast) {
  34. uptr top = 0;
  35. uptr bottom = 0;
  36. GetThreadStackTopAndBottom(false, &top, &bottom);
  37. bool fast = StackTrace::WillUseFastUnwind(request_fast);
  38. stack->Unwind(max_depth, pc, bp, context, top, bottom, fast);
  39. }
  40. static void MaybePrintStackTrace(uptr pc, uptr bp) {
  41. // We assume that flags are already parsed, as UBSan runtime
  42. // will definitely be called when we print the first diagnostics message.
  43. if (!flags()->print_stacktrace)
  44. return;
  45. BufferedStackTrace stack;
  46. ubsan_GetStackTrace(&stack, kStackTraceMax, pc, bp, nullptr,
  47. common_flags()->fast_unwind_on_fatal);
  48. stack.Print();
  49. }
  50. static const char *ConvertTypeToString(ErrorType Type) {
  51. switch (Type) {
  52. #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
  53. case ErrorType::Name: \
  54. return SummaryKind;
  55. #include "ubsan_checks.inc"
  56. #undef UBSAN_CHECK
  57. }
  58. UNREACHABLE("unknown ErrorType!");
  59. }
  60. static const char *ConvertTypeToFlagName(ErrorType Type) {
  61. switch (Type) {
  62. #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
  63. case ErrorType::Name: \
  64. return FSanitizeFlagName;
  65. #include "ubsan_checks.inc"
  66. #undef UBSAN_CHECK
  67. }
  68. UNREACHABLE("unknown ErrorType!");
  69. }
  70. static void MaybeReportErrorSummary(Location Loc, ErrorType Type) {
  71. if (!common_flags()->print_summary)
  72. return;
  73. if (!flags()->report_error_type)
  74. Type = ErrorType::GenericUB;
  75. const char *ErrorKind = ConvertTypeToString(Type);
  76. if (Loc.isSourceLocation()) {
  77. SourceLocation SLoc = Loc.getSourceLocation();
  78. if (!SLoc.isInvalid()) {
  79. AddressInfo AI;
  80. AI.file = internal_strdup(SLoc.getFilename());
  81. AI.line = SLoc.getLine();
  82. AI.column = SLoc.getColumn();
  83. AI.function = nullptr;
  84. ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());
  85. AI.Clear();
  86. return;
  87. }
  88. } else if (Loc.isSymbolizedStack()) {
  89. const AddressInfo &AI = Loc.getSymbolizedStack()->info;
  90. ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());
  91. return;
  92. }
  93. ReportErrorSummary(ErrorKind, GetSanititizerToolName());
  94. }
  95. namespace {
  96. class Decorator : public SanitizerCommonDecorator {
  97. public:
  98. Decorator() : SanitizerCommonDecorator() {}
  99. const char *Highlight() const { return Green(); }
  100. const char *Note() const { return Black(); }
  101. };
  102. }
  103. SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
  104. InitAsStandaloneIfNecessary();
  105. return Symbolizer::GetOrInit()->SymbolizePC(PC);
  106. }
  107. Diag &Diag::operator<<(const TypeDescriptor &V) {
  108. return AddArg(V.getTypeName());
  109. }
  110. Diag &Diag::operator<<(const Value &V) {
  111. if (V.getType().isSignedIntegerTy())
  112. AddArg(V.getSIntValue());
  113. else if (V.getType().isUnsignedIntegerTy())
  114. AddArg(V.getUIntValue());
  115. else if (V.getType().isFloatTy())
  116. AddArg(V.getFloatValue());
  117. else
  118. AddArg("<unknown>");
  119. return *this;
  120. }
  121. /// Hexadecimal printing for numbers too large for Printf to handle directly.
  122. static void RenderHex(InternalScopedString *Buffer, UIntMax Val) {
  123. #if HAVE_INT128_T
  124. Buffer->AppendF("0x%08x%08x%08x%08x", (unsigned int)(Val >> 96),
  125. (unsigned int)(Val >> 64), (unsigned int)(Val >> 32),
  126. (unsigned int)(Val));
  127. #else
  128. UNREACHABLE("long long smaller than 64 bits?");
  129. #endif
  130. }
  131. static void RenderLocation(InternalScopedString *Buffer, Location Loc) {
  132. switch (Loc.getKind()) {
  133. case Location::LK_Source: {
  134. SourceLocation SLoc = Loc.getSourceLocation();
  135. if (SLoc.isInvalid())
  136. Buffer->AppendF("<unknown>");
  137. else
  138. StackTracePrinter::GetOrInit()->RenderSourceLocation(
  139. Buffer, SLoc.getFilename(), SLoc.getLine(), SLoc.getColumn(),
  140. common_flags()->symbolize_vs_style,
  141. common_flags()->strip_path_prefix);
  142. return;
  143. }
  144. case Location::LK_Memory:
  145. Buffer->AppendF("%p", reinterpret_cast<void *>(Loc.getMemoryLocation()));
  146. return;
  147. case Location::LK_Symbolized: {
  148. const AddressInfo &Info = Loc.getSymbolizedStack()->info;
  149. if (Info.file)
  150. StackTracePrinter::GetOrInit()->RenderSourceLocation(
  151. Buffer, Info.file, Info.line, Info.column,
  152. common_flags()->symbolize_vs_style,
  153. common_flags()->strip_path_prefix);
  154. else if (Info.module)
  155. StackTracePrinter::GetOrInit()->RenderModuleLocation(
  156. Buffer, Info.module, Info.module_offset, Info.module_arch,
  157. common_flags()->strip_path_prefix);
  158. else
  159. Buffer->AppendF("%p", reinterpret_cast<void *>(Info.address));
  160. return;
  161. }
  162. case Location::LK_Null:
  163. Buffer->AppendF("<unknown>");
  164. return;
  165. }
  166. }
  167. static void RenderText(InternalScopedString *Buffer, const char *Message,
  168. const Diag::Arg *Args) {
  169. for (const char *Msg = Message; *Msg; ++Msg) {
  170. if (*Msg != '%') {
  171. Buffer->AppendF("%c", *Msg);
  172. continue;
  173. }
  174. const Diag::Arg &A = Args[*++Msg - '0'];
  175. switch (A.Kind) {
  176. case Diag::AK_String:
  177. Buffer->AppendF("%s", A.String);
  178. break;
  179. case Diag::AK_TypeName: {
  180. if (SANITIZER_WINDOWS)
  181. // The Windows implementation demangles names early.
  182. Buffer->AppendF("'%s'", A.String);
  183. else
  184. Buffer->AppendF("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
  185. break;
  186. }
  187. case Diag::AK_SInt:
  188. // 'long long' is guaranteed to be at least 64 bits wide.
  189. if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
  190. Buffer->AppendF("%lld", (long long)A.SInt);
  191. else
  192. RenderHex(Buffer, A.SInt);
  193. break;
  194. case Diag::AK_UInt:
  195. if (A.UInt <= UINT64_MAX)
  196. Buffer->AppendF("%llu", (unsigned long long)A.UInt);
  197. else
  198. RenderHex(Buffer, A.UInt);
  199. break;
  200. case Diag::AK_Float: {
  201. // FIXME: Support floating-point formatting in sanitizer_common's
  202. // printf, and stop using snprintf here.
  203. char FloatBuffer[32];
  204. #if SANITIZER_WINDOWS
  205. // On MSVC platforms, long doubles are equal to regular doubles.
  206. // In MinGW environments on x86, long doubles are 80 bit, but here,
  207. // we're calling an MS CRT provided printf function which considers
  208. // long doubles to be 64 bit. Just cast the float value to a regular
  209. // double to avoid the potential ambiguity in MinGW mode.
  210. sprintf_s(FloatBuffer, sizeof(FloatBuffer), "%g", (double)A.Float);
  211. #else
  212. snprintf(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
  213. #endif
  214. Buffer->Append(FloatBuffer);
  215. break;
  216. }
  217. case Diag::AK_Pointer:
  218. Buffer->AppendF("%p", A.Pointer);
  219. break;
  220. }
  221. }
  222. }
  223. /// Find the earliest-starting range in Ranges which ends after Loc.
  224. static Range *upperBound(MemoryLocation Loc, Range *Ranges,
  225. unsigned NumRanges) {
  226. Range *Best = 0;
  227. for (unsigned I = 0; I != NumRanges; ++I)
  228. if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
  229. (!Best ||
  230. Best->getStart().getMemoryLocation() >
  231. Ranges[I].getStart().getMemoryLocation()))
  232. Best = &Ranges[I];
  233. return Best;
  234. }
  235. static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
  236. return (LHS < RHS) ? 0 : LHS - RHS;
  237. }
  238. static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
  239. const uptr Limit = (uptr)-1;
  240. return (LHS > Limit - RHS) ? Limit : LHS + RHS;
  241. }
  242. /// Render a snippet of the address space near a location.
  243. static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
  244. Range *Ranges, unsigned NumRanges,
  245. const Diag::Arg *Args) {
  246. // Show at least the 8 bytes surrounding Loc.
  247. const unsigned MinBytesNearLoc = 4;
  248. MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
  249. MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
  250. MemoryLocation OrigMin = Min;
  251. for (unsigned I = 0; I < NumRanges; ++I) {
  252. Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
  253. Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
  254. }
  255. // If we have too many interesting bytes, prefer to show bytes after Loc.
  256. const unsigned BytesToShow = 32;
  257. if (Max - Min > BytesToShow)
  258. Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
  259. Max = addNoOverflow(Min, BytesToShow);
  260. if (!IsAccessibleMemoryRange(Min, Max - Min)) {
  261. Printf("<memory cannot be printed>\n");
  262. return;
  263. }
  264. // Emit data.
  265. InternalScopedString Buffer;
  266. for (uptr P = Min; P != Max; ++P) {
  267. unsigned char C = *reinterpret_cast<const unsigned char*>(P);
  268. Buffer.AppendF("%s%02x", (P % 8 == 0) ? " " : " ", C);
  269. }
  270. Buffer.AppendF("\n");
  271. // Emit highlights.
  272. Buffer.Append(Decor.Highlight());
  273. Range *InRange = upperBound(Min, Ranges, NumRanges);
  274. for (uptr P = Min; P != Max; ++P) {
  275. char Pad = ' ', Byte = ' ';
  276. if (InRange && InRange->getEnd().getMemoryLocation() == P)
  277. InRange = upperBound(P, Ranges, NumRanges);
  278. if (!InRange && P > Loc)
  279. break;
  280. if (InRange && InRange->getStart().getMemoryLocation() < P)
  281. Pad = '~';
  282. if (InRange && InRange->getStart().getMemoryLocation() <= P)
  283. Byte = '~';
  284. if (P % 8 == 0)
  285. Buffer.AppendF("%c", Pad);
  286. Buffer.AppendF("%c", Pad);
  287. Buffer.AppendF("%c", P == Loc ? '^' : Byte);
  288. Buffer.AppendF("%c", Byte);
  289. }
  290. Buffer.AppendF("%s\n", Decor.Default());
  291. // Go over the line again, and print names for the ranges.
  292. InRange = 0;
  293. unsigned Spaces = 0;
  294. for (uptr P = Min; P != Max; ++P) {
  295. if (!InRange || InRange->getEnd().getMemoryLocation() == P)
  296. InRange = upperBound(P, Ranges, NumRanges);
  297. if (!InRange)
  298. break;
  299. Spaces += (P % 8) == 0 ? 2 : 1;
  300. if (InRange && InRange->getStart().getMemoryLocation() == P) {
  301. while (Spaces--)
  302. Buffer.AppendF(" ");
  303. RenderText(&Buffer, InRange->getText(), Args);
  304. Buffer.AppendF("\n");
  305. // FIXME: We only support naming one range for now!
  306. break;
  307. }
  308. Spaces += 2;
  309. }
  310. Printf("%s", Buffer.data());
  311. // FIXME: Print names for anything we can identify within the line:
  312. //
  313. // * If we can identify the memory itself as belonging to a particular
  314. // global, stack variable, or dynamic allocation, then do so.
  315. //
  316. // * If we have a pointer-size, pointer-aligned range highlighted,
  317. // determine whether the value of that range is a pointer to an
  318. // entity which we can name, and if so, print that name.
  319. //
  320. // This needs an external symbolizer, or (preferably) ASan instrumentation.
  321. }
  322. Diag::~Diag() {
  323. // All diagnostics should be printed under report mutex.
  324. ScopedReport::CheckLocked();
  325. Decorator Decor;
  326. InternalScopedString Buffer;
  327. // Prepare a report that a monitor process can inspect.
  328. if (Level == DL_Error) {
  329. RenderText(&Buffer, Message, Args);
  330. UndefinedBehaviorReport UBR{ConvertTypeToString(ET), Loc, Buffer};
  331. Buffer.clear();
  332. }
  333. Buffer.Append(Decor.Bold());
  334. RenderLocation(&Buffer, Loc);
  335. Buffer.AppendF(":");
  336. switch (Level) {
  337. case DL_Error:
  338. Buffer.AppendF("%s runtime error: %s%s", Decor.Warning(), Decor.Default(),
  339. Decor.Bold());
  340. break;
  341. case DL_Note:
  342. Buffer.AppendF("%s note: %s", Decor.Note(), Decor.Default());
  343. break;
  344. }
  345. RenderText(&Buffer, Message, Args);
  346. Buffer.AppendF("%s\n", Decor.Default());
  347. Printf("%s", Buffer.data());
  348. if (Loc.isMemoryLocation())
  349. PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args);
  350. }
  351. ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); }
  352. ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,
  353. ErrorType Type)
  354. : Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {}
  355. ScopedReport::~ScopedReport() {
  356. MaybePrintStackTrace(Opts.pc, Opts.bp);
  357. MaybeReportErrorSummary(SummaryLoc, Type);
  358. if (common_flags()->print_module_map >= 2)
  359. DumpProcessMap();
  360. if (flags()->halt_on_error)
  361. Die();
  362. }
  363. ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
  364. static SuppressionContext *suppression_ctx = nullptr;
  365. static const char kVptrCheck[] = "vptr_check";
  366. static const char *kSuppressionTypes[] = {
  367. #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName,
  368. #include "ubsan_checks.inc"
  369. #undef UBSAN_CHECK
  370. kVptrCheck,
  371. };
  372. SANITIZER_INTERFACE_WEAK_DEF(const char *, __ubsan_default_suppressions, void) {
  373. return "";
  374. }
  375. void __ubsan::InitializeSuppressions() {
  376. CHECK_EQ(nullptr, suppression_ctx);
  377. suppression_ctx = new (suppression_placeholder)
  378. SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
  379. suppression_ctx->ParseFromFile(flags()->suppressions);
  380. if (&__ubsan_default_suppressions)
  381. suppression_ctx->Parse(__ubsan_default_suppressions());
  382. }
  383. bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
  384. InitAsStandaloneIfNecessary();
  385. CHECK(suppression_ctx);
  386. Suppression *s;
  387. return suppression_ctx->Match(TypeName, kVptrCheck, &s);
  388. }
  389. bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) {
  390. InitAsStandaloneIfNecessary();
  391. CHECK(suppression_ctx);
  392. const char *SuppType = ConvertTypeToFlagName(ET);
  393. // Fast path: don't symbolize PC if there is no suppressions for given UB
  394. // type.
  395. if (!suppression_ctx->HasSuppressionType(SuppType))
  396. return false;
  397. Suppression *s = nullptr;
  398. // Suppress by file name known to runtime.
  399. if (Filename != nullptr && suppression_ctx->Match(Filename, SuppType, &s))
  400. return true;
  401. // Suppress by module name.
  402. if (const char *Module = Symbolizer::GetOrInit()->GetModuleNameForPc(PC)) {
  403. if (suppression_ctx->Match(Module, SuppType, &s))
  404. return true;
  405. }
  406. // Suppress by function or source file name from debug info.
  407. SymbolizedStackHolder Stack(Symbolizer::GetOrInit()->SymbolizePC(PC));
  408. const AddressInfo &AI = Stack.get()->info;
  409. return suppression_ctx->Match(AI.function, SuppType, &s) ||
  410. suppression_ctx->Match(AI.file, SuppType, &s);
  411. }
  412. #endif // CAN_SANITIZE_UB