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 void __ubsan::GetStackTrace(BufferedStackTrace *stack, uptr max_depth, uptr pc,
30 uptr bp, void *context, bool fast) {
34 GetThreadStackTopAndBottom(false, &top, &bottom);
35 stack->Unwind(max_depth, pc, bp, context, top, bottom, fast);
38 static void MaybePrintStackTrace(uptr pc, uptr bp) {
39 // We assume that flags are already parsed, as UBSan runtime
40 // will definitely be called when we print the first diagnostics message.
41 if (!flags()->print_stacktrace)
44 BufferedStackTrace stack;
45 GetStackTrace(&stack, kStackTraceMax, pc, bp, nullptr,
46 common_flags()->fast_unwind_on_fatal);
50 static const char *ConvertTypeToString(ErrorType Type) {
52 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
53 case ErrorType::Name: \
55 #include "ubsan_checks.inc"
58 UNREACHABLE("unknown ErrorType!");
61 static const char *ConvertTypeToFlagName(ErrorType Type) {
63 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
64 case ErrorType::Name: \
65 return FSanitizeFlagName;
66 #include "ubsan_checks.inc"
69 UNREACHABLE("unknown ErrorType!");
72 static void MaybeReportErrorSummary(Location Loc, ErrorType Type) {
73 if (!common_flags()->print_summary)
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()) {
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());
90 } else if (Loc.isSymbolizedStack()) {
91 const AddressInfo &AI = Loc.getSymbolizedStack()->info;
92 ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());
95 ReportErrorSummary(ErrorKind, GetSanititizerToolName());
99 class Decorator : public SanitizerCommonDecorator {
101 Decorator() : SanitizerCommonDecorator() {}
102 const char *Highlight() const { return Green(); }
103 const char *Note() const { return Black(); }
107 SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
108 InitAsStandaloneIfNecessary();
109 return Symbolizer::GetOrInit()->SymbolizePC(PC);
112 Diag &Diag::operator<<(const TypeDescriptor &V) {
113 return AddArg(V.getTypeName());
116 Diag &Diag::operator<<(const Value &V) {
117 if (V.getType().isSignedIntegerTy())
118 AddArg(V.getSIntValue());
119 else if (V.getType().isUnsignedIntegerTy())
120 AddArg(V.getUIntValue());
121 else if (V.getType().isFloatTy())
122 AddArg(V.getFloatValue());
128 /// Hexadecimal printing for numbers too large for Printf to handle directly.
129 static void RenderHex(InternalScopedString *Buffer, UIntMax Val) {
131 Buffer->append("0x%08x%08x%08x%08x", (unsigned int)(Val >> 96),
132 (unsigned int)(Val >> 64), (unsigned int)(Val >> 32),
133 (unsigned int)(Val));
135 UNREACHABLE("long long smaller than 64 bits?");
139 static void RenderLocation(InternalScopedString *Buffer, Location Loc) {
140 switch (Loc.getKind()) {
141 case Location::LK_Source: {
142 SourceLocation SLoc = Loc.getSourceLocation();
143 if (SLoc.isInvalid())
144 Buffer->append("<unknown>");
146 RenderSourceLocation(Buffer, SLoc.getFilename(), SLoc.getLine(),
147 SLoc.getColumn(), common_flags()->symbolize_vs_style,
148 common_flags()->strip_path_prefix);
151 case Location::LK_Memory:
152 Buffer->append("%p", Loc.getMemoryLocation());
154 case Location::LK_Symbolized: {
155 const AddressInfo &Info = Loc.getSymbolizedStack()->info;
157 RenderSourceLocation(Buffer, Info.file, Info.line, Info.column,
158 common_flags()->symbolize_vs_style,
159 common_flags()->strip_path_prefix);
160 else if (Info.module)
161 RenderModuleLocation(Buffer, Info.module, Info.module_offset,
162 Info.module_arch, common_flags()->strip_path_prefix);
164 Buffer->append("%p", Info.address);
167 case Location::LK_Null:
168 Buffer->append("<unknown>");
173 static void RenderText(InternalScopedString *Buffer, const char *Message,
174 const Diag::Arg *Args) {
175 for (const char *Msg = Message; *Msg; ++Msg) {
177 Buffer->append("%c", *Msg);
180 const Diag::Arg &A = Args[*++Msg - '0'];
182 case Diag::AK_String:
183 Buffer->append("%s", A.String);
185 case Diag::AK_TypeName: {
186 if (SANITIZER_WINDOWS)
187 // The Windows implementation demangles names early.
188 Buffer->append("'%s'", A.String);
190 Buffer->append("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
194 // 'long long' is guaranteed to be at least 64 bits wide.
195 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
196 Buffer->append("%lld", (long long)A.SInt);
198 RenderHex(Buffer, A.SInt);
201 if (A.UInt <= UINT64_MAX)
202 Buffer->append("%llu", (unsigned long long)A.UInt);
204 RenderHex(Buffer, A.UInt);
206 case Diag::AK_Float: {
207 // FIXME: Support floating-point formatting in sanitizer_common's
208 // printf, and stop using snprintf here.
209 char FloatBuffer[32];
210 #if SANITIZER_WINDOWS
211 sprintf_s(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
213 snprintf(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
215 Buffer->append("%s", FloatBuffer);
218 case Diag::AK_Pointer:
219 Buffer->append("%p", A.Pointer);
225 /// Find the earliest-starting range in Ranges which ends after Loc.
226 static Range *upperBound(MemoryLocation Loc, Range *Ranges,
227 unsigned NumRanges) {
229 for (unsigned I = 0; I != NumRanges; ++I)
230 if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
232 Best->getStart().getMemoryLocation() >
233 Ranges[I].getStart().getMemoryLocation()))
238 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
239 return (LHS < RHS) ? 0 : LHS - RHS;
242 static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
243 const uptr Limit = (uptr)-1;
244 return (LHS > Limit - RHS) ? Limit : LHS + RHS;
247 /// Render a snippet of the address space near a location.
248 static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
249 Range *Ranges, unsigned NumRanges,
250 const Diag::Arg *Args) {
251 // Show at least the 8 bytes surrounding Loc.
252 const unsigned MinBytesNearLoc = 4;
253 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
254 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
255 MemoryLocation OrigMin = Min;
256 for (unsigned I = 0; I < NumRanges; ++I) {
257 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
258 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
261 // If we have too many interesting bytes, prefer to show bytes after Loc.
262 const unsigned BytesToShow = 32;
263 if (Max - Min > BytesToShow)
264 Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
265 Max = addNoOverflow(Min, BytesToShow);
267 if (!IsAccessibleMemoryRange(Min, Max - Min)) {
268 Printf("<memory cannot be printed>\n");
273 InternalScopedString Buffer(1024);
274 for (uptr P = Min; P != Max; ++P) {
275 unsigned char C = *reinterpret_cast<const unsigned char*>(P);
276 Buffer.append("%s%02x", (P % 8 == 0) ? " " : " ", C);
281 Buffer.append(Decor.Highlight());
282 Range *InRange = upperBound(Min, Ranges, NumRanges);
283 for (uptr P = Min; P != Max; ++P) {
284 char Pad = ' ', Byte = ' ';
285 if (InRange && InRange->getEnd().getMemoryLocation() == P)
286 InRange = upperBound(P, Ranges, NumRanges);
287 if (!InRange && P > Loc)
289 if (InRange && InRange->getStart().getMemoryLocation() < P)
291 if (InRange && InRange->getStart().getMemoryLocation() <= P)
294 Buffer.append("%c", Pad);
295 Buffer.append("%c", Pad);
296 Buffer.append("%c", P == Loc ? '^' : Byte);
297 Buffer.append("%c", Byte);
299 Buffer.append("%s\n", Decor.Default());
301 // Go over the line again, and print names for the ranges.
304 for (uptr P = Min; P != Max; ++P) {
305 if (!InRange || InRange->getEnd().getMemoryLocation() == P)
306 InRange = upperBound(P, Ranges, NumRanges);
310 Spaces += (P % 8) == 0 ? 2 : 1;
312 if (InRange && InRange->getStart().getMemoryLocation() == P) {
315 RenderText(&Buffer, InRange->getText(), Args);
317 // FIXME: We only support naming one range for now!
324 Printf("%s", Buffer.data());
325 // FIXME: Print names for anything we can identify within the line:
327 // * If we can identify the memory itself as belonging to a particular
328 // global, stack variable, or dynamic allocation, then do so.
330 // * If we have a pointer-size, pointer-aligned range highlighted,
331 // determine whether the value of that range is a pointer to an
332 // entity which we can name, and if so, print that name.
334 // This needs an external symbolizer, or (preferably) ASan instrumentation.
338 // All diagnostics should be printed under report mutex.
339 ScopedReport::CheckLocked();
341 InternalScopedString Buffer(1024);
343 Buffer.append(Decor.Bold());
344 RenderLocation(&Buffer, Loc);
349 Buffer.append("%s runtime error: %s%s", Decor.Warning(), Decor.Default(),
354 Buffer.append("%s note: %s", Decor.Note(), Decor.Default());
358 RenderText(&Buffer, Message, Args);
360 Buffer.append("%s\n", Decor.Default());
361 Printf("%s", Buffer.data());
363 if (Loc.isMemoryLocation())
364 PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args);
367 ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); }
369 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,
371 : Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {}
373 ScopedReport::~ScopedReport() {
374 MaybePrintStackTrace(Opts.pc, Opts.bp);
375 MaybeReportErrorSummary(SummaryLoc, Type);
376 if (flags()->halt_on_error)
380 ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
381 static SuppressionContext *suppression_ctx = nullptr;
382 static const char kVptrCheck[] = "vptr_check";
383 static const char *kSuppressionTypes[] = {
384 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName,
385 #include "ubsan_checks.inc"
390 void __ubsan::InitializeSuppressions() {
391 CHECK_EQ(nullptr, suppression_ctx);
392 suppression_ctx = new (suppression_placeholder) // NOLINT
393 SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
394 suppression_ctx->ParseFromFile(flags()->suppressions);
397 bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
398 InitAsStandaloneIfNecessary();
399 CHECK(suppression_ctx);
401 return suppression_ctx->Match(TypeName, kVptrCheck, &s);
404 bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) {
405 InitAsStandaloneIfNecessary();
406 CHECK(suppression_ctx);
407 const char *SuppType = ConvertTypeToFlagName(ET);
408 // Fast path: don't symbolize PC if there is no suppressions for given UB
410 if (!suppression_ctx->HasSuppressionType(SuppType))
412 Suppression *s = nullptr;
413 // Suppress by file name known to runtime.
414 if (Filename != nullptr && suppression_ctx->Match(Filename, SuppType, &s))
416 // Suppress by module name.
417 if (const char *Module = Symbolizer::GetOrInit()->GetModuleNameForPc(PC)) {
418 if (suppression_ctx->Match(Module, SuppType, &s))
421 // Suppress by function or source file name from debug info.
422 SymbolizedStackHolder Stack(Symbolizer::GetOrInit()->SymbolizePC(PC));
423 const AddressInfo &AI = Stack.get()->info;
424 return suppression_ctx->Match(AI.function, SuppType, &s) ||
425 suppression_ctx->Match(AI.file, SuppType, &s);
428 #endif // CAN_SANITIZE_UB