xref: /freebsd/contrib/llvm-project/compiler-rt/lib/ubsan/ubsan_diag.cpp (revision 68d75eff68281c1b445e3010bb975eae07aac225)
1*68d75effSDimitry Andric //===-- ubsan_diag.cpp ----------------------------------------------------===//
2*68d75effSDimitry Andric //
3*68d75effSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*68d75effSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*68d75effSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*68d75effSDimitry Andric //
7*68d75effSDimitry Andric //===----------------------------------------------------------------------===//
8*68d75effSDimitry Andric //
9*68d75effSDimitry Andric // Diagnostic reporting for the UBSan runtime.
10*68d75effSDimitry Andric //
11*68d75effSDimitry Andric //===----------------------------------------------------------------------===//
12*68d75effSDimitry Andric 
13*68d75effSDimitry Andric #include "ubsan_platform.h"
14*68d75effSDimitry Andric #if CAN_SANITIZE_UB
15*68d75effSDimitry Andric #include "ubsan_diag.h"
16*68d75effSDimitry Andric #include "ubsan_init.h"
17*68d75effSDimitry Andric #include "ubsan_flags.h"
18*68d75effSDimitry Andric #include "ubsan_monitor.h"
19*68d75effSDimitry Andric #include "sanitizer_common/sanitizer_placement_new.h"
20*68d75effSDimitry Andric #include "sanitizer_common/sanitizer_report_decorator.h"
21*68d75effSDimitry Andric #include "sanitizer_common/sanitizer_stacktrace.h"
22*68d75effSDimitry Andric #include "sanitizer_common/sanitizer_stacktrace_printer.h"
23*68d75effSDimitry Andric #include "sanitizer_common/sanitizer_suppressions.h"
24*68d75effSDimitry Andric #include "sanitizer_common/sanitizer_symbolizer.h"
25*68d75effSDimitry Andric #include <stdio.h>
26*68d75effSDimitry Andric 
27*68d75effSDimitry Andric using namespace __ubsan;
28*68d75effSDimitry Andric 
29*68d75effSDimitry Andric // UBSan is combined with runtimes that already provide this functionality
30*68d75effSDimitry Andric // (e.g., ASan) as well as runtimes that lack it (e.g., scudo). Tried to use
31*68d75effSDimitry Andric // weak linkage to resolve this issue which is not portable and breaks on
32*68d75effSDimitry Andric // Windows.
33*68d75effSDimitry Andric // TODO(yln): This is a temporary workaround. GetStackTrace functions will be
34*68d75effSDimitry Andric // removed in the future.
35*68d75effSDimitry Andric void ubsan_GetStackTrace(BufferedStackTrace *stack, uptr max_depth,
36*68d75effSDimitry Andric                          uptr pc, uptr bp, void *context, bool fast) {
37*68d75effSDimitry Andric   uptr top = 0;
38*68d75effSDimitry Andric   uptr bottom = 0;
39*68d75effSDimitry Andric   if (StackTrace::WillUseFastUnwind(fast)) {
40*68d75effSDimitry Andric     GetThreadStackTopAndBottom(false, &top, &bottom);
41*68d75effSDimitry Andric     stack->Unwind(max_depth, pc, bp, nullptr, top, bottom, true);
42*68d75effSDimitry Andric   } else
43*68d75effSDimitry Andric     stack->Unwind(max_depth, pc, bp, context, 0, 0, false);
44*68d75effSDimitry Andric }
45*68d75effSDimitry Andric 
46*68d75effSDimitry Andric static void MaybePrintStackTrace(uptr pc, uptr bp) {
47*68d75effSDimitry Andric   // We assume that flags are already parsed, as UBSan runtime
48*68d75effSDimitry Andric   // will definitely be called when we print the first diagnostics message.
49*68d75effSDimitry Andric   if (!flags()->print_stacktrace)
50*68d75effSDimitry Andric     return;
51*68d75effSDimitry Andric 
52*68d75effSDimitry Andric   BufferedStackTrace stack;
53*68d75effSDimitry Andric   ubsan_GetStackTrace(&stack, kStackTraceMax, pc, bp, nullptr,
54*68d75effSDimitry Andric                 common_flags()->fast_unwind_on_fatal);
55*68d75effSDimitry Andric   stack.Print();
56*68d75effSDimitry Andric }
57*68d75effSDimitry Andric 
58*68d75effSDimitry Andric static const char *ConvertTypeToString(ErrorType Type) {
59*68d75effSDimitry Andric   switch (Type) {
60*68d75effSDimitry Andric #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName)                      \
61*68d75effSDimitry Andric   case ErrorType::Name:                                                        \
62*68d75effSDimitry Andric     return SummaryKind;
63*68d75effSDimitry Andric #include "ubsan_checks.inc"
64*68d75effSDimitry Andric #undef UBSAN_CHECK
65*68d75effSDimitry Andric   }
66*68d75effSDimitry Andric   UNREACHABLE("unknown ErrorType!");
67*68d75effSDimitry Andric }
68*68d75effSDimitry Andric 
69*68d75effSDimitry Andric static const char *ConvertTypeToFlagName(ErrorType Type) {
70*68d75effSDimitry Andric   switch (Type) {
71*68d75effSDimitry Andric #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName)                      \
72*68d75effSDimitry Andric   case ErrorType::Name:                                                        \
73*68d75effSDimitry Andric     return FSanitizeFlagName;
74*68d75effSDimitry Andric #include "ubsan_checks.inc"
75*68d75effSDimitry Andric #undef UBSAN_CHECK
76*68d75effSDimitry Andric   }
77*68d75effSDimitry Andric   UNREACHABLE("unknown ErrorType!");
78*68d75effSDimitry Andric }
79*68d75effSDimitry Andric 
80*68d75effSDimitry Andric static void MaybeReportErrorSummary(Location Loc, ErrorType Type) {
81*68d75effSDimitry Andric   if (!common_flags()->print_summary)
82*68d75effSDimitry Andric     return;
83*68d75effSDimitry Andric   if (!flags()->report_error_type)
84*68d75effSDimitry Andric     Type = ErrorType::GenericUB;
85*68d75effSDimitry Andric   const char *ErrorKind = ConvertTypeToString(Type);
86*68d75effSDimitry Andric   if (Loc.isSourceLocation()) {
87*68d75effSDimitry Andric     SourceLocation SLoc = Loc.getSourceLocation();
88*68d75effSDimitry Andric     if (!SLoc.isInvalid()) {
89*68d75effSDimitry Andric       AddressInfo AI;
90*68d75effSDimitry Andric       AI.file = internal_strdup(SLoc.getFilename());
91*68d75effSDimitry Andric       AI.line = SLoc.getLine();
92*68d75effSDimitry Andric       AI.column = SLoc.getColumn();
93*68d75effSDimitry Andric       AI.function = internal_strdup("");  // Avoid printing ?? as function name.
94*68d75effSDimitry Andric       ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());
95*68d75effSDimitry Andric       AI.Clear();
96*68d75effSDimitry Andric       return;
97*68d75effSDimitry Andric     }
98*68d75effSDimitry Andric   } else if (Loc.isSymbolizedStack()) {
99*68d75effSDimitry Andric     const AddressInfo &AI = Loc.getSymbolizedStack()->info;
100*68d75effSDimitry Andric     ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());
101*68d75effSDimitry Andric     return;
102*68d75effSDimitry Andric   }
103*68d75effSDimitry Andric   ReportErrorSummary(ErrorKind, GetSanititizerToolName());
104*68d75effSDimitry Andric }
105*68d75effSDimitry Andric 
106*68d75effSDimitry Andric namespace {
107*68d75effSDimitry Andric class Decorator : public SanitizerCommonDecorator {
108*68d75effSDimitry Andric  public:
109*68d75effSDimitry Andric   Decorator() : SanitizerCommonDecorator() {}
110*68d75effSDimitry Andric   const char *Highlight() const { return Green(); }
111*68d75effSDimitry Andric   const char *Note() const { return Black(); }
112*68d75effSDimitry Andric };
113*68d75effSDimitry Andric }
114*68d75effSDimitry Andric 
115*68d75effSDimitry Andric SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
116*68d75effSDimitry Andric   InitAsStandaloneIfNecessary();
117*68d75effSDimitry Andric   return Symbolizer::GetOrInit()->SymbolizePC(PC);
118*68d75effSDimitry Andric }
119*68d75effSDimitry Andric 
120*68d75effSDimitry Andric Diag &Diag::operator<<(const TypeDescriptor &V) {
121*68d75effSDimitry Andric   return AddArg(V.getTypeName());
122*68d75effSDimitry Andric }
123*68d75effSDimitry Andric 
124*68d75effSDimitry Andric Diag &Diag::operator<<(const Value &V) {
125*68d75effSDimitry Andric   if (V.getType().isSignedIntegerTy())
126*68d75effSDimitry Andric     AddArg(V.getSIntValue());
127*68d75effSDimitry Andric   else if (V.getType().isUnsignedIntegerTy())
128*68d75effSDimitry Andric     AddArg(V.getUIntValue());
129*68d75effSDimitry Andric   else if (V.getType().isFloatTy())
130*68d75effSDimitry Andric     AddArg(V.getFloatValue());
131*68d75effSDimitry Andric   else
132*68d75effSDimitry Andric     AddArg("<unknown>");
133*68d75effSDimitry Andric   return *this;
134*68d75effSDimitry Andric }
135*68d75effSDimitry Andric 
136*68d75effSDimitry Andric /// Hexadecimal printing for numbers too large for Printf to handle directly.
137*68d75effSDimitry Andric static void RenderHex(InternalScopedString *Buffer, UIntMax Val) {
138*68d75effSDimitry Andric #if HAVE_INT128_T
139*68d75effSDimitry Andric   Buffer->append("0x%08x%08x%08x%08x", (unsigned int)(Val >> 96),
140*68d75effSDimitry Andric                  (unsigned int)(Val >> 64), (unsigned int)(Val >> 32),
141*68d75effSDimitry Andric                  (unsigned int)(Val));
142*68d75effSDimitry Andric #else
143*68d75effSDimitry Andric   UNREACHABLE("long long smaller than 64 bits?");
144*68d75effSDimitry Andric #endif
145*68d75effSDimitry Andric }
146*68d75effSDimitry Andric 
147*68d75effSDimitry Andric static void RenderLocation(InternalScopedString *Buffer, Location Loc) {
148*68d75effSDimitry Andric   switch (Loc.getKind()) {
149*68d75effSDimitry Andric   case Location::LK_Source: {
150*68d75effSDimitry Andric     SourceLocation SLoc = Loc.getSourceLocation();
151*68d75effSDimitry Andric     if (SLoc.isInvalid())
152*68d75effSDimitry Andric       Buffer->append("<unknown>");
153*68d75effSDimitry Andric     else
154*68d75effSDimitry Andric       RenderSourceLocation(Buffer, SLoc.getFilename(), SLoc.getLine(),
155*68d75effSDimitry Andric                            SLoc.getColumn(), common_flags()->symbolize_vs_style,
156*68d75effSDimitry Andric                            common_flags()->strip_path_prefix);
157*68d75effSDimitry Andric     return;
158*68d75effSDimitry Andric   }
159*68d75effSDimitry Andric   case Location::LK_Memory:
160*68d75effSDimitry Andric     Buffer->append("%p", Loc.getMemoryLocation());
161*68d75effSDimitry Andric     return;
162*68d75effSDimitry Andric   case Location::LK_Symbolized: {
163*68d75effSDimitry Andric     const AddressInfo &Info = Loc.getSymbolizedStack()->info;
164*68d75effSDimitry Andric     if (Info.file)
165*68d75effSDimitry Andric       RenderSourceLocation(Buffer, Info.file, Info.line, Info.column,
166*68d75effSDimitry Andric                            common_flags()->symbolize_vs_style,
167*68d75effSDimitry Andric                            common_flags()->strip_path_prefix);
168*68d75effSDimitry Andric     else if (Info.module)
169*68d75effSDimitry Andric       RenderModuleLocation(Buffer, Info.module, Info.module_offset,
170*68d75effSDimitry Andric                            Info.module_arch, common_flags()->strip_path_prefix);
171*68d75effSDimitry Andric     else
172*68d75effSDimitry Andric       Buffer->append("%p", Info.address);
173*68d75effSDimitry Andric     return;
174*68d75effSDimitry Andric   }
175*68d75effSDimitry Andric   case Location::LK_Null:
176*68d75effSDimitry Andric     Buffer->append("<unknown>");
177*68d75effSDimitry Andric     return;
178*68d75effSDimitry Andric   }
179*68d75effSDimitry Andric }
180*68d75effSDimitry Andric 
181*68d75effSDimitry Andric static void RenderText(InternalScopedString *Buffer, const char *Message,
182*68d75effSDimitry Andric                        const Diag::Arg *Args) {
183*68d75effSDimitry Andric   for (const char *Msg = Message; *Msg; ++Msg) {
184*68d75effSDimitry Andric     if (*Msg != '%') {
185*68d75effSDimitry Andric       Buffer->append("%c", *Msg);
186*68d75effSDimitry Andric       continue;
187*68d75effSDimitry Andric     }
188*68d75effSDimitry Andric     const Diag::Arg &A = Args[*++Msg - '0'];
189*68d75effSDimitry Andric     switch (A.Kind) {
190*68d75effSDimitry Andric     case Diag::AK_String:
191*68d75effSDimitry Andric       Buffer->append("%s", A.String);
192*68d75effSDimitry Andric       break;
193*68d75effSDimitry Andric     case Diag::AK_TypeName: {
194*68d75effSDimitry Andric       if (SANITIZER_WINDOWS)
195*68d75effSDimitry Andric         // The Windows implementation demangles names early.
196*68d75effSDimitry Andric         Buffer->append("'%s'", A.String);
197*68d75effSDimitry Andric       else
198*68d75effSDimitry Andric         Buffer->append("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
199*68d75effSDimitry Andric       break;
200*68d75effSDimitry Andric     }
201*68d75effSDimitry Andric     case Diag::AK_SInt:
202*68d75effSDimitry Andric       // 'long long' is guaranteed to be at least 64 bits wide.
203*68d75effSDimitry Andric       if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
204*68d75effSDimitry Andric         Buffer->append("%lld", (long long)A.SInt);
205*68d75effSDimitry Andric       else
206*68d75effSDimitry Andric         RenderHex(Buffer, A.SInt);
207*68d75effSDimitry Andric       break;
208*68d75effSDimitry Andric     case Diag::AK_UInt:
209*68d75effSDimitry Andric       if (A.UInt <= UINT64_MAX)
210*68d75effSDimitry Andric         Buffer->append("%llu", (unsigned long long)A.UInt);
211*68d75effSDimitry Andric       else
212*68d75effSDimitry Andric         RenderHex(Buffer, A.UInt);
213*68d75effSDimitry Andric       break;
214*68d75effSDimitry Andric     case Diag::AK_Float: {
215*68d75effSDimitry Andric       // FIXME: Support floating-point formatting in sanitizer_common's
216*68d75effSDimitry Andric       //        printf, and stop using snprintf here.
217*68d75effSDimitry Andric       char FloatBuffer[32];
218*68d75effSDimitry Andric #if SANITIZER_WINDOWS
219*68d75effSDimitry Andric       sprintf_s(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
220*68d75effSDimitry Andric #else
221*68d75effSDimitry Andric       snprintf(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);
222*68d75effSDimitry Andric #endif
223*68d75effSDimitry Andric       Buffer->append("%s", FloatBuffer);
224*68d75effSDimitry Andric       break;
225*68d75effSDimitry Andric     }
226*68d75effSDimitry Andric     case Diag::AK_Pointer:
227*68d75effSDimitry Andric       Buffer->append("%p", A.Pointer);
228*68d75effSDimitry Andric       break;
229*68d75effSDimitry Andric     }
230*68d75effSDimitry Andric   }
231*68d75effSDimitry Andric }
232*68d75effSDimitry Andric 
233*68d75effSDimitry Andric /// Find the earliest-starting range in Ranges which ends after Loc.
234*68d75effSDimitry Andric static Range *upperBound(MemoryLocation Loc, Range *Ranges,
235*68d75effSDimitry Andric                          unsigned NumRanges) {
236*68d75effSDimitry Andric   Range *Best = 0;
237*68d75effSDimitry Andric   for (unsigned I = 0; I != NumRanges; ++I)
238*68d75effSDimitry Andric     if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
239*68d75effSDimitry Andric         (!Best ||
240*68d75effSDimitry Andric          Best->getStart().getMemoryLocation() >
241*68d75effSDimitry Andric          Ranges[I].getStart().getMemoryLocation()))
242*68d75effSDimitry Andric       Best = &Ranges[I];
243*68d75effSDimitry Andric   return Best;
244*68d75effSDimitry Andric }
245*68d75effSDimitry Andric 
246*68d75effSDimitry Andric static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
247*68d75effSDimitry Andric   return (LHS < RHS) ? 0 : LHS - RHS;
248*68d75effSDimitry Andric }
249*68d75effSDimitry Andric 
250*68d75effSDimitry Andric static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
251*68d75effSDimitry Andric   const uptr Limit = (uptr)-1;
252*68d75effSDimitry Andric   return (LHS > Limit - RHS) ? Limit : LHS + RHS;
253*68d75effSDimitry Andric }
254*68d75effSDimitry Andric 
255*68d75effSDimitry Andric /// Render a snippet of the address space near a location.
256*68d75effSDimitry Andric static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
257*68d75effSDimitry Andric                                Range *Ranges, unsigned NumRanges,
258*68d75effSDimitry Andric                                const Diag::Arg *Args) {
259*68d75effSDimitry Andric   // Show at least the 8 bytes surrounding Loc.
260*68d75effSDimitry Andric   const unsigned MinBytesNearLoc = 4;
261*68d75effSDimitry Andric   MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
262*68d75effSDimitry Andric   MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
263*68d75effSDimitry Andric   MemoryLocation OrigMin = Min;
264*68d75effSDimitry Andric   for (unsigned I = 0; I < NumRanges; ++I) {
265*68d75effSDimitry Andric     Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
266*68d75effSDimitry Andric     Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
267*68d75effSDimitry Andric   }
268*68d75effSDimitry Andric 
269*68d75effSDimitry Andric   // If we have too many interesting bytes, prefer to show bytes after Loc.
270*68d75effSDimitry Andric   const unsigned BytesToShow = 32;
271*68d75effSDimitry Andric   if (Max - Min > BytesToShow)
272*68d75effSDimitry Andric     Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
273*68d75effSDimitry Andric   Max = addNoOverflow(Min, BytesToShow);
274*68d75effSDimitry Andric 
275*68d75effSDimitry Andric   if (!IsAccessibleMemoryRange(Min, Max - Min)) {
276*68d75effSDimitry Andric     Printf("<memory cannot be printed>\n");
277*68d75effSDimitry Andric     return;
278*68d75effSDimitry Andric   }
279*68d75effSDimitry Andric 
280*68d75effSDimitry Andric   // Emit data.
281*68d75effSDimitry Andric   InternalScopedString Buffer(1024);
282*68d75effSDimitry Andric   for (uptr P = Min; P != Max; ++P) {
283*68d75effSDimitry Andric     unsigned char C = *reinterpret_cast<const unsigned char*>(P);
284*68d75effSDimitry Andric     Buffer.append("%s%02x", (P % 8 == 0) ? "  " : " ", C);
285*68d75effSDimitry Andric   }
286*68d75effSDimitry Andric   Buffer.append("\n");
287*68d75effSDimitry Andric 
288*68d75effSDimitry Andric   // Emit highlights.
289*68d75effSDimitry Andric   Buffer.append(Decor.Highlight());
290*68d75effSDimitry Andric   Range *InRange = upperBound(Min, Ranges, NumRanges);
291*68d75effSDimitry Andric   for (uptr P = Min; P != Max; ++P) {
292*68d75effSDimitry Andric     char Pad = ' ', Byte = ' ';
293*68d75effSDimitry Andric     if (InRange && InRange->getEnd().getMemoryLocation() == P)
294*68d75effSDimitry Andric       InRange = upperBound(P, Ranges, NumRanges);
295*68d75effSDimitry Andric     if (!InRange && P > Loc)
296*68d75effSDimitry Andric       break;
297*68d75effSDimitry Andric     if (InRange && InRange->getStart().getMemoryLocation() < P)
298*68d75effSDimitry Andric       Pad = '~';
299*68d75effSDimitry Andric     if (InRange && InRange->getStart().getMemoryLocation() <= P)
300*68d75effSDimitry Andric       Byte = '~';
301*68d75effSDimitry Andric     if (P % 8 == 0)
302*68d75effSDimitry Andric       Buffer.append("%c", Pad);
303*68d75effSDimitry Andric     Buffer.append("%c", Pad);
304*68d75effSDimitry Andric     Buffer.append("%c", P == Loc ? '^' : Byte);
305*68d75effSDimitry Andric     Buffer.append("%c", Byte);
306*68d75effSDimitry Andric   }
307*68d75effSDimitry Andric   Buffer.append("%s\n", Decor.Default());
308*68d75effSDimitry Andric 
309*68d75effSDimitry Andric   // Go over the line again, and print names for the ranges.
310*68d75effSDimitry Andric   InRange = 0;
311*68d75effSDimitry Andric   unsigned Spaces = 0;
312*68d75effSDimitry Andric   for (uptr P = Min; P != Max; ++P) {
313*68d75effSDimitry Andric     if (!InRange || InRange->getEnd().getMemoryLocation() == P)
314*68d75effSDimitry Andric       InRange = upperBound(P, Ranges, NumRanges);
315*68d75effSDimitry Andric     if (!InRange)
316*68d75effSDimitry Andric       break;
317*68d75effSDimitry Andric 
318*68d75effSDimitry Andric     Spaces += (P % 8) == 0 ? 2 : 1;
319*68d75effSDimitry Andric 
320*68d75effSDimitry Andric     if (InRange && InRange->getStart().getMemoryLocation() == P) {
321*68d75effSDimitry Andric       while (Spaces--)
322*68d75effSDimitry Andric         Buffer.append(" ");
323*68d75effSDimitry Andric       RenderText(&Buffer, InRange->getText(), Args);
324*68d75effSDimitry Andric       Buffer.append("\n");
325*68d75effSDimitry Andric       // FIXME: We only support naming one range for now!
326*68d75effSDimitry Andric       break;
327*68d75effSDimitry Andric     }
328*68d75effSDimitry Andric 
329*68d75effSDimitry Andric     Spaces += 2;
330*68d75effSDimitry Andric   }
331*68d75effSDimitry Andric 
332*68d75effSDimitry Andric   Printf("%s", Buffer.data());
333*68d75effSDimitry Andric   // FIXME: Print names for anything we can identify within the line:
334*68d75effSDimitry Andric   //
335*68d75effSDimitry Andric   //  * If we can identify the memory itself as belonging to a particular
336*68d75effSDimitry Andric   //    global, stack variable, or dynamic allocation, then do so.
337*68d75effSDimitry Andric   //
338*68d75effSDimitry Andric   //  * If we have a pointer-size, pointer-aligned range highlighted,
339*68d75effSDimitry Andric   //    determine whether the value of that range is a pointer to an
340*68d75effSDimitry Andric   //    entity which we can name, and if so, print that name.
341*68d75effSDimitry Andric   //
342*68d75effSDimitry Andric   // This needs an external symbolizer, or (preferably) ASan instrumentation.
343*68d75effSDimitry Andric }
344*68d75effSDimitry Andric 
345*68d75effSDimitry Andric Diag::~Diag() {
346*68d75effSDimitry Andric   // All diagnostics should be printed under report mutex.
347*68d75effSDimitry Andric   ScopedReport::CheckLocked();
348*68d75effSDimitry Andric   Decorator Decor;
349*68d75effSDimitry Andric   InternalScopedString Buffer(1024);
350*68d75effSDimitry Andric 
351*68d75effSDimitry Andric   // Prepare a report that a monitor process can inspect.
352*68d75effSDimitry Andric   if (Level == DL_Error) {
353*68d75effSDimitry Andric     RenderText(&Buffer, Message, Args);
354*68d75effSDimitry Andric     UndefinedBehaviorReport UBR{ConvertTypeToString(ET), Loc, Buffer};
355*68d75effSDimitry Andric     Buffer.clear();
356*68d75effSDimitry Andric   }
357*68d75effSDimitry Andric 
358*68d75effSDimitry Andric   Buffer.append(Decor.Bold());
359*68d75effSDimitry Andric   RenderLocation(&Buffer, Loc);
360*68d75effSDimitry Andric   Buffer.append(":");
361*68d75effSDimitry Andric 
362*68d75effSDimitry Andric   switch (Level) {
363*68d75effSDimitry Andric   case DL_Error:
364*68d75effSDimitry Andric     Buffer.append("%s runtime error: %s%s", Decor.Warning(), Decor.Default(),
365*68d75effSDimitry Andric                   Decor.Bold());
366*68d75effSDimitry Andric     break;
367*68d75effSDimitry Andric 
368*68d75effSDimitry Andric   case DL_Note:
369*68d75effSDimitry Andric     Buffer.append("%s note: %s", Decor.Note(), Decor.Default());
370*68d75effSDimitry Andric     break;
371*68d75effSDimitry Andric   }
372*68d75effSDimitry Andric 
373*68d75effSDimitry Andric   RenderText(&Buffer, Message, Args);
374*68d75effSDimitry Andric 
375*68d75effSDimitry Andric   Buffer.append("%s\n", Decor.Default());
376*68d75effSDimitry Andric   Printf("%s", Buffer.data());
377*68d75effSDimitry Andric 
378*68d75effSDimitry Andric   if (Loc.isMemoryLocation())
379*68d75effSDimitry Andric     PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args);
380*68d75effSDimitry Andric }
381*68d75effSDimitry Andric 
382*68d75effSDimitry Andric ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); }
383*68d75effSDimitry Andric 
384*68d75effSDimitry Andric ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,
385*68d75effSDimitry Andric                            ErrorType Type)
386*68d75effSDimitry Andric     : Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {}
387*68d75effSDimitry Andric 
388*68d75effSDimitry Andric ScopedReport::~ScopedReport() {
389*68d75effSDimitry Andric   MaybePrintStackTrace(Opts.pc, Opts.bp);
390*68d75effSDimitry Andric   MaybeReportErrorSummary(SummaryLoc, Type);
391*68d75effSDimitry Andric   if (flags()->halt_on_error)
392*68d75effSDimitry Andric     Die();
393*68d75effSDimitry Andric }
394*68d75effSDimitry Andric 
395*68d75effSDimitry Andric ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
396*68d75effSDimitry Andric static SuppressionContext *suppression_ctx = nullptr;
397*68d75effSDimitry Andric static const char kVptrCheck[] = "vptr_check";
398*68d75effSDimitry Andric static const char *kSuppressionTypes[] = {
399*68d75effSDimitry Andric #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName,
400*68d75effSDimitry Andric #include "ubsan_checks.inc"
401*68d75effSDimitry Andric #undef UBSAN_CHECK
402*68d75effSDimitry Andric     kVptrCheck,
403*68d75effSDimitry Andric };
404*68d75effSDimitry Andric 
405*68d75effSDimitry Andric void __ubsan::InitializeSuppressions() {
406*68d75effSDimitry Andric   CHECK_EQ(nullptr, suppression_ctx);
407*68d75effSDimitry Andric   suppression_ctx = new (suppression_placeholder)
408*68d75effSDimitry Andric       SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
409*68d75effSDimitry Andric   suppression_ctx->ParseFromFile(flags()->suppressions);
410*68d75effSDimitry Andric }
411*68d75effSDimitry Andric 
412*68d75effSDimitry Andric bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
413*68d75effSDimitry Andric   InitAsStandaloneIfNecessary();
414*68d75effSDimitry Andric   CHECK(suppression_ctx);
415*68d75effSDimitry Andric   Suppression *s;
416*68d75effSDimitry Andric   return suppression_ctx->Match(TypeName, kVptrCheck, &s);
417*68d75effSDimitry Andric }
418*68d75effSDimitry Andric 
419*68d75effSDimitry Andric bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) {
420*68d75effSDimitry Andric   InitAsStandaloneIfNecessary();
421*68d75effSDimitry Andric   CHECK(suppression_ctx);
422*68d75effSDimitry Andric   const char *SuppType = ConvertTypeToFlagName(ET);
423*68d75effSDimitry Andric   // Fast path: don't symbolize PC if there is no suppressions for given UB
424*68d75effSDimitry Andric   // type.
425*68d75effSDimitry Andric   if (!suppression_ctx->HasSuppressionType(SuppType))
426*68d75effSDimitry Andric     return false;
427*68d75effSDimitry Andric   Suppression *s = nullptr;
428*68d75effSDimitry Andric   // Suppress by file name known to runtime.
429*68d75effSDimitry Andric   if (Filename != nullptr && suppression_ctx->Match(Filename, SuppType, &s))
430*68d75effSDimitry Andric     return true;
431*68d75effSDimitry Andric   // Suppress by module name.
432*68d75effSDimitry Andric   if (const char *Module = Symbolizer::GetOrInit()->GetModuleNameForPc(PC)) {
433*68d75effSDimitry Andric     if (suppression_ctx->Match(Module, SuppType, &s))
434*68d75effSDimitry Andric       return true;
435*68d75effSDimitry Andric   }
436*68d75effSDimitry Andric   // Suppress by function or source file name from debug info.
437*68d75effSDimitry Andric   SymbolizedStackHolder Stack(Symbolizer::GetOrInit()->SymbolizePC(PC));
438*68d75effSDimitry Andric   const AddressInfo &AI = Stack.get()->info;
439*68d75effSDimitry Andric   return suppression_ctx->Match(AI.function, SuppType, &s) ||
440*68d75effSDimitry Andric          suppression_ctx->Match(AI.file, SuppType, &s);
441*68d75effSDimitry Andric }
442*68d75effSDimitry Andric 
443*68d75effSDimitry Andric #endif  // CAN_SANITIZE_UB
444