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_diag.h"
15 #include "ubsan_init.h"
16 #include "ubsan_flags.h"
17 #include "sanitizer_common/sanitizer_report_decorator.h"
18 #include "sanitizer_common/sanitizer_stacktrace.h"
19 #include "sanitizer_common/sanitizer_stacktrace_printer.h"
20 #include "sanitizer_common/sanitizer_symbolizer.h"
23 using namespace __ubsan;
25 static void MaybePrintStackTrace(uptr pc, uptr bp) {
26 // We assume that flags are already parsed: InitIfNecessary
27 // will definitely be called when we print the first diagnostics message.
28 if (!flags()->print_stacktrace)
30 // We can only use slow unwind, as we don't have any information about stack
32 // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
33 // fetch stack top/bottom information if we have it (e.g. if we're running
35 if (StackTrace::WillUseFastUnwind(false))
37 BufferedStackTrace stack;
38 stack.Unwind(kStackTraceMax, pc, bp, 0, 0, 0, false);
42 static void MaybeReportErrorSummary(Location Loc) {
43 if (!common_flags()->print_summary)
45 // Don't try to unwind the stack trace in UBSan summaries: just use the
47 if (Loc.isSourceLocation()) {
48 SourceLocation SLoc = Loc.getSourceLocation();
49 if (!SLoc.isInvalid()) {
50 ReportErrorSummary("undefined-behavior", SLoc.getFilename(),
55 ReportErrorSummary("undefined-behavior");
59 class Decorator : public SanitizerCommonDecorator {
61 Decorator() : SanitizerCommonDecorator() {}
62 const char *Highlight() const { return Green(); }
63 const char *EndHighlight() const { return Default(); }
64 const char *Note() const { return Black(); }
65 const char *EndNote() const { return Default(); }
69 Location __ubsan::getCallerLocation(uptr CallerLoc) {
73 uptr Loc = StackTrace::GetPreviousInstructionPc(CallerLoc);
74 return getFunctionLocation(Loc, 0);
77 Location __ubsan::getFunctionLocation(uptr Loc, const char **FName) {
82 SymbolizedStack *Frames = Symbolizer::GetOrInit()->SymbolizePC(Loc);
83 const AddressInfo &Info = Frames->info;
90 if (FName && Info.function)
91 *FName = internal_strdup(Info.function);
94 ModuleLocation MLoc(internal_strdup(Info.module), Info.module_offset);
99 SourceLocation SLoc(internal_strdup(Info.file), Info.line, Info.column);
104 Diag &Diag::operator<<(const TypeDescriptor &V) {
105 return AddArg(V.getTypeName());
108 Diag &Diag::operator<<(const Value &V) {
109 if (V.getType().isSignedIntegerTy())
110 AddArg(V.getSIntValue());
111 else if (V.getType().isUnsignedIntegerTy())
112 AddArg(V.getUIntValue());
113 else if (V.getType().isFloatTy())
114 AddArg(V.getFloatValue());
120 /// Hexadecimal printing for numbers too large for Printf to handle directly.
121 static void PrintHex(UIntMax Val) {
123 Printf("0x%08x%08x%08x%08x",
124 (unsigned int)(Val >> 96),
125 (unsigned int)(Val >> 64),
126 (unsigned int)(Val >> 32),
127 (unsigned int)(Val));
129 UNREACHABLE("long long smaller than 64 bits?");
133 static void renderLocation(Location Loc) {
134 InternalScopedString LocBuffer(1024);
135 switch (Loc.getKind()) {
136 case Location::LK_Source: {
137 SourceLocation SLoc = Loc.getSourceLocation();
138 if (SLoc.isInvalid())
139 LocBuffer.append("<unknown>");
141 RenderSourceLocation(&LocBuffer, SLoc.getFilename(), SLoc.getLine(),
142 SLoc.getColumn(), common_flags()->strip_path_prefix);
145 case Location::LK_Module: {
146 ModuleLocation MLoc = Loc.getModuleLocation();
147 RenderModuleLocation(&LocBuffer, MLoc.getModuleName(), MLoc.getOffset(),
148 common_flags()->strip_path_prefix);
151 case Location::LK_Memory:
152 LocBuffer.append("%p", Loc.getMemoryLocation());
154 case Location::LK_Null:
155 LocBuffer.append("<unknown>");
158 Printf("%s:", LocBuffer.data());
161 static void renderText(const char *Message, const Diag::Arg *Args) {
162 for (const char *Msg = Message; *Msg; ++Msg) {
166 for (I = 0; Msg[I] && Msg[I] != '%' && I != 63; ++I)
172 const Diag::Arg &A = Args[*++Msg - '0'];
174 case Diag::AK_String:
175 Printf("%s", A.String);
177 case Diag::AK_Mangled: {
178 Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
182 // 'long long' is guaranteed to be at least 64 bits wide.
183 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
184 Printf("%lld", (long long)A.SInt);
189 if (A.UInt <= UINT64_MAX)
190 Printf("%llu", (unsigned long long)A.UInt);
194 case Diag::AK_Float: {
195 // FIXME: Support floating-point formatting in sanitizer_common's
196 // printf, and stop using snprintf here.
198 snprintf(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float);
199 Printf("%s", Buffer);
202 case Diag::AK_Pointer:
203 Printf("%p", A.Pointer);
210 /// Find the earliest-starting range in Ranges which ends after Loc.
211 static Range *upperBound(MemoryLocation Loc, Range *Ranges,
212 unsigned NumRanges) {
214 for (unsigned I = 0; I != NumRanges; ++I)
215 if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
217 Best->getStart().getMemoryLocation() >
218 Ranges[I].getStart().getMemoryLocation()))
223 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
224 return (LHS < RHS) ? 0 : LHS - RHS;
227 static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
228 const uptr Limit = (uptr)-1;
229 return (LHS > Limit - RHS) ? Limit : LHS + RHS;
232 /// Render a snippet of the address space near a location.
233 static void renderMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
234 Range *Ranges, unsigned NumRanges,
235 const Diag::Arg *Args) {
236 // Show at least the 8 bytes surrounding Loc.
237 const unsigned MinBytesNearLoc = 4;
238 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
239 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
240 MemoryLocation OrigMin = Min;
241 for (unsigned I = 0; I < NumRanges; ++I) {
242 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
243 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
246 // If we have too many interesting bytes, prefer to show bytes after Loc.
247 const unsigned BytesToShow = 32;
248 if (Max - Min > BytesToShow)
249 Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
250 Max = addNoOverflow(Min, BytesToShow);
252 if (!IsAccessibleMemoryRange(Min, Max - Min)) {
253 Printf("<memory cannot be printed>\n");
258 for (uptr P = Min; P != Max; ++P) {
259 unsigned char C = *reinterpret_cast<const unsigned char*>(P);
260 Printf("%s%02x", (P % 8 == 0) ? " " : " ", C);
265 Printf(Decor.Highlight());
266 Range *InRange = upperBound(Min, Ranges, NumRanges);
267 for (uptr P = Min; P != Max; ++P) {
268 char Pad = ' ', Byte = ' ';
269 if (InRange && InRange->getEnd().getMemoryLocation() == P)
270 InRange = upperBound(P, Ranges, NumRanges);
271 if (!InRange && P > Loc)
273 if (InRange && InRange->getStart().getMemoryLocation() < P)
275 if (InRange && InRange->getStart().getMemoryLocation() <= P)
277 char Buffer[] = { Pad, Pad, P == Loc ? '^' : Byte, Byte, 0 };
278 Printf((P % 8 == 0) ? Buffer : &Buffer[1]);
280 Printf("%s\n", Decor.EndHighlight());
282 // Go over the line again, and print names for the ranges.
285 for (uptr P = Min; P != Max; ++P) {
286 if (!InRange || InRange->getEnd().getMemoryLocation() == P)
287 InRange = upperBound(P, Ranges, NumRanges);
291 Spaces += (P % 8) == 0 ? 2 : 1;
293 if (InRange && InRange->getStart().getMemoryLocation() == P) {
296 renderText(InRange->getText(), Args);
298 // FIXME: We only support naming one range for now!
305 // FIXME: Print names for anything we can identify within the line:
307 // * If we can identify the memory itself as belonging to a particular
308 // global, stack variable, or dynamic allocation, then do so.
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.
314 // This needs an external symbolizer, or (preferably) ASan instrumentation.
318 // All diagnostics should be printed under report mutex.
319 CommonSanitizerReportMutex.CheckLocked();
321 Printf(Decor.Bold());
327 Printf("%s runtime error: %s%s",
328 Decor.Warning(), Decor.EndWarning(), Decor.Bold());
332 Printf("%s note: %s", Decor.Note(), Decor.EndNote());
336 renderText(Message, Args);
338 Printf("%s\n", Decor.Default());
340 if (Loc.isMemoryLocation())
341 renderMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges,
345 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc)
346 : Opts(Opts), SummaryLoc(SummaryLoc) {
348 CommonSanitizerReportMutex.Lock();
351 ScopedReport::~ScopedReport() {
352 MaybePrintStackTrace(Opts.pc, Opts.bp);
353 MaybeReportErrorSummary(SummaryLoc);
354 CommonSanitizerReportMutex.Unlock();
355 if (Opts.DieAfterReport || flags()->halt_on_error)
359 bool __ubsan::MatchSuppression(const char *Str, SuppressionType Type) {
361 // If .preinit_array is not used, it is possible that the UBSan runtime is not
363 if (!SANITIZER_CAN_USE_PREINIT_ARRAY)
365 return SuppressionContext::Get()->Match(Str, Type, &s);