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