1 //===-- ubsan_diag.cc -----------------------------------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // Diagnostic reporting for the UBSan runtime.
10 //===----------------------------------------------------------------------===//
12 #include "ubsan_diag.h"
13 #include "ubsan_init.h"
14 #include "ubsan_flags.h"
15 #include "sanitizer_common/sanitizer_report_decorator.h"
16 #include "sanitizer_common/sanitizer_stacktrace.h"
17 #include "sanitizer_common/sanitizer_stacktrace_printer.h"
18 #include "sanitizer_common/sanitizer_symbolizer.h"
21 using namespace __ubsan
;
23 static void MaybePrintStackTrace(uptr pc
, uptr bp
) {
24 // We assume that flags are already parsed: InitIfNecessary
25 // will definitely be called when we print the first diagnostics message.
26 if (!flags()->print_stacktrace
)
28 // We can only use slow unwind, as we don't have any information about stack
30 // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
31 // fetch stack top/bottom information if we have it (e.g. if we're running
33 if (StackTrace::WillUseFastUnwind(false))
35 BufferedStackTrace stack
;
36 stack
.Unwind(kStackTraceMax
, pc
, bp
, 0, 0, 0, false);
40 static void MaybeReportErrorSummary(Location Loc
) {
41 if (!common_flags()->print_summary
)
43 // Don't try to unwind the stack trace in UBSan summaries: just use the
45 if (Loc
.isSourceLocation()) {
46 SourceLocation SLoc
= Loc
.getSourceLocation();
47 if (!SLoc
.isInvalid()) {
48 ReportErrorSummary("undefined-behavior", SLoc
.getFilename(),
53 ReportErrorSummary("undefined-behavior");
57 class Decorator
: public SanitizerCommonDecorator
{
59 Decorator() : SanitizerCommonDecorator() {}
60 const char *Highlight() const { return Green(); }
61 const char *EndHighlight() const { return Default(); }
62 const char *Note() const { return Black(); }
63 const char *EndNote() const { return Default(); }
67 Location
__ubsan::getCallerLocation(uptr CallerLoc
) {
71 uptr Loc
= StackTrace::GetPreviousInstructionPc(CallerLoc
);
72 return getFunctionLocation(Loc
, 0);
75 Location
__ubsan::getFunctionLocation(uptr Loc
, const char **FName
) {
81 if (!Symbolizer::GetOrInit()->SymbolizePC(Loc
, &Info
, 1) || !Info
.module
||
85 if (FName
&& Info
.function
)
86 *FName
= Info
.function
;
89 return ModuleLocation(Info
.module
, Info
.module_offset
);
91 return SourceLocation(Info
.file
, Info
.line
, Info
.column
);
94 Diag
&Diag::operator<<(const TypeDescriptor
&V
) {
95 return AddArg(V
.getTypeName());
98 Diag
&Diag::operator<<(const Value
&V
) {
99 if (V
.getType().isSignedIntegerTy())
100 AddArg(V
.getSIntValue());
101 else if (V
.getType().isUnsignedIntegerTy())
102 AddArg(V
.getUIntValue());
103 else if (V
.getType().isFloatTy())
104 AddArg(V
.getFloatValue());
110 /// Hexadecimal printing for numbers too large for Printf to handle directly.
111 static void PrintHex(UIntMax Val
) {
113 Printf("0x%08x%08x%08x%08x",
114 (unsigned int)(Val
>> 96),
115 (unsigned int)(Val
>> 64),
116 (unsigned int)(Val
>> 32),
117 (unsigned int)(Val
));
119 UNREACHABLE("long long smaller than 64 bits?");
123 static void renderLocation(Location Loc
) {
124 InternalScopedString
LocBuffer(1024);
125 switch (Loc
.getKind()) {
126 case Location::LK_Source
: {
127 SourceLocation SLoc
= Loc
.getSourceLocation();
128 if (SLoc
.isInvalid())
129 LocBuffer
.append("<unknown>");
131 RenderSourceLocation(&LocBuffer
, SLoc
.getFilename(), SLoc
.getLine(),
132 SLoc
.getColumn(), common_flags()->strip_path_prefix
);
135 case Location::LK_Module
: {
136 ModuleLocation MLoc
= Loc
.getModuleLocation();
137 RenderModuleLocation(&LocBuffer
, MLoc
.getModuleName(), MLoc
.getOffset(),
138 common_flags()->strip_path_prefix
);
141 case Location::LK_Memory
:
142 LocBuffer
.append("%p", Loc
.getMemoryLocation());
144 case Location::LK_Null
:
145 LocBuffer
.append("<unknown>");
148 Printf("%s:", LocBuffer
.data());
151 static void renderText(const char *Message
, const Diag::Arg
*Args
) {
152 for (const char *Msg
= Message
; *Msg
; ++Msg
) {
156 for (I
= 0; Msg
[I
] && Msg
[I
] != '%' && I
!= 63; ++I
)
162 const Diag::Arg
&A
= Args
[*++Msg
- '0'];
164 case Diag::AK_String
:
165 Printf("%s", A
.String
);
167 case Diag::AK_Mangled
: {
168 Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A
.String
));
172 // 'long long' is guaranteed to be at least 64 bits wide.
173 if (A
.SInt
>= INT64_MIN
&& A
.SInt
<= INT64_MAX
)
174 Printf("%lld", (long long)A
.SInt
);
179 if (A
.UInt
<= UINT64_MAX
)
180 Printf("%llu", (unsigned long long)A
.UInt
);
184 case Diag::AK_Float
: {
185 // FIXME: Support floating-point formatting in sanitizer_common's
186 // printf, and stop using snprintf here.
188 snprintf(Buffer
, sizeof(Buffer
), "%Lg", (long double)A
.Float
);
189 Printf("%s", Buffer
);
192 case Diag::AK_Pointer
:
193 Printf("%p", A
.Pointer
);
200 /// Find the earliest-starting range in Ranges which ends after Loc.
201 static Range
*upperBound(MemoryLocation Loc
, Range
*Ranges
,
202 unsigned NumRanges
) {
204 for (unsigned I
= 0; I
!= NumRanges
; ++I
)
205 if (Ranges
[I
].getEnd().getMemoryLocation() > Loc
&&
207 Best
->getStart().getMemoryLocation() >
208 Ranges
[I
].getStart().getMemoryLocation()))
213 static inline uptr
subtractNoOverflow(uptr LHS
, uptr RHS
) {
214 return (LHS
< RHS
) ? 0 : LHS
- RHS
;
217 static inline uptr
addNoOverflow(uptr LHS
, uptr RHS
) {
218 const uptr Limit
= (uptr
)-1;
219 return (LHS
> Limit
- RHS
) ? Limit
: LHS
+ RHS
;
222 /// Render a snippet of the address space near a location.
223 static void renderMemorySnippet(const Decorator
&Decor
, MemoryLocation Loc
,
224 Range
*Ranges
, unsigned NumRanges
,
225 const Diag::Arg
*Args
) {
226 // Show at least the 8 bytes surrounding Loc.
227 const unsigned MinBytesNearLoc
= 4;
228 MemoryLocation Min
= subtractNoOverflow(Loc
, MinBytesNearLoc
);
229 MemoryLocation Max
= addNoOverflow(Loc
, MinBytesNearLoc
);
230 MemoryLocation OrigMin
= Min
;
231 for (unsigned I
= 0; I
< NumRanges
; ++I
) {
232 Min
= __sanitizer::Min(Ranges
[I
].getStart().getMemoryLocation(), Min
);
233 Max
= __sanitizer::Max(Ranges
[I
].getEnd().getMemoryLocation(), Max
);
236 // If we have too many interesting bytes, prefer to show bytes after Loc.
237 const unsigned BytesToShow
= 32;
238 if (Max
- Min
> BytesToShow
)
239 Min
= __sanitizer::Min(Max
- BytesToShow
, OrigMin
);
240 Max
= addNoOverflow(Min
, BytesToShow
);
242 if (!IsAccessibleMemoryRange(Min
, Max
- Min
)) {
243 Printf("<memory cannot be printed>\n");
248 for (uptr P
= Min
; P
!= Max
; ++P
) {
249 unsigned char C
= *reinterpret_cast<const unsigned char*>(P
);
250 Printf("%s%02x", (P
% 8 == 0) ? " " : " ", C
);
255 Printf(Decor
.Highlight());
256 Range
*InRange
= upperBound(Min
, Ranges
, NumRanges
);
257 for (uptr P
= Min
; P
!= Max
; ++P
) {
258 char Pad
= ' ', Byte
= ' ';
259 if (InRange
&& InRange
->getEnd().getMemoryLocation() == P
)
260 InRange
= upperBound(P
, Ranges
, NumRanges
);
261 if (!InRange
&& P
> Loc
)
263 if (InRange
&& InRange
->getStart().getMemoryLocation() < P
)
265 if (InRange
&& InRange
->getStart().getMemoryLocation() <= P
)
267 char Buffer
[] = { Pad
, Pad
, P
== Loc
? '^' : Byte
, Byte
, 0 };
268 Printf((P
% 8 == 0) ? Buffer
: &Buffer
[1]);
270 Printf("%s\n", Decor
.EndHighlight());
272 // Go over the line again, and print names for the ranges.
275 for (uptr P
= Min
; P
!= Max
; ++P
) {
276 if (!InRange
|| InRange
->getEnd().getMemoryLocation() == P
)
277 InRange
= upperBound(P
, Ranges
, NumRanges
);
281 Spaces
+= (P
% 8) == 0 ? 2 : 1;
283 if (InRange
&& InRange
->getStart().getMemoryLocation() == P
) {
286 renderText(InRange
->getText(), Args
);
288 // FIXME: We only support naming one range for now!
295 // FIXME: Print names for anything we can identify within the line:
297 // * If we can identify the memory itself as belonging to a particular
298 // global, stack variable, or dynamic allocation, then do so.
300 // * If we have a pointer-size, pointer-aligned range highlighted,
301 // determine whether the value of that range is a pointer to an
302 // entity which we can name, and if so, print that name.
304 // This needs an external symbolizer, or (preferably) ASan instrumentation.
308 // All diagnostics should be printed under report mutex.
309 CommonSanitizerReportMutex
.CheckLocked();
311 Printf(Decor
.Bold());
317 Printf("%s runtime error: %s%s",
318 Decor
.Warning(), Decor
.EndWarning(), Decor
.Bold());
322 Printf("%s note: %s", Decor
.Note(), Decor
.EndNote());
326 renderText(Message
, Args
);
328 Printf("%s\n", Decor
.Default());
330 if (Loc
.isMemoryLocation())
331 renderMemorySnippet(Decor
, Loc
.getMemoryLocation(), Ranges
,
335 ScopedReport::ScopedReport(ReportOptions Opts
, Location SummaryLoc
)
336 : Opts(Opts
), SummaryLoc(SummaryLoc
) {
338 CommonSanitizerReportMutex
.Lock();
341 ScopedReport::~ScopedReport() {
342 MaybePrintStackTrace(Opts
.pc
, Opts
.bp
);
343 MaybeReportErrorSummary(SummaryLoc
);
344 CommonSanitizerReportMutex
.Unlock();
345 if (Opts
.DieAfterReport
|| flags()->halt_on_error
)
349 bool __ubsan::MatchSuppression(const char *Str
, SuppressionType Type
) {
351 // If .preinit_array is not used, it is possible that the UBSan runtime is not
353 if (!SANITIZER_CAN_USE_PREINIT_ARRAY
)
355 return SuppressionContext::Get()->Match(Str
, Type
, &s
);