ubsan_diag.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 = internal_strdup(""); // Avoid printing ?? as function name.
  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->append("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->append("<unknown>");
  137. else
  138. RenderSourceLocation(Buffer, SLoc.getFilename(), SLoc.getLine(),
  139. SLoc.getColumn(), common_flags()->symbolize_vs_style,
  140. common_flags()->strip_path_prefix);
  141. return;
  142. }
  143. case Location::LK_Memory:
  144. Buffer->append("%p", reinterpret_cast<void *>(Loc.getMemoryLocation()));
  145. return;
  146. case Location::LK_Symbolized: {
  147. const AddressInfo &Info = Loc.getSymbolizedStack()->info;
  148. if (Info.file)
  149. RenderSourceLocation(Buffer, Info.file, Info.line, Info.column,
  150. common_flags()->symbolize_vs_style,
  151. common_flags()->strip_path_prefix);
  152. else if (Info.module)
  153. RenderModuleLocation(Buffer, Info.module, Info.module_offset,
  154. Info.module_arch, common_flags()->strip_path_prefix);
  155. else
  156. Buffer->append("%p", reinterpret_cast<void *>(Info.address));
  157. return;
  158. }
  159. case Location::LK_Null:
  160. Buffer->append("<unknown>");
  161. return;
  162. }
  163. }
  164. static void RenderText(InternalScopedString *Buffer, const char *Message,
  165. const Diag::Arg *Args) {
  166. for (const char *Msg = Message; *Msg; ++Msg) {
  167. if (*Msg != '%') {
  168. Buffer->append("%c", *Msg);
  169. continue;
  170. }
  171. const Diag::Arg &A = Args[*++Msg - '0'];
  172. switch (A.Kind) {
  173. case Diag::AK_String:
  174. Buffer->append("%s", A.String);
  175. break;
  176. case Diag::AK_TypeName: {
  177. if (SANITIZER_WINDOWS)
  178. // The Windows implementation demangles names early.
  179. Buffer->append("'%s'", A.String);
  180. else
  181. Buffer->append("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
  182. break;
  183. }
  184. case Diag::AK_SInt:
  185. // 'long long' is guaranteed to be at least 64 bits wide.
  186. if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
  187. Buffer->append("%lld", (long long)A.SInt);
  188. else
  189. RenderHex(Buffer, A.SInt);
  190. break;
  191. case Diag::AK_UInt:
  192. if (A.UInt <= UINT64_MAX)
  193. Buffer->append("%llu", (unsigned long long)A.UInt);
  194. else
  195. RenderHex(Buffer, A.UInt);
  196. break;
  197. case Diag::AK_Float: {
  198. // FIXME: Support floating-point formatting in sanitizer_common's
  199. // printf, and stop using snprintf here.
  200. char FloatBuffer[32];
  201. #if SANITIZER_WINDOWS
  202. sprintf_s(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
  203. #else
  204. snprintf(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
  205. #endif
  206. Buffer->append("%s", FloatBuffer);
  207. break;
  208. }
  209. case Diag::AK_Pointer:
  210. Buffer->append("%p", A.Pointer);
  211. break;
  212. }
  213. }
  214. }
  215. /// Find the earliest-starting range in Ranges which ends after Loc.
  216. static Range *upperBound(MemoryLocation Loc, Range *Ranges,
  217. unsigned NumRanges) {
  218. Range *Best = 0;
  219. for (unsigned I = 0; I != NumRanges; ++I)
  220. if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
  221. (!Best ||
  222. Best->getStart().getMemoryLocation() >
  223. Ranges[I].getStart().getMemoryLocation()))
  224. Best = &Ranges[I];
  225. return Best;
  226. }
  227. static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
  228. return (LHS < RHS) ? 0 : LHS - RHS;
  229. }
  230. static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
  231. const uptr Limit = (uptr)-1;
  232. return (LHS > Limit - RHS) ? Limit : LHS + RHS;
  233. }
  234. /// Render a snippet of the address space near a location.
  235. static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
  236. Range *Ranges, unsigned NumRanges,
  237. const Diag::Arg *Args) {
  238. // Show at least the 8 bytes surrounding Loc.
  239. const unsigned MinBytesNearLoc = 4;
  240. MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
  241. MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
  242. MemoryLocation OrigMin = Min;
  243. for (unsigned I = 0; I < NumRanges; ++I) {
  244. Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
  245. Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
  246. }
  247. // If we have too many interesting bytes, prefer to show bytes after Loc.
  248. const unsigned BytesToShow = 32;
  249. if (Max - Min > BytesToShow)
  250. Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
  251. Max = addNoOverflow(Min, BytesToShow);
  252. if (!IsAccessibleMemoryRange(Min, Max - Min)) {
  253. Printf("<memory cannot be printed>\n");
  254. return;
  255. }
  256. // Emit data.
  257. InternalScopedString Buffer;
  258. for (uptr P = Min; P != Max; ++P) {
  259. unsigned char C = *reinterpret_cast<const unsigned char*>(P);
  260. Buffer.append("%s%02x", (P % 8 == 0) ? " " : " ", C);
  261. }
  262. Buffer.append("\n");
  263. // Emit highlights.
  264. Buffer.append("%s", Decor.Highlight());
  265. Range *InRange = upperBound(Min, Ranges, NumRanges);
  266. for (uptr P = Min; P != Max; ++P) {
  267. char Pad = ' ', Byte = ' ';
  268. if (InRange && InRange->getEnd().getMemoryLocation() == P)
  269. InRange = upperBound(P, Ranges, NumRanges);
  270. if (!InRange && P > Loc)
  271. break;
  272. if (InRange && InRange->getStart().getMemoryLocation() < P)
  273. Pad = '~';
  274. if (InRange && InRange->getStart().getMemoryLocation() <= P)
  275. Byte = '~';
  276. if (P % 8 == 0)
  277. Buffer.append("%c", Pad);
  278. Buffer.append("%c", Pad);
  279. Buffer.append("%c", P == Loc ? '^' : Byte);
  280. Buffer.append("%c", Byte);
  281. }
  282. Buffer.append("%s\n", Decor.Default());
  283. // Go over the line again, and print names for the ranges.
  284. InRange = 0;
  285. unsigned Spaces = 0;
  286. for (uptr P = Min; P != Max; ++P) {
  287. if (!InRange || InRange->getEnd().getMemoryLocation() == P)
  288. InRange = upperBound(P, Ranges, NumRanges);
  289. if (!InRange)
  290. break;
  291. Spaces += (P % 8) == 0 ? 2 : 1;
  292. if (InRange && InRange->getStart().getMemoryLocation() == P) {
  293. while (Spaces--)
  294. Buffer.append(" ");
  295. RenderText(&Buffer, InRange->getText(), Args);
  296. Buffer.append("\n");
  297. // FIXME: We only support naming one range for now!
  298. break;
  299. }
  300. Spaces += 2;
  301. }
  302. Printf("%s", Buffer.data());
  303. // FIXME: Print names for anything we can identify within the line:
  304. //
  305. // * If we can identify the memory itself as belonging to a particular
  306. // global, stack variable, or dynamic allocation, then do so.
  307. //
  308. // * If we have a pointer-size, pointer-aligned range highlighted,
  309. // determine whether the value of that range is a pointer to an
  310. // entity which we can name, and if so, print that name.
  311. //
  312. // This needs an external symbolizer, or (preferably) ASan instrumentation.
  313. }
  314. Diag::~Diag() {
  315. // All diagnostics should be printed under report mutex.
  316. ScopedReport::CheckLocked();
  317. Decorator Decor;
  318. InternalScopedString Buffer;
  319. // Prepare a report that a monitor process can inspect.
  320. if (Level == DL_Error) {
  321. RenderText(&Buffer, Message, Args);
  322. UndefinedBehaviorReport UBR{ConvertTypeToString(ET), Loc, Buffer};
  323. Buffer.clear();
  324. }
  325. Buffer.append("%s", Decor.Bold());
  326. RenderLocation(&Buffer, Loc);
  327. Buffer.append(":");
  328. switch (Level) {
  329. case DL_Error:
  330. Buffer.append("%s runtime error: %s%s", Decor.Warning(), Decor.Default(),
  331. Decor.Bold());
  332. break;
  333. case DL_Note:
  334. Buffer.append("%s note: %s", Decor.Note(), Decor.Default());
  335. break;
  336. }
  337. RenderText(&Buffer, Message, Args);
  338. Buffer.append("%s\n", Decor.Default());
  339. Printf("%s", Buffer.data());
  340. if (Loc.isMemoryLocation())
  341. PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args);
  342. }
  343. ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); }
  344. ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,
  345. ErrorType Type)
  346. : Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {}
  347. ScopedReport::~ScopedReport() {
  348. MaybePrintStackTrace(Opts.pc, Opts.bp);
  349. MaybeReportErrorSummary(SummaryLoc, Type);
  350. if (common_flags()->print_module_map >= 2)
  351. DumpProcessMap();
  352. if (flags()->halt_on_error)
  353. Die();
  354. }
  355. ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
  356. static SuppressionContext *suppression_ctx = nullptr;
  357. static const char kVptrCheck[] = "vptr_check";
  358. static const char *kSuppressionTypes[] = {
  359. #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName,
  360. #include "ubsan_checks.inc"
  361. #undef UBSAN_CHECK
  362. kVptrCheck,
  363. };
  364. void __ubsan::InitializeSuppressions() {
  365. CHECK_EQ(nullptr, suppression_ctx);
  366. suppression_ctx = new (suppression_placeholder)
  367. SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
  368. suppression_ctx->ParseFromFile(flags()->suppressions);
  369. }
  370. bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
  371. InitAsStandaloneIfNecessary();
  372. CHECK(suppression_ctx);
  373. Suppression *s;
  374. return suppression_ctx->Match(TypeName, kVptrCheck, &s);
  375. }
  376. bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) {
  377. InitAsStandaloneIfNecessary();
  378. CHECK(suppression_ctx);
  379. const char *SuppType = ConvertTypeToFlagName(ET);
  380. // Fast path: don't symbolize PC if there is no suppressions for given UB
  381. // type.
  382. if (!suppression_ctx->HasSuppressionType(SuppType))
  383. return false;
  384. Suppression *s = nullptr;
  385. // Suppress by file name known to runtime.
  386. if (Filename != nullptr && suppression_ctx->Match(Filename, SuppType, &s))
  387. return true;
  388. // Suppress by module name.
  389. if (const char *Module = Symbolizer::GetOrInit()->GetModuleNameForPc(PC)) {
  390. if (suppression_ctx->Match(Module, SuppType, &s))
  391. return true;
  392. }
  393. // Suppress by function or source file name from debug info.
  394. SymbolizedStackHolder Stack(Symbolizer::GetOrInit()->SymbolizePC(PC));
  395. const AddressInfo &AI = Stack.get()->info;
  396. return suppression_ctx->Match(AI.function, SuppType, &s) ||
  397. suppression_ctx->Match(AI.file, SuppType, &s);
  398. }
  399. #endif // CAN_SANITIZE_UB