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_platform.h"
14 #include "ubsan_diag.h"
15 #include "ubsan_init.h"
16 #include "ubsan_flags.h"
17 #include "sanitizer_common/sanitizer_placement_new.h"
18 #include "sanitizer_common/sanitizer_report_decorator.h"
19 #include "sanitizer_common/sanitizer_stacktrace.h"
20 #include "sanitizer_common/sanitizer_stacktrace_printer.h"
21 #include "sanitizer_common/sanitizer_suppressions.h"
22 #include "sanitizer_common/sanitizer_symbolizer.h"
25 using namespace __ubsan
;
27 static void MaybePrintStackTrace(uptr pc
, uptr bp
) {
28 // We assume that flags are already parsed, as UBSan runtime
29 // will definitely be called when we print the first diagnostics message.
30 if (!flags()->print_stacktrace
)
32 // We can only use slow unwind, as we don't have any information about stack
34 // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
35 // fetch stack top/bottom information if we have it (e.g. if we're running
37 if (StackTrace::WillUseFastUnwind(false))
39 BufferedStackTrace stack
;
40 stack
.Unwind(kStackTraceMax
, pc
, bp
, 0, 0, 0, false);
44 static const char *ConvertTypeToString(ErrorType Type
) {
46 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
47 case ErrorType::Name: \
49 #include "ubsan_checks.inc"
52 UNREACHABLE("unknown ErrorType!");
55 static const char *ConvertTypeToFlagName(ErrorType Type
) {
57 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \
58 case ErrorType::Name: \
59 return FSanitizeFlagName;
60 #include "ubsan_checks.inc"
63 UNREACHABLE("unknown ErrorType!");
66 static void MaybeReportErrorSummary(Location Loc
, ErrorType Type
) {
67 if (!common_flags()->print_summary
)
69 if (!flags()->report_error_type
)
70 Type
= ErrorType::GenericUB
;
71 const char *ErrorKind
= ConvertTypeToString(Type
);
72 if (Loc
.isSourceLocation()) {
73 SourceLocation SLoc
= Loc
.getSourceLocation();
74 if (!SLoc
.isInvalid()) {
76 AI
.file
= internal_strdup(SLoc
.getFilename());
77 AI
.line
= SLoc
.getLine();
78 AI
.column
= SLoc
.getColumn();
79 AI
.function
= internal_strdup(""); // Avoid printing ?? as function name.
80 ReportErrorSummary(ErrorKind
, AI
);
84 } else if (Loc
.isSymbolizedStack()) {
85 const AddressInfo
&AI
= Loc
.getSymbolizedStack()->info
;
86 ReportErrorSummary(ErrorKind
, AI
);
89 ReportErrorSummary(ErrorKind
);
93 class Decorator
: public SanitizerCommonDecorator
{
95 Decorator() : SanitizerCommonDecorator() {}
96 const char *Highlight() const { return Green(); }
97 const char *EndHighlight() const { return Default(); }
98 const char *Note() const { return Black(); }
99 const char *EndNote() const { return Default(); }
103 SymbolizedStack
*__ubsan::getSymbolizedLocation(uptr PC
) {
104 InitAsStandaloneIfNecessary();
105 return Symbolizer::GetOrInit()->SymbolizePC(PC
);
108 Diag
&Diag::operator<<(const TypeDescriptor
&V
) {
109 return AddArg(V
.getTypeName());
112 Diag
&Diag::operator<<(const Value
&V
) {
113 if (V
.getType().isSignedIntegerTy())
114 AddArg(V
.getSIntValue());
115 else if (V
.getType().isUnsignedIntegerTy())
116 AddArg(V
.getUIntValue());
117 else if (V
.getType().isFloatTy())
118 AddArg(V
.getFloatValue());
124 /// Hexadecimal printing for numbers too large for Printf to handle directly.
125 static void RenderHex(InternalScopedString
*Buffer
, UIntMax Val
) {
127 Buffer
->append("0x%08x%08x%08x%08x", (unsigned int)(Val
>> 96),
128 (unsigned int)(Val
>> 64), (unsigned int)(Val
>> 32),
129 (unsigned int)(Val
));
131 UNREACHABLE("long long smaller than 64 bits?");
135 static void RenderLocation(InternalScopedString
*Buffer
, Location Loc
) {
136 switch (Loc
.getKind()) {
137 case Location::LK_Source
: {
138 SourceLocation SLoc
= Loc
.getSourceLocation();
139 if (SLoc
.isInvalid())
140 Buffer
->append("<unknown>");
142 RenderSourceLocation(Buffer
, SLoc
.getFilename(), SLoc
.getLine(),
143 SLoc
.getColumn(), common_flags()->symbolize_vs_style
,
144 common_flags()->strip_path_prefix
);
147 case Location::LK_Memory
:
148 Buffer
->append("%p", Loc
.getMemoryLocation());
150 case Location::LK_Symbolized
: {
151 const AddressInfo
&Info
= Loc
.getSymbolizedStack()->info
;
153 RenderSourceLocation(Buffer
, Info
.file
, Info
.line
, Info
.column
,
154 common_flags()->symbolize_vs_style
,
155 common_flags()->strip_path_prefix
);
156 else if (Info
.module
)
157 RenderModuleLocation(Buffer
, Info
.module
, Info
.module_offset
,
158 common_flags()->strip_path_prefix
);
160 Buffer
->append("%p", Info
.address
);
163 case Location::LK_Null
:
164 Buffer
->append("<unknown>");
169 static void RenderText(InternalScopedString
*Buffer
, const char *Message
,
170 const Diag::Arg
*Args
) {
171 for (const char *Msg
= Message
; *Msg
; ++Msg
) {
173 Buffer
->append("%c", *Msg
);
176 const Diag::Arg
&A
= Args
[*++Msg
- '0'];
178 case Diag::AK_String
:
179 Buffer
->append("%s", A
.String
);
181 case Diag::AK_TypeName
: {
182 if (SANITIZER_WINDOWS
)
183 // The Windows implementation demangles names early.
184 Buffer
->append("'%s'", A
.String
);
186 Buffer
->append("'%s'", Symbolizer::GetOrInit()->Demangle(A
.String
));
190 // 'long long' is guaranteed to be at least 64 bits wide.
191 if (A
.SInt
>= INT64_MIN
&& A
.SInt
<= INT64_MAX
)
192 Buffer
->append("%lld", (long long)A
.SInt
);
194 RenderHex(Buffer
, A
.SInt
);
197 if (A
.UInt
<= UINT64_MAX
)
198 Buffer
->append("%llu", (unsigned long long)A
.UInt
);
200 RenderHex(Buffer
, A
.UInt
);
202 case Diag::AK_Float
: {
203 // FIXME: Support floating-point formatting in sanitizer_common's
204 // printf, and stop using snprintf here.
205 char FloatBuffer
[32];
206 #if SANITIZER_WINDOWS
207 sprintf_s(FloatBuffer
, sizeof(FloatBuffer
), "%Lg", (long double)A
.Float
);
209 snprintf(FloatBuffer
, sizeof(FloatBuffer
), "%Lg", (long double)A
.Float
);
211 Buffer
->append("%s", FloatBuffer
);
214 case Diag::AK_Pointer
:
215 Buffer
->append("%p", A
.Pointer
);
221 /// Find the earliest-starting range in Ranges which ends after Loc.
222 static Range
*upperBound(MemoryLocation Loc
, Range
*Ranges
,
223 unsigned NumRanges
) {
225 for (unsigned I
= 0; I
!= NumRanges
; ++I
)
226 if (Ranges
[I
].getEnd().getMemoryLocation() > Loc
&&
228 Best
->getStart().getMemoryLocation() >
229 Ranges
[I
].getStart().getMemoryLocation()))
234 static inline uptr
subtractNoOverflow(uptr LHS
, uptr RHS
) {
235 return (LHS
< RHS
) ? 0 : LHS
- RHS
;
238 static inline uptr
addNoOverflow(uptr LHS
, uptr RHS
) {
239 const uptr Limit
= (uptr
)-1;
240 return (LHS
> Limit
- RHS
) ? Limit
: LHS
+ RHS
;
243 /// Render a snippet of the address space near a location.
244 static void PrintMemorySnippet(const Decorator
&Decor
, MemoryLocation Loc
,
245 Range
*Ranges
, unsigned NumRanges
,
246 const Diag::Arg
*Args
) {
247 // Show at least the 8 bytes surrounding Loc.
248 const unsigned MinBytesNearLoc
= 4;
249 MemoryLocation Min
= subtractNoOverflow(Loc
, MinBytesNearLoc
);
250 MemoryLocation Max
= addNoOverflow(Loc
, MinBytesNearLoc
);
251 MemoryLocation OrigMin
= Min
;
252 for (unsigned I
= 0; I
< NumRanges
; ++I
) {
253 Min
= __sanitizer::Min(Ranges
[I
].getStart().getMemoryLocation(), Min
);
254 Max
= __sanitizer::Max(Ranges
[I
].getEnd().getMemoryLocation(), Max
);
257 // If we have too many interesting bytes, prefer to show bytes after Loc.
258 const unsigned BytesToShow
= 32;
259 if (Max
- Min
> BytesToShow
)
260 Min
= __sanitizer::Min(Max
- BytesToShow
, OrigMin
);
261 Max
= addNoOverflow(Min
, BytesToShow
);
263 if (!IsAccessibleMemoryRange(Min
, Max
- Min
)) {
264 Printf("<memory cannot be printed>\n");
269 InternalScopedString
Buffer(1024);
270 for (uptr P
= Min
; P
!= Max
; ++P
) {
271 unsigned char C
= *reinterpret_cast<const unsigned char*>(P
);
272 Buffer
.append("%s%02x", (P
% 8 == 0) ? " " : " ", C
);
277 Buffer
.append(Decor
.Highlight());
278 Range
*InRange
= upperBound(Min
, Ranges
, NumRanges
);
279 for (uptr P
= Min
; P
!= Max
; ++P
) {
280 char Pad
= ' ', Byte
= ' ';
281 if (InRange
&& InRange
->getEnd().getMemoryLocation() == P
)
282 InRange
= upperBound(P
, Ranges
, NumRanges
);
283 if (!InRange
&& P
> Loc
)
285 if (InRange
&& InRange
->getStart().getMemoryLocation() < P
)
287 if (InRange
&& InRange
->getStart().getMemoryLocation() <= P
)
290 Buffer
.append("%c", Pad
);
291 Buffer
.append("%c", Pad
);
292 Buffer
.append("%c", P
== Loc
? '^' : Byte
);
293 Buffer
.append("%c", Byte
);
295 Buffer
.append("%s\n", Decor
.EndHighlight());
297 // Go over the line again, and print names for the ranges.
300 for (uptr P
= Min
; P
!= Max
; ++P
) {
301 if (!InRange
|| InRange
->getEnd().getMemoryLocation() == P
)
302 InRange
= upperBound(P
, Ranges
, NumRanges
);
306 Spaces
+= (P
% 8) == 0 ? 2 : 1;
308 if (InRange
&& InRange
->getStart().getMemoryLocation() == P
) {
311 RenderText(&Buffer
, InRange
->getText(), Args
);
313 // FIXME: We only support naming one range for now!
320 Printf("%s", Buffer
.data());
321 // FIXME: Print names for anything we can identify within the line:
323 // * If we can identify the memory itself as belonging to a particular
324 // global, stack variable, or dynamic allocation, then do so.
326 // * If we have a pointer-size, pointer-aligned range highlighted,
327 // determine whether the value of that range is a pointer to an
328 // entity which we can name, and if so, print that name.
330 // This needs an external symbolizer, or (preferably) ASan instrumentation.
334 // All diagnostics should be printed under report mutex.
335 CommonSanitizerReportMutex
.CheckLocked();
337 InternalScopedString
Buffer(1024);
339 Buffer
.append(Decor
.Bold());
340 RenderLocation(&Buffer
, Loc
);
345 Buffer
.append("%s runtime error: %s%s", Decor
.Warning(), Decor
.EndWarning(),
350 Buffer
.append("%s note: %s", Decor
.Note(), Decor
.EndNote());
354 RenderText(&Buffer
, Message
, Args
);
356 Buffer
.append("%s\n", Decor
.Default());
357 Printf("%s", Buffer
.data());
359 if (Loc
.isMemoryLocation())
360 PrintMemorySnippet(Decor
, Loc
.getMemoryLocation(), Ranges
, NumRanges
, Args
);
363 ScopedReport::ScopedReport(ReportOptions Opts
, Location SummaryLoc
,
365 : Opts(Opts
), SummaryLoc(SummaryLoc
), Type(Type
) {
366 InitAsStandaloneIfNecessary();
367 CommonSanitizerReportMutex
.Lock();
370 ScopedReport::~ScopedReport() {
371 MaybePrintStackTrace(Opts
.pc
, Opts
.bp
);
372 MaybeReportErrorSummary(SummaryLoc
, Type
);
373 CommonSanitizerReportMutex
.Unlock();
374 if (flags()->halt_on_error
)
378 ALIGNED(64) static char suppression_placeholder
[sizeof(SuppressionContext
)];
379 static SuppressionContext
*suppression_ctx
= nullptr;
380 static const char kVptrCheck
[] = "vptr_check";
381 static const char *kSuppressionTypes
[] = {
382 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName,
383 #include "ubsan_checks.inc"
388 void __ubsan::InitializeSuppressions() {
389 CHECK_EQ(nullptr, suppression_ctx
);
390 suppression_ctx
= new (suppression_placeholder
) // NOLINT
391 SuppressionContext(kSuppressionTypes
, ARRAY_SIZE(kSuppressionTypes
));
392 suppression_ctx
->ParseFromFile(flags()->suppressions
);
395 bool __ubsan::IsVptrCheckSuppressed(const char *TypeName
) {
396 InitAsStandaloneIfNecessary();
397 CHECK(suppression_ctx
);
399 return suppression_ctx
->Match(TypeName
, kVptrCheck
, &s
);
402 bool __ubsan::IsPCSuppressed(ErrorType ET
, uptr PC
, const char *Filename
) {
403 InitAsStandaloneIfNecessary();
404 CHECK(suppression_ctx
);
405 const char *SuppType
= ConvertTypeToFlagName(ET
);
406 // Fast path: don't symbolize PC if there is no suppressions for given UB
408 if (!suppression_ctx
->HasSuppressionType(SuppType
))
410 Suppression
*s
= nullptr;
411 // Suppress by file name known to runtime.
412 if (Filename
!= nullptr && suppression_ctx
->Match(Filename
, SuppType
, &s
))
414 // Suppress by module name.
415 if (const char *Module
= Symbolizer::GetOrInit()->GetModuleNameForPc(PC
)) {
416 if (suppression_ctx
->Match(Module
, SuppType
, &s
))
419 // Suppress by function or source file name from debug info.
420 SymbolizedStackHolder
Stack(Symbolizer::GetOrInit()->SymbolizePC(PC
));
421 const AddressInfo
&AI
= Stack
.get()->info
;
422 return suppression_ctx
->Match(AI
.function
, SuppType
, &s
) ||
423 suppression_ctx
->Match(AI
.file
, SuppType
, &s
);
426 #endif // CAN_SANITIZE_UB