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_symbolizer.h"
20 using namespace __ubsan
;
22 static void MaybePrintStackTrace(uptr pc
, uptr bp
) {
23 // We assume that flags are already parsed: InitIfNecessary
24 // will definitely be called when we print the first diagnostics message.
25 if (!flags()->print_stacktrace
)
27 // We can only use slow unwind, as we don't have any information about stack
29 // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
30 // fetch stack top/bottom information if we have it (e.g. if we're running
32 if (StackTrace::WillUseFastUnwind(false))
35 stack
.Unwind(kStackTraceMax
, pc
, bp
, 0, 0, 0, false);
39 static void MaybeReportErrorSummary(Location Loc
) {
40 if (!common_flags()->print_summary
)
42 // Don't try to unwind the stack trace in UBSan summaries: just use the
44 if (Loc
.isSourceLocation()) {
45 SourceLocation SLoc
= Loc
.getSourceLocation();
46 if (!SLoc
.isInvalid()) {
47 ReportErrorSummary("runtime-error", SLoc
.getFilename(), SLoc
.getLine(),
52 ReportErrorSummary("runtime-error");
56 class Decorator
: public SanitizerCommonDecorator
{
58 Decorator() : SanitizerCommonDecorator() {}
59 const char *Highlight() const { return Green(); }
60 const char *EndHighlight() const { return Default(); }
61 const char *Note() const { return Black(); }
62 const char *EndNote() const { return Default(); }
66 Location
__ubsan::getCallerLocation(uptr CallerLoc
) {
70 uptr Loc
= StackTrace::GetPreviousInstructionPc(CallerLoc
);
71 return getFunctionLocation(Loc
, 0);
74 Location
__ubsan::getFunctionLocation(uptr Loc
, const char **FName
) {
80 if (!Symbolizer::GetOrInit()->SymbolizePC(Loc
, &Info
, 1) || !Info
.module
||
84 if (FName
&& Info
.function
)
85 *FName
= Info
.function
;
88 return ModuleLocation(Info
.module
, Info
.module_offset
);
90 return SourceLocation(Info
.file
, Info
.line
, Info
.column
);
93 Diag
&Diag::operator<<(const TypeDescriptor
&V
) {
94 return AddArg(V
.getTypeName());
97 Diag
&Diag::operator<<(const Value
&V
) {
98 if (V
.getType().isSignedIntegerTy())
99 AddArg(V
.getSIntValue());
100 else if (V
.getType().isUnsignedIntegerTy())
101 AddArg(V
.getUIntValue());
102 else if (V
.getType().isFloatTy())
103 AddArg(V
.getFloatValue());
109 /// Hexadecimal printing for numbers too large for Printf to handle directly.
110 static void PrintHex(UIntMax Val
) {
112 Printf("0x%08x%08x%08x%08x",
113 (unsigned int)(Val
>> 96),
114 (unsigned int)(Val
>> 64),
115 (unsigned int)(Val
>> 32),
116 (unsigned int)(Val
));
118 UNREACHABLE("long long smaller than 64 bits?");
122 static void renderLocation(Location Loc
) {
123 InternalScopedString
LocBuffer(1024);
124 switch (Loc
.getKind()) {
125 case Location::LK_Source
: {
126 SourceLocation SLoc
= Loc
.getSourceLocation();
127 if (SLoc
.isInvalid())
128 LocBuffer
.append("<unknown>");
130 PrintSourceLocation(&LocBuffer
, SLoc
.getFilename(), SLoc
.getLine(),
134 case Location::LK_Module
:
135 PrintModuleAndOffset(&LocBuffer
, Loc
.getModuleLocation().getModuleName(),
136 Loc
.getModuleLocation().getOffset());
138 case Location::LK_Memory
:
139 LocBuffer
.append("%p", Loc
.getMemoryLocation());
141 case Location::LK_Null
:
142 LocBuffer
.append("<unknown>");
145 Printf("%s:", LocBuffer
.data());
148 static void renderText(const char *Message
, const Diag::Arg
*Args
) {
149 for (const char *Msg
= Message
; *Msg
; ++Msg
) {
153 for (I
= 0; Msg
[I
] && Msg
[I
] != '%' && I
!= 63; ++I
)
159 const Diag::Arg
&A
= Args
[*++Msg
- '0'];
161 case Diag::AK_String
:
162 Printf("%s", A
.String
);
164 case Diag::AK_Mangled
: {
165 Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A
.String
));
169 // 'long long' is guaranteed to be at least 64 bits wide.
170 if (A
.SInt
>= INT64_MIN
&& A
.SInt
<= INT64_MAX
)
171 Printf("%lld", (long long)A
.SInt
);
176 if (A
.UInt
<= UINT64_MAX
)
177 Printf("%llu", (unsigned long long)A
.UInt
);
181 case Diag::AK_Float
: {
182 // FIXME: Support floating-point formatting in sanitizer_common's
183 // printf, and stop using snprintf here.
185 snprintf(Buffer
, sizeof(Buffer
), "%Lg", (long double)A
.Float
);
186 Printf("%s", Buffer
);
189 case Diag::AK_Pointer
:
190 Printf("%p", A
.Pointer
);
197 /// Find the earliest-starting range in Ranges which ends after Loc.
198 static Range
*upperBound(MemoryLocation Loc
, Range
*Ranges
,
199 unsigned NumRanges
) {
201 for (unsigned I
= 0; I
!= NumRanges
; ++I
)
202 if (Ranges
[I
].getEnd().getMemoryLocation() > Loc
&&
204 Best
->getStart().getMemoryLocation() >
205 Ranges
[I
].getStart().getMemoryLocation()))
210 static inline uptr
subtractNoOverflow(uptr LHS
, uptr RHS
) {
211 return (LHS
< RHS
) ? 0 : LHS
- RHS
;
214 static inline uptr
addNoOverflow(uptr LHS
, uptr RHS
) {
215 const uptr Limit
= (uptr
)-1;
216 return (LHS
> Limit
- RHS
) ? Limit
: LHS
+ RHS
;
219 /// Render a snippet of the address space near a location.
220 static void renderMemorySnippet(const Decorator
&Decor
, MemoryLocation Loc
,
221 Range
*Ranges
, unsigned NumRanges
,
222 const Diag::Arg
*Args
) {
223 // Show at least the 8 bytes surrounding Loc.
224 const unsigned MinBytesNearLoc
= 4;
225 MemoryLocation Min
= subtractNoOverflow(Loc
, MinBytesNearLoc
);
226 MemoryLocation Max
= addNoOverflow(Loc
, MinBytesNearLoc
);
227 MemoryLocation OrigMin
= Min
;
228 for (unsigned I
= 0; I
< NumRanges
; ++I
) {
229 Min
= __sanitizer::Min(Ranges
[I
].getStart().getMemoryLocation(), Min
);
230 Max
= __sanitizer::Max(Ranges
[I
].getEnd().getMemoryLocation(), Max
);
233 // If we have too many interesting bytes, prefer to show bytes after Loc.
234 const unsigned BytesToShow
= 32;
235 if (Max
- Min
> BytesToShow
)
236 Min
= __sanitizer::Min(Max
- BytesToShow
, OrigMin
);
237 Max
= addNoOverflow(Min
, BytesToShow
);
239 if (!IsAccessibleMemoryRange(Min
, Max
- Min
)) {
240 Printf("<memory cannot be printed>\n");
245 for (uptr P
= Min
; P
!= Max
; ++P
) {
246 unsigned char C
= *reinterpret_cast<const unsigned char*>(P
);
247 Printf("%s%02x", (P
% 8 == 0) ? " " : " ", C
);
252 Printf(Decor
.Highlight());
253 Range
*InRange
= upperBound(Min
, Ranges
, NumRanges
);
254 for (uptr P
= Min
; P
!= Max
; ++P
) {
255 char Pad
= ' ', Byte
= ' ';
256 if (InRange
&& InRange
->getEnd().getMemoryLocation() == P
)
257 InRange
= upperBound(P
, Ranges
, NumRanges
);
258 if (!InRange
&& P
> Loc
)
260 if (InRange
&& InRange
->getStart().getMemoryLocation() < P
)
262 if (InRange
&& InRange
->getStart().getMemoryLocation() <= P
)
264 char Buffer
[] = { Pad
, Pad
, P
== Loc
? '^' : Byte
, Byte
, 0 };
265 Printf((P
% 8 == 0) ? Buffer
: &Buffer
[1]);
267 Printf("%s\n", Decor
.EndHighlight());
269 // Go over the line again, and print names for the ranges.
272 for (uptr P
= Min
; P
!= Max
; ++P
) {
273 if (!InRange
|| InRange
->getEnd().getMemoryLocation() == P
)
274 InRange
= upperBound(P
, Ranges
, NumRanges
);
278 Spaces
+= (P
% 8) == 0 ? 2 : 1;
280 if (InRange
&& InRange
->getStart().getMemoryLocation() == P
) {
283 renderText(InRange
->getText(), Args
);
285 // FIXME: We only support naming one range for now!
292 // FIXME: Print names for anything we can identify within the line:
294 // * If we can identify the memory itself as belonging to a particular
295 // global, stack variable, or dynamic allocation, then do so.
297 // * If we have a pointer-size, pointer-aligned range highlighted,
298 // determine whether the value of that range is a pointer to an
299 // entity which we can name, and if so, print that name.
301 // This needs an external symbolizer, or (preferably) ASan instrumentation.
305 // All diagnostics should be printed under report mutex.
306 CommonSanitizerReportMutex
.CheckLocked();
308 Printf(Decor
.Bold());
314 Printf("%s runtime error: %s%s",
315 Decor
.Warning(), Decor
.EndWarning(), Decor
.Bold());
319 Printf("%s note: %s", Decor
.Note(), Decor
.EndNote());
323 renderText(Message
, Args
);
325 Printf("%s\n", Decor
.Default());
327 if (Loc
.isMemoryLocation())
328 renderMemorySnippet(Decor
, Loc
.getMemoryLocation(), Ranges
,
332 ScopedReport::ScopedReport(ReportOptions Opts
, Location SummaryLoc
)
333 : Opts(Opts
), SummaryLoc(SummaryLoc
) {
335 CommonSanitizerReportMutex
.Lock();
338 ScopedReport::~ScopedReport() {
339 MaybePrintStackTrace(Opts
.pc
, Opts
.bp
);
340 MaybeReportErrorSummary(SummaryLoc
);
341 CommonSanitizerReportMutex
.Unlock();
342 if (Opts
.DieAfterReport
|| flags()->halt_on_error
)
346 bool __ubsan::MatchSuppression(const char *Str
, SuppressionType Type
) {
348 // If .preinit_array is not used, it is possible that the UBSan runtime is not
350 if (!SANITIZER_CAN_USE_PREINIT_ARRAY
)
352 return SuppressionContext::Get()->Match(Str
, Type
, &s
);