ubsan_diag.cpp 15 KB

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