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 "sanitizer_common/sanitizer_placement_new.h"
20 #include "sanitizer_common/sanitizer_report_decorator.h"
21 #include "sanitizer_common/sanitizer_stacktrace.h"
22 #include "sanitizer_common/sanitizer_stacktrace_printer.h"
23 #include "sanitizer_common/sanitizer_suppressions.h"
24 #include "sanitizer_common/sanitizer_symbolizer.h"
27 using namespace __ubsan;
29 static void MaybePrintStackTrace(uptr pc, uptr bp) {
30 // We assume that flags are already parsed, as UBSan runtime
31 // will definitely be called when we print the first diagnostics message.
32 if (!flags()->print_stacktrace)
34 // We can only use slow unwind, as we don't have any information about stack
36 // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
37 // fetch stack top/bottom information if we have it (e.g. if we're running
39 if (StackTrace::WillUseFastUnwind(false))
41 BufferedStackTrace stack;
42 stack.Unwind(kStackTraceMax, pc, bp, 0, 0, 0, false);
46 static void MaybeReportErrorSummary(Location Loc) {
47 if (!common_flags()->print_summary)
49 const char *ErrorType = "undefined-behavior";
50 if (Loc.isSourceLocation()) {
51 SourceLocation SLoc = Loc.getSourceLocation();
52 if (!SLoc.isInvalid()) {
54 AI.file = internal_strdup(SLoc.getFilename());
55 AI.line = SLoc.getLine();
56 AI.column = SLoc.getColumn();
57 AI.function = internal_strdup(""); // Avoid printing ?? as function name.
58 ReportErrorSummary(ErrorType, AI);
62 } else if (Loc.isSymbolizedStack()) {
63 const AddressInfo &AI = Loc.getSymbolizedStack()->info;
64 ReportErrorSummary(ErrorType, AI);
67 ReportErrorSummary(ErrorType);
71 class Decorator : public SanitizerCommonDecorator {
73 Decorator() : SanitizerCommonDecorator() {}
74 const char *Highlight() const { return Green(); }
75 const char *EndHighlight() const { return Default(); }
76 const char *Note() const { return Black(); }
77 const char *EndNote() const { return Default(); }
81 SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
82 InitAsStandaloneIfNecessary();
83 return Symbolizer::GetOrInit()->SymbolizePC(PC);
86 Diag &Diag::operator<<(const TypeDescriptor &V) {
87 return AddArg(V.getTypeName());
90 Diag &Diag::operator<<(const Value &V) {
91 if (V.getType().isSignedIntegerTy())
92 AddArg(V.getSIntValue());
93 else if (V.getType().isUnsignedIntegerTy())
94 AddArg(V.getUIntValue());
95 else if (V.getType().isFloatTy())
96 AddArg(V.getFloatValue());
102 /// Hexadecimal printing for numbers too large for Printf to handle directly.
103 static void PrintHex(UIntMax Val) {
105 Printf("0x%08x%08x%08x%08x",
106 (unsigned int)(Val >> 96),
107 (unsigned int)(Val >> 64),
108 (unsigned int)(Val >> 32),
109 (unsigned int)(Val));
111 UNREACHABLE("long long smaller than 64 bits?");
115 static void renderLocation(Location Loc) {
116 InternalScopedString LocBuffer(1024);
117 switch (Loc.getKind()) {
118 case Location::LK_Source: {
119 SourceLocation SLoc = Loc.getSourceLocation();
120 if (SLoc.isInvalid())
121 LocBuffer.append("<unknown>");
123 RenderSourceLocation(&LocBuffer, SLoc.getFilename(), SLoc.getLine(),
124 SLoc.getColumn(), common_flags()->symbolize_vs_style,
125 common_flags()->strip_path_prefix);
128 case Location::LK_Memory:
129 LocBuffer.append("%p", Loc.getMemoryLocation());
131 case Location::LK_Symbolized: {
132 const AddressInfo &Info = Loc.getSymbolizedStack()->info;
134 RenderSourceLocation(&LocBuffer, Info.file, Info.line, Info.column,
135 common_flags()->symbolize_vs_style,
136 common_flags()->strip_path_prefix);
137 } else if (Info.module) {
138 RenderModuleLocation(&LocBuffer, Info.module, Info.module_offset,
139 common_flags()->strip_path_prefix);
141 LocBuffer.append("%p", Info.address);
145 case Location::LK_Null:
146 LocBuffer.append("<unknown>");
149 Printf("%s:", LocBuffer.data());
152 static void renderText(const char *Message, const Diag::Arg *Args) {
153 for (const char *Msg = Message; *Msg; ++Msg) {
157 for (I = 0; Msg[I] && Msg[I] != '%' && I != 63; ++I)
163 const Diag::Arg &A = Args[*++Msg - '0'];
165 case Diag::AK_String:
166 Printf("%s", A.String);
168 case Diag::AK_TypeName: {
169 if (SANITIZER_WINDOWS)
170 // The Windows implementation demangles names early.
171 Printf("'%s'", A.String);
173 Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
177 // 'long long' is guaranteed to be at least 64 bits wide.
178 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
179 Printf("%lld", (long long)A.SInt);
184 if (A.UInt <= UINT64_MAX)
185 Printf("%llu", (unsigned long long)A.UInt);
189 case Diag::AK_Float: {
190 // FIXME: Support floating-point formatting in sanitizer_common's
191 // printf, and stop using snprintf here.
193 #if SANITIZER_WINDOWS
194 sprintf_s(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float);
196 snprintf(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float);
198 Printf("%s", Buffer);
201 case Diag::AK_Pointer:
202 Printf("%p", A.Pointer);
209 /// Find the earliest-starting range in Ranges which ends after Loc.
210 static Range *upperBound(MemoryLocation Loc, Range *Ranges,
211 unsigned NumRanges) {
213 for (unsigned I = 0; I != NumRanges; ++I)
214 if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
216 Best->getStart().getMemoryLocation() >
217 Ranges[I].getStart().getMemoryLocation()))
222 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
223 return (LHS < RHS) ? 0 : LHS - RHS;
226 static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
227 const uptr Limit = (uptr)-1;
228 return (LHS > Limit - RHS) ? Limit : LHS + RHS;
231 /// Render a snippet of the address space near a location.
232 static void renderMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
233 Range *Ranges, unsigned NumRanges,
234 const Diag::Arg *Args) {
235 // Show at least the 8 bytes surrounding Loc.
236 const unsigned MinBytesNearLoc = 4;
237 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
238 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
239 MemoryLocation OrigMin = Min;
240 for (unsigned I = 0; I < NumRanges; ++I) {
241 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
242 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
245 // If we have too many interesting bytes, prefer to show bytes after Loc.
246 const unsigned BytesToShow = 32;
247 if (Max - Min > BytesToShow)
248 Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
249 Max = addNoOverflow(Min, BytesToShow);
251 if (!IsAccessibleMemoryRange(Min, Max - Min)) {
252 Printf("<memory cannot be printed>\n");
257 for (uptr P = Min; P != Max; ++P) {
258 unsigned char C = *reinterpret_cast<const unsigned char*>(P);
259 Printf("%s%02x", (P % 8 == 0) ? " " : " ", C);
264 Printf(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)
272 if (InRange && InRange->getStart().getMemoryLocation() < P)
274 if (InRange && InRange->getStart().getMemoryLocation() <= P)
276 char Buffer[] = { Pad, Pad, P == Loc ? '^' : Byte, Byte, 0 };
277 Printf((P % 8 == 0) ? Buffer : &Buffer[1]);
279 Printf("%s\n", Decor.EndHighlight());
281 // Go over the line again, and print names for the ranges.
284 for (uptr P = Min; P != Max; ++P) {
285 if (!InRange || InRange->getEnd().getMemoryLocation() == P)
286 InRange = upperBound(P, Ranges, NumRanges);
290 Spaces += (P % 8) == 0 ? 2 : 1;
292 if (InRange && InRange->getStart().getMemoryLocation() == P) {
295 renderText(InRange->getText(), Args);
297 // FIXME: We only support naming one range for now!
304 // FIXME: Print names for anything we can identify within the line:
306 // * If we can identify the memory itself as belonging to a particular
307 // global, stack variable, or dynamic allocation, then do so.
309 // * If we have a pointer-size, pointer-aligned range highlighted,
310 // determine whether the value of that range is a pointer to an
311 // entity which we can name, and if so, print that name.
313 // This needs an external symbolizer, or (preferably) ASan instrumentation.
317 // All diagnostics should be printed under report mutex.
318 CommonSanitizerReportMutex.CheckLocked();
320 Printf(Decor.Bold());
326 Printf("%s runtime error: %s%s",
327 Decor.Warning(), Decor.EndWarning(), Decor.Bold());
331 Printf("%s note: %s", Decor.Note(), Decor.EndNote());
335 renderText(Message, Args);
337 Printf("%s\n", Decor.Default());
339 if (Loc.isMemoryLocation())
340 renderMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges,
344 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc)
345 : Opts(Opts), SummaryLoc(SummaryLoc) {
346 InitAsStandaloneIfNecessary();
347 CommonSanitizerReportMutex.Lock();
350 ScopedReport::~ScopedReport() {
351 MaybePrintStackTrace(Opts.pc, Opts.bp);
352 MaybeReportErrorSummary(SummaryLoc);
353 CommonSanitizerReportMutex.Unlock();
354 if (Opts.DieAfterReport || flags()->halt_on_error)
358 ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
359 static SuppressionContext *suppression_ctx = nullptr;
360 static const char kVptrCheck[] = "vptr_check";
361 static const char *kSuppressionTypes[] = { kVptrCheck };
363 void __ubsan::InitializeSuppressions() {
364 CHECK_EQ(nullptr, suppression_ctx);
365 suppression_ctx = new (suppression_placeholder) // NOLINT
366 SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
367 suppression_ctx->ParseFromFile(flags()->suppressions);
370 bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
371 InitAsStandaloneIfNecessary();
372 CHECK(suppression_ctx);
374 return suppression_ctx->Match(TypeName, kVptrCheck, &s);
377 #endif // CAN_SANITIZE_UB