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