1 //===-- ubsan_diag.cc -----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Diagnostic reporting for the UBSan runtime.
12 //===----------------------------------------------------------------------===//
14 #include "ubsan_platform.h"
16 #include "ubsan_diag.h"
17 #include "ubsan_init.h"
18 #include "ubsan_flags.h"
19 #include "ubsan_monitor.h"
20 #include "sanitizer_common/sanitizer_placement_new.h"
21 #include "sanitizer_common/sanitizer_report_decorator.h"
22 #include "sanitizer_common/sanitizer_stacktrace.h"
23 #include "sanitizer_common/sanitizer_stacktrace_printer.h"
24 #include "sanitizer_common/sanitizer_suppressions.h"
25 #include "sanitizer_common/sanitizer_symbolizer.h"
28 using namespace __ubsan;
30 void __ubsan::GetStackTrace(BufferedStackTrace *stack, uptr max_depth, uptr pc,
31 uptr bp, void *context, bool fast) {
35 GetThreadStackTopAndBottom(false, &top, &bottom);
36 stack->Unwind(max_depth, pc, bp, context, top, bottom, fast);
39 static void MaybePrintStackTrace(uptr pc, uptr bp) {
40 // We assume that flags are already parsed, as UBSan runtime
41 // will definitely be called when we print the first diagnostics message.
42 if (!flags()->print_stacktrace)
45 BufferedStackTrace stack;
46 GetStackTrace(&stack, kStackTraceMax, pc, bp, nullptr,
47 common_flags()->fast_unwind_on_fatal);
51 static const char *ConvertTypeToString(ErrorType Type) {
53 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
54 case ErrorType::Name: \
56 #include "ubsan_checks.inc"
59 UNREACHABLE("unknown ErrorType!");
62 static const char *ConvertTypeToFlagName(ErrorType Type) {
64 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
65 case ErrorType::Name: \
66 return FSanitizeFlagName;
67 #include "ubsan_checks.inc"
70 UNREACHABLE("unknown ErrorType!");
73 static void MaybeReportErrorSummary(Location Loc, ErrorType Type) {
74 if (!common_flags()->print_summary)
76 if (!flags()->report_error_type)
77 Type = ErrorType::GenericUB;
78 const char *ErrorKind = ConvertTypeToString(Type);
79 if (Loc.isSourceLocation()) {
80 SourceLocation SLoc = Loc.getSourceLocation();
81 if (!SLoc.isInvalid()) {
83 AI.file = internal_strdup(SLoc.getFilename());
84 AI.line = SLoc.getLine();
85 AI.column = SLoc.getColumn();
86 AI.function = internal_strdup(""); // Avoid printing ?? as function name.
87 ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());
91 } else if (Loc.isSymbolizedStack()) {
92 const AddressInfo &AI = Loc.getSymbolizedStack()->info;
93 ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());
96 ReportErrorSummary(ErrorKind, GetSanititizerToolName());
100 class Decorator : public SanitizerCommonDecorator {
102 Decorator() : SanitizerCommonDecorator() {}
103 const char *Highlight() const { return Green(); }
104 const char *Note() const { return Black(); }
108 SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
109 InitAsStandaloneIfNecessary();
110 return Symbolizer::GetOrInit()->SymbolizePC(PC);
113 Diag &Diag::operator<<(const TypeDescriptor &V) {
114 return AddArg(V.getTypeName());
117 Diag &Diag::operator<<(const Value &V) {
118 if (V.getType().isSignedIntegerTy())
119 AddArg(V.getSIntValue());
120 else if (V.getType().isUnsignedIntegerTy())
121 AddArg(V.getUIntValue());
122 else if (V.getType().isFloatTy())
123 AddArg(V.getFloatValue());
129 /// Hexadecimal printing for numbers too large for Printf to handle directly.
130 static void RenderHex(InternalScopedString *Buffer, UIntMax Val) {
132 Buffer->append("0x%08x%08x%08x%08x", (unsigned int)(Val >> 96),
133 (unsigned int)(Val >> 64), (unsigned int)(Val >> 32),
134 (unsigned int)(Val));
136 UNREACHABLE("long long smaller than 64 bits?");
140 static void RenderLocation(InternalScopedString *Buffer, Location Loc) {
141 switch (Loc.getKind()) {
142 case Location::LK_Source: {
143 SourceLocation SLoc = Loc.getSourceLocation();
144 if (SLoc.isInvalid())
145 Buffer->append("<unknown>");
147 RenderSourceLocation(Buffer, SLoc.getFilename(), SLoc.getLine(),
148 SLoc.getColumn(), common_flags()->symbolize_vs_style,
149 common_flags()->strip_path_prefix);
152 case Location::LK_Memory:
153 Buffer->append("%p", Loc.getMemoryLocation());
155 case Location::LK_Symbolized: {
156 const AddressInfo &Info = Loc.getSymbolizedStack()->info;
158 RenderSourceLocation(Buffer, Info.file, Info.line, Info.column,
159 common_flags()->symbolize_vs_style,
160 common_flags()->strip_path_prefix);
161 else if (Info.module)
162 RenderModuleLocation(Buffer, Info.module, Info.module_offset,
163 Info.module_arch, common_flags()->strip_path_prefix);
165 Buffer->append("%p", Info.address);
168 case Location::LK_Null:
169 Buffer->append("<unknown>");
174 static void RenderText(InternalScopedString *Buffer, const char *Message,
175 const Diag::Arg *Args) {
176 for (const char *Msg = Message; *Msg; ++Msg) {
178 Buffer->append("%c", *Msg);
181 const Diag::Arg &A = Args[*++Msg - '0'];
183 case Diag::AK_String:
184 Buffer->append("%s", A.String);
186 case Diag::AK_TypeName: {
187 if (SANITIZER_WINDOWS)
188 // The Windows implementation demangles names early.
189 Buffer->append("'%s'", A.String);
191 Buffer->append("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
195 // 'long long' is guaranteed to be at least 64 bits wide.
196 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
197 Buffer->append("%lld", (long long)A.SInt);
199 RenderHex(Buffer, A.SInt);
202 if (A.UInt <= UINT64_MAX)
203 Buffer->append("%llu", (unsigned long long)A.UInt);
205 RenderHex(Buffer, A.UInt);
207 case Diag::AK_Float: {
208 // FIXME: Support floating-point formatting in sanitizer_common's
209 // printf, and stop using snprintf here.
210 char FloatBuffer[32];
211 #if SANITIZER_WINDOWS
212 sprintf_s(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
214 snprintf(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
216 Buffer->append("%s", FloatBuffer);
219 case Diag::AK_Pointer:
220 Buffer->append("%p", A.Pointer);
226 /// Find the earliest-starting range in Ranges which ends after Loc.
227 static Range *upperBound(MemoryLocation Loc, Range *Ranges,
228 unsigned NumRanges) {
230 for (unsigned I = 0; I != NumRanges; ++I)
231 if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
233 Best->getStart().getMemoryLocation() >
234 Ranges[I].getStart().getMemoryLocation()))
239 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
240 return (LHS < RHS) ? 0 : LHS - RHS;
243 static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
244 const uptr Limit = (uptr)-1;
245 return (LHS > Limit - RHS) ? Limit : LHS + RHS;
248 /// Render a snippet of the address space near a location.
249 static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
250 Range *Ranges, unsigned NumRanges,
251 const Diag::Arg *Args) {
252 // Show at least the 8 bytes surrounding Loc.
253 const unsigned MinBytesNearLoc = 4;
254 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
255 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
256 MemoryLocation OrigMin = Min;
257 for (unsigned I = 0; I < NumRanges; ++I) {
258 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
259 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
262 // If we have too many interesting bytes, prefer to show bytes after Loc.
263 const unsigned BytesToShow = 32;
264 if (Max - Min > BytesToShow)
265 Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
266 Max = addNoOverflow(Min, BytesToShow);
268 if (!IsAccessibleMemoryRange(Min, Max - Min)) {
269 Printf("<memory cannot be printed>\n");
274 InternalScopedString Buffer(1024);
275 for (uptr P = Min; P != Max; ++P) {
276 unsigned char C = *reinterpret_cast<const unsigned char*>(P);
277 Buffer.append("%s%02x", (P % 8 == 0) ? " " : " ", C);
282 Buffer.append(Decor.Highlight());
283 Range *InRange = upperBound(Min, Ranges, NumRanges);
284 for (uptr P = Min; P != Max; ++P) {
285 char Pad = ' ', Byte = ' ';
286 if (InRange && InRange->getEnd().getMemoryLocation() == P)
287 InRange = upperBound(P, Ranges, NumRanges);
288 if (!InRange && P > Loc)
290 if (InRange && InRange->getStart().getMemoryLocation() < P)
292 if (InRange && InRange->getStart().getMemoryLocation() <= P)
295 Buffer.append("%c", Pad);
296 Buffer.append("%c", Pad);
297 Buffer.append("%c", P == Loc ? '^' : Byte);
298 Buffer.append("%c", Byte);
300 Buffer.append("%s\n", Decor.Default());
302 // Go over the line again, and print names for the ranges.
305 for (uptr P = Min; P != Max; ++P) {
306 if (!InRange || InRange->getEnd().getMemoryLocation() == P)
307 InRange = upperBound(P, Ranges, NumRanges);
311 Spaces += (P % 8) == 0 ? 2 : 1;
313 if (InRange && InRange->getStart().getMemoryLocation() == P) {
316 RenderText(&Buffer, InRange->getText(), Args);
318 // FIXME: We only support naming one range for now!
325 Printf("%s", Buffer.data());
326 // FIXME: Print names for anything we can identify within the line:
328 // * If we can identify the memory itself as belonging to a particular
329 // global, stack variable, or dynamic allocation, then do so.
331 // * If we have a pointer-size, pointer-aligned range highlighted,
332 // determine whether the value of that range is a pointer to an
333 // entity which we can name, and if so, print that name.
335 // This needs an external symbolizer, or (preferably) ASan instrumentation.
339 // All diagnostics should be printed under report mutex.
340 ScopedReport::CheckLocked();
342 InternalScopedString Buffer(1024);
344 // Prepare a report that a monitor process can inspect.
345 if (Level == DL_Error) {
346 RenderText(&Buffer, Message, Args);
347 UndefinedBehaviorReport UBR{ConvertTypeToString(ET), Loc, Buffer};
351 Buffer.append(Decor.Bold());
352 RenderLocation(&Buffer, Loc);
357 Buffer.append("%s runtime error: %s%s", Decor.Warning(), Decor.Default(),
362 Buffer.append("%s note: %s", Decor.Note(), Decor.Default());
366 RenderText(&Buffer, Message, Args);
368 Buffer.append("%s\n", Decor.Default());
369 Printf("%s", Buffer.data());
371 if (Loc.isMemoryLocation())
372 PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args);
375 ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); }
377 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,
379 : Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {}
381 ScopedReport::~ScopedReport() {
382 MaybePrintStackTrace(Opts.pc, Opts.bp);
383 MaybeReportErrorSummary(SummaryLoc, Type);
384 if (flags()->halt_on_error)
388 ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
389 static SuppressionContext *suppression_ctx = nullptr;
390 static const char kVptrCheck[] = "vptr_check";
391 static const char *kSuppressionTypes[] = {
392 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName,
393 #include "ubsan_checks.inc"
398 void __ubsan::InitializeSuppressions() {
399 CHECK_EQ(nullptr, suppression_ctx);
400 suppression_ctx = new (suppression_placeholder) // NOLINT
401 SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
402 suppression_ctx->ParseFromFile(flags()->suppressions);
405 bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
406 InitAsStandaloneIfNecessary();
407 CHECK(suppression_ctx);
409 return suppression_ctx->Match(TypeName, kVptrCheck, &s);
412 bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) {
413 InitAsStandaloneIfNecessary();
414 CHECK(suppression_ctx);
415 const char *SuppType = ConvertTypeToFlagName(ET);
416 // Fast path: don't symbolize PC if there is no suppressions for given UB
418 if (!suppression_ctx->HasSuppressionType(SuppType))
420 Suppression *s = nullptr;
421 // Suppress by file name known to runtime.
422 if (Filename != nullptr && suppression_ctx->Match(Filename, SuppType, &s))
424 // Suppress by module name.
425 if (const char *Module = Symbolizer::GetOrInit()->GetModuleNameForPc(PC)) {
426 if (suppression_ctx->Match(Module, SuppType, &s))
429 // Suppress by function or source file name from debug info.
430 SymbolizedStackHolder Stack(Symbolizer::GetOrInit()->SymbolizePC(PC));
431 const AddressInfo &AI = Stack.get()->info;
432 return suppression_ctx->Match(AI.function, SuppType, &s) ||
433 suppression_ctx->Match(AI.file, SuppType, &s);
436 #endif // CAN_SANITIZE_UB