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 
MaybePrintStackTrace(uptr pc,uptr bp)29 static void MaybePrintStackTrace(uptr pc, uptr bp) {
30   // We assume that flags are already parsed, as UBSan runtime
31   // will definitely be called when we print the first diagnostics message.
32   if (!flags()->print_stacktrace)
33     return;
34   // We can only use slow unwind, as we don't have any information about stack
35   // top/bottom.
36   // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
37   // fetch stack top/bottom information if we have it (e.g. if we're running
38   // under ASan).
39   if (StackTrace::WillUseFastUnwind(false))
40     return;
41   BufferedStackTrace stack;
42   stack.Unwind(kStackTraceMax, pc, bp, 0, 0, 0, false);
43   stack.Print();
44 }
45 
MaybeReportErrorSummary(Location Loc)46 static void MaybeReportErrorSummary(Location Loc) {
47   if (!common_flags()->print_summary)
48     return;
49   // Don't try to unwind the stack trace in UBSan summaries: just use the
50   // provided location.
51   if (Loc.isSourceLocation()) {
52     SourceLocation SLoc = Loc.getSourceLocation();
53     if (!SLoc.isInvalid()) {
54       AddressInfo AI;
55       AI.file = internal_strdup(SLoc.getFilename());
56       AI.line = SLoc.getLine();
57       AI.column = SLoc.getColumn();
58       AI.function = internal_strdup("");  // Avoid printing ?? as function name.
59       ReportErrorSummary("undefined-behavior", AI);
60       AI.Clear();
61       return;
62     }
63   }
64   ReportErrorSummary("undefined-behavior");
65 }
66 
67 namespace {
68 class Decorator : public SanitizerCommonDecorator {
69  public:
Decorator()70   Decorator() : SanitizerCommonDecorator() {}
Highlight() const71   const char *Highlight() const { return Green(); }
EndHighlight() const72   const char *EndHighlight() const { return Default(); }
Note() const73   const char *Note() const { return Black(); }
EndNote() const74   const char *EndNote() const { return Default(); }
75 };
76 }
77 
getSymbolizedLocation(uptr PC)78 SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
79   InitAsStandaloneIfNecessary();
80   return Symbolizer::GetOrInit()->SymbolizePC(PC);
81 }
82 
operator <<(const TypeDescriptor & V)83 Diag &Diag::operator<<(const TypeDescriptor &V) {
84   return AddArg(V.getTypeName());
85 }
86 
operator <<(const Value & V)87 Diag &Diag::operator<<(const Value &V) {
88   if (V.getType().isSignedIntegerTy())
89     AddArg(V.getSIntValue());
90   else if (V.getType().isUnsignedIntegerTy())
91     AddArg(V.getUIntValue());
92   else if (V.getType().isFloatTy())
93     AddArg(V.getFloatValue());
94   else
95     AddArg("<unknown>");
96   return *this;
97 }
98 
99 /// Hexadecimal printing for numbers too large for Printf to handle directly.
PrintHex(UIntMax Val)100 static void PrintHex(UIntMax Val) {
101 #if HAVE_INT128_T
102   Printf("0x%08x%08x%08x%08x",
103           (unsigned int)(Val >> 96),
104           (unsigned int)(Val >> 64),
105           (unsigned int)(Val >> 32),
106           (unsigned int)(Val));
107 #else
108   UNREACHABLE("long long smaller than 64 bits?");
109 #endif
110 }
111 
renderLocation(Location Loc)112 static void renderLocation(Location Loc) {
113   InternalScopedString LocBuffer(1024);
114   switch (Loc.getKind()) {
115   case Location::LK_Source: {
116     SourceLocation SLoc = Loc.getSourceLocation();
117     if (SLoc.isInvalid())
118       LocBuffer.append("<unknown>");
119     else
120       RenderSourceLocation(&LocBuffer, SLoc.getFilename(), SLoc.getLine(),
121                            SLoc.getColumn(), common_flags()->strip_path_prefix);
122     break;
123   }
124   case Location::LK_Memory:
125     LocBuffer.append("%p", Loc.getMemoryLocation());
126     break;
127   case Location::LK_Symbolized: {
128     const AddressInfo &Info = Loc.getSymbolizedStack()->info;
129     if (Info.file) {
130       RenderSourceLocation(&LocBuffer, Info.file, Info.line, Info.column,
131                            common_flags()->strip_path_prefix);
132     } else if (Info.module) {
133       RenderModuleLocation(&LocBuffer, Info.module, Info.module_offset,
134                            common_flags()->strip_path_prefix);
135     } else {
136       LocBuffer.append("%p", Info.address);
137     }
138     break;
139   }
140   case Location::LK_Null:
141     LocBuffer.append("<unknown>");
142     break;
143   }
144   Printf("%s:", LocBuffer.data());
145 }
146 
renderText(const char * Message,const Diag::Arg * Args)147 static void renderText(const char *Message, const Diag::Arg *Args) {
148   for (const char *Msg = Message; *Msg; ++Msg) {
149     if (*Msg != '%') {
150       char Buffer[64];
151       unsigned I;
152       for (I = 0; Msg[I] && Msg[I] != '%' && I != 63; ++I)
153         Buffer[I] = Msg[I];
154       Buffer[I] = '\0';
155       Printf(Buffer);
156       Msg += I - 1;
157     } else {
158       const Diag::Arg &A = Args[*++Msg - '0'];
159       switch (A.Kind) {
160       case Diag::AK_String:
161         Printf("%s", A.String);
162         break;
163       case Diag::AK_Mangled: {
164         Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
165         break;
166       }
167       case Diag::AK_SInt:
168         // 'long long' is guaranteed to be at least 64 bits wide.
169         if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
170           Printf("%lld", (long long)A.SInt);
171         else
172           PrintHex(A.SInt);
173         break;
174       case Diag::AK_UInt:
175         if (A.UInt <= UINT64_MAX)
176           Printf("%llu", (unsigned long long)A.UInt);
177         else
178           PrintHex(A.UInt);
179         break;
180       case Diag::AK_Float: {
181         // FIXME: Support floating-point formatting in sanitizer_common's
182         //        printf, and stop using snprintf here.
183         char Buffer[32];
184         snprintf(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float);
185         Printf("%s", Buffer);
186         break;
187       }
188       case Diag::AK_Pointer:
189         Printf("%p", A.Pointer);
190         break;
191       }
192     }
193   }
194 }
195 
196 /// Find the earliest-starting range in Ranges which ends after Loc.
upperBound(MemoryLocation Loc,Range * Ranges,unsigned NumRanges)197 static Range *upperBound(MemoryLocation Loc, Range *Ranges,
198                          unsigned NumRanges) {
199   Range *Best = 0;
200   for (unsigned I = 0; I != NumRanges; ++I)
201     if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
202         (!Best ||
203          Best->getStart().getMemoryLocation() >
204          Ranges[I].getStart().getMemoryLocation()))
205       Best = &Ranges[I];
206   return Best;
207 }
208 
subtractNoOverflow(uptr LHS,uptr RHS)209 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
210   return (LHS < RHS) ? 0 : LHS - RHS;
211 }
212 
addNoOverflow(uptr LHS,uptr RHS)213 static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
214   const uptr Limit = (uptr)-1;
215   return (LHS > Limit - RHS) ? Limit : LHS + RHS;
216 }
217 
218 /// Render a snippet of the address space near a location.
renderMemorySnippet(const Decorator & Decor,MemoryLocation Loc,Range * Ranges,unsigned NumRanges,const Diag::Arg * Args)219 static void renderMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
220                                 Range *Ranges, unsigned NumRanges,
221                                 const Diag::Arg *Args) {
222   // Show at least the 8 bytes surrounding Loc.
223   const unsigned MinBytesNearLoc = 4;
224   MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
225   MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
226   MemoryLocation OrigMin = Min;
227   for (unsigned I = 0; I < NumRanges; ++I) {
228     Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
229     Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
230   }
231 
232   // If we have too many interesting bytes, prefer to show bytes after Loc.
233   const unsigned BytesToShow = 32;
234   if (Max - Min > BytesToShow)
235     Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
236   Max = addNoOverflow(Min, BytesToShow);
237 
238   if (!IsAccessibleMemoryRange(Min, Max - Min)) {
239     Printf("<memory cannot be printed>\n");
240     return;
241   }
242 
243   // Emit data.
244   for (uptr P = Min; P != Max; ++P) {
245     unsigned char C = *reinterpret_cast<const unsigned char*>(P);
246     Printf("%s%02x", (P % 8 == 0) ? "  " : " ", C);
247   }
248   Printf("\n");
249 
250   // Emit highlights.
251   Printf(Decor.Highlight());
252   Range *InRange = upperBound(Min, Ranges, NumRanges);
253   for (uptr P = Min; P != Max; ++P) {
254     char Pad = ' ', Byte = ' ';
255     if (InRange && InRange->getEnd().getMemoryLocation() == P)
256       InRange = upperBound(P, Ranges, NumRanges);
257     if (!InRange && P > Loc)
258       break;
259     if (InRange && InRange->getStart().getMemoryLocation() < P)
260       Pad = '~';
261     if (InRange && InRange->getStart().getMemoryLocation() <= P)
262       Byte = '~';
263     char Buffer[] = { Pad, Pad, P == Loc ? '^' : Byte, Byte, 0 };
264     Printf((P % 8 == 0) ? Buffer : &Buffer[1]);
265   }
266   Printf("%s\n", Decor.EndHighlight());
267 
268   // Go over the line again, and print names for the ranges.
269   InRange = 0;
270   unsigned Spaces = 0;
271   for (uptr P = Min; P != Max; ++P) {
272     if (!InRange || InRange->getEnd().getMemoryLocation() == P)
273       InRange = upperBound(P, Ranges, NumRanges);
274     if (!InRange)
275       break;
276 
277     Spaces += (P % 8) == 0 ? 2 : 1;
278 
279     if (InRange && InRange->getStart().getMemoryLocation() == P) {
280       while (Spaces--)
281         Printf(" ");
282       renderText(InRange->getText(), Args);
283       Printf("\n");
284       // FIXME: We only support naming one range for now!
285       break;
286     }
287 
288     Spaces += 2;
289   }
290 
291   // FIXME: Print names for anything we can identify within the line:
292   //
293   //  * If we can identify the memory itself as belonging to a particular
294   //    global, stack variable, or dynamic allocation, then do so.
295   //
296   //  * If we have a pointer-size, pointer-aligned range highlighted,
297   //    determine whether the value of that range is a pointer to an
298   //    entity which we can name, and if so, print that name.
299   //
300   // This needs an external symbolizer, or (preferably) ASan instrumentation.
301 }
302 
~Diag()303 Diag::~Diag() {
304   // All diagnostics should be printed under report mutex.
305   CommonSanitizerReportMutex.CheckLocked();
306   Decorator Decor;
307   Printf(Decor.Bold());
308 
309   renderLocation(Loc);
310 
311   switch (Level) {
312   case DL_Error:
313     Printf("%s runtime error: %s%s",
314            Decor.Warning(), Decor.EndWarning(), Decor.Bold());
315     break;
316 
317   case DL_Note:
318     Printf("%s note: %s", Decor.Note(), Decor.EndNote());
319     break;
320   }
321 
322   renderText(Message, Args);
323 
324   Printf("%s\n", Decor.Default());
325 
326   if (Loc.isMemoryLocation())
327     renderMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges,
328                         NumRanges, Args);
329 }
330 
ScopedReport(ReportOptions Opts,Location SummaryLoc)331 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc)
332     : Opts(Opts), SummaryLoc(SummaryLoc) {
333   InitAsStandaloneIfNecessary();
334   CommonSanitizerReportMutex.Lock();
335 }
336 
~ScopedReport()337 ScopedReport::~ScopedReport() {
338   MaybePrintStackTrace(Opts.pc, Opts.bp);
339   MaybeReportErrorSummary(SummaryLoc);
340   CommonSanitizerReportMutex.Unlock();
341   if (Opts.DieAfterReport || flags()->halt_on_error)
342     Die();
343 }
344 
345 ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
346 static SuppressionContext *suppression_ctx = nullptr;
347 static const char kVptrCheck[] = "vptr_check";
348 static const char *kSuppressionTypes[] = { kVptrCheck };
349 
InitializeSuppressions()350 void __ubsan::InitializeSuppressions() {
351   CHECK_EQ(nullptr, suppression_ctx);
352   suppression_ctx = new (suppression_placeholder) // NOLINT
353       SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
354   suppression_ctx->ParseFromFile(flags()->suppressions);
355 }
356 
IsVptrCheckSuppressed(const char * TypeName)357 bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
358   InitAsStandaloneIfNecessary();
359   CHECK(suppression_ctx);
360   Suppression *s;
361   return suppression_ctx->Match(TypeName, kVptrCheck, &s);
362 }
363 
364 #endif  // CAN_SANITIZE_UB
365