blob: a4c9e30467162893847ffd29699ea356dc214c65 [file] [log] [blame]
Richard Smith6ebe4512012-10-09 19:34:32 +00001//===-- 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
Pirama Arumuga Nainar7c915052015-04-08 08:58:29 -070014#include "ubsan_platform.h"
15#if CAN_SANITIZE_UB
Richard Smith6ebe4512012-10-09 19:34:32 +000016#include "ubsan_diag.h"
Stephen Hines6d186232014-11-26 17:56:19 -080017#include "ubsan_init.h"
18#include "ubsan_flags.h"
Stephen Hines86277eb2015-03-23 12:06:32 -070019#include "sanitizer_common/sanitizer_placement_new.h"
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +000020#include "sanitizer_common/sanitizer_report_decorator.h"
Richard Smith5f116492012-12-18 04:23:18 +000021#include "sanitizer_common/sanitizer_stacktrace.h"
Stephen Hines6d186232014-11-26 17:56:19 -080022#include "sanitizer_common/sanitizer_stacktrace_printer.h"
Stephen Hines86277eb2015-03-23 12:06:32 -070023#include "sanitizer_common/sanitizer_suppressions.h"
Richard Smith5f116492012-12-18 04:23:18 +000024#include "sanitizer_common/sanitizer_symbolizer.h"
Richard Smith6ebe4512012-10-09 19:34:32 +000025#include <stdio.h>
Richard Smith6ebe4512012-10-09 19:34:32 +000026
27using namespace __ubsan;
28
Stephen Hines6d186232014-11-26 17:56:19 -080029static void MaybePrintStackTrace(uptr pc, uptr bp) {
Pirama Arumuga Nainar259f7062015-05-06 11:49:53 -070030 // We assume that flags are already parsed, as UBSan runtime
Stephen Hines6d186232014-11-26 17:56:19 -080031 // 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
46static void MaybeReportErrorSummary(Location Loc) {
47 if (!common_flags()->print_summary)
48 return;
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -070049 const char *ErrorType = "undefined-behavior";
Stephen Hines6d186232014-11-26 17:56:19 -080050 if (Loc.isSourceLocation()) {
51 SourceLocation SLoc = Loc.getSourceLocation();
52 if (!SLoc.isInvalid()) {
Pirama Arumuga Nainar7c915052015-04-08 08:58:29 -070053 AddressInfo AI;
54 AI.file = internal_strdup(SLoc.getFilename());
55 AI.line = SLoc.getLine();
56 AI.column = SLoc.getColumn();
57 AI.function = internal_strdup(""); // Avoid printing ?? as function name.
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -070058 ReportErrorSummary(ErrorType, AI);
Pirama Arumuga Nainar7c915052015-04-08 08:58:29 -070059 AI.Clear();
Stephen Hines6d186232014-11-26 17:56:19 -080060 return;
61 }
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -070062 } else if (Loc.isSymbolizedStack()) {
63 const AddressInfo &AI = Loc.getSymbolizedStack()->info;
64 ReportErrorSummary(ErrorType, AI);
65 return;
Stephen Hines2d1fdb22014-05-28 23:58:16 -070066 }
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -070067 ReportErrorSummary(ErrorType);
Stephen Hines2d1fdb22014-05-28 23:58:16 -070068}
69
Stephen Hines6a211c52014-07-21 00:49:56 -070070namespace {
71class Decorator : public SanitizerCommonDecorator {
72 public:
73 Decorator() : SanitizerCommonDecorator() {}
74 const char *Highlight() const { return Green(); }
75 const char *EndHighlight() const { return Default(); }
76 const char *Note() const { return Black(); }
77 const char *EndNote() const { return Default(); }
78};
79}
80
Stephen Hines86277eb2015-03-23 12:06:32 -070081SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {
Pirama Arumuga Nainar259f7062015-05-06 11:49:53 -070082 InitAsStandaloneIfNecessary();
Stephen Hines86277eb2015-03-23 12:06:32 -070083 return Symbolizer::GetOrInit()->SymbolizePC(PC);
Richard Smith5f116492012-12-18 04:23:18 +000084}
85
Richard Smith6ebe4512012-10-09 19:34:32 +000086Diag &Diag::operator<<(const TypeDescriptor &V) {
87 return AddArg(V.getTypeName());
88}
89
90Diag &Diag::operator<<(const Value &V) {
91 if (V.getType().isSignedIntegerTy())
92 AddArg(V.getSIntValue());
93 else if (V.getType().isUnsignedIntegerTy())
94 AddArg(V.getUIntValue());
Richard Smith58561702012-10-12 22:57:15 +000095 else if (V.getType().isFloatTy())
96 AddArg(V.getFloatValue());
Richard Smith6ebe4512012-10-09 19:34:32 +000097 else
98 AddArg("<unknown>");
99 return *this;
100}
101
Richard Smith0ad23f72012-12-18 09:30:21 +0000102/// Hexadecimal printing for numbers too large for Printf to handle directly.
Richard Smith6ebe4512012-10-09 19:34:32 +0000103static void PrintHex(UIntMax Val) {
Chandler Carruthba3fde62012-10-13 02:30:10 +0000104#if HAVE_INT128_T
Richard Smithf4932202012-11-13 23:42:05 +0000105 Printf("0x%08x%08x%08x%08x",
Richard Smith6ebe4512012-10-09 19:34:32 +0000106 (unsigned int)(Val >> 96),
107 (unsigned int)(Val >> 64),
108 (unsigned int)(Val >> 32),
109 (unsigned int)(Val));
110#else
111 UNREACHABLE("long long smaller than 64 bits?");
112#endif
113}
114
Richard Smith5f116492012-12-18 04:23:18 +0000115static void renderLocation(Location Loc) {
Alexey Samsonovaed85842013-11-14 09:54:10 +0000116 InternalScopedString LocBuffer(1024);
Richard Smith5f116492012-12-18 04:23:18 +0000117 switch (Loc.getKind()) {
118 case Location::LK_Source: {
119 SourceLocation SLoc = Loc.getSourceLocation();
120 if (SLoc.isInvalid())
Alexey Samsonovaed85842013-11-14 09:54:10 +0000121 LocBuffer.append("<unknown>");
Alexey Samsonov90b0f1e2013-10-04 08:55:03 +0000122 else
Stephen Hines6d186232014-11-26 17:56:19 -0800123 RenderSourceLocation(&LocBuffer, SLoc.getFilename(), SLoc.getLine(),
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700124 SLoc.getColumn(), common_flags()->symbolize_vs_style,
125 common_flags()->strip_path_prefix);
Richard Smith5f116492012-12-18 04:23:18 +0000126 break;
127 }
Richard Smith5f116492012-12-18 04:23:18 +0000128 case Location::LK_Memory:
Alexey Samsonovaed85842013-11-14 09:54:10 +0000129 LocBuffer.append("%p", Loc.getMemoryLocation());
Richard Smith5f116492012-12-18 04:23:18 +0000130 break;
Stephen Hines86277eb2015-03-23 12:06:32 -0700131 case Location::LK_Symbolized: {
132 const AddressInfo &Info = Loc.getSymbolizedStack()->info;
133 if (Info.file) {
134 RenderSourceLocation(&LocBuffer, Info.file, Info.line, Info.column,
Pirama Arumuga Nainarcdce50b2015-07-01 12:26:56 -0700135 common_flags()->symbolize_vs_style,
Stephen Hines86277eb2015-03-23 12:06:32 -0700136 common_flags()->strip_path_prefix);
137 } else if (Info.module) {
138 RenderModuleLocation(&LocBuffer, Info.module, Info.module_offset,
139 common_flags()->strip_path_prefix);
140 } else {
141 LocBuffer.append("%p", Info.address);
142 }
143 break;
144 }
Richard Smith5f116492012-12-18 04:23:18 +0000145 case Location::LK_Null:
Alexey Samsonovaed85842013-11-14 09:54:10 +0000146 LocBuffer.append("<unknown>");
Richard Smith25ee97f2012-12-18 06:30:32 +0000147 break;
Richard Smith5f116492012-12-18 04:23:18 +0000148 }
Alexey Samsonovaed85842013-11-14 09:54:10 +0000149 Printf("%s:", LocBuffer.data());
Richard Smith5f116492012-12-18 04:23:18 +0000150}
151
Richard Smith25ee97f2012-12-18 06:30:32 +0000152static void renderText(const char *Message, const Diag::Arg *Args) {
Richard Smith6ebe4512012-10-09 19:34:32 +0000153 for (const char *Msg = Message; *Msg; ++Msg) {
Richard Smithf4932202012-11-13 23:42:05 +0000154 if (*Msg != '%') {
155 char Buffer[64];
156 unsigned I;
157 for (I = 0; Msg[I] && Msg[I] != '%' && I != 63; ++I)
158 Buffer[I] = Msg[I];
159 Buffer[I] = '\0';
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000160 Printf(Buffer);
Richard Smithf4932202012-11-13 23:42:05 +0000161 Msg += I - 1;
162 } else {
Richard Smith25ee97f2012-12-18 06:30:32 +0000163 const Diag::Arg &A = Args[*++Msg - '0'];
Richard Smith6ebe4512012-10-09 19:34:32 +0000164 switch (A.Kind) {
Richard Smith25ee97f2012-12-18 06:30:32 +0000165 case Diag::AK_String:
Richard Smithf4932202012-11-13 23:42:05 +0000166 Printf("%s", A.String);
Richard Smith6ebe4512012-10-09 19:34:32 +0000167 break;
Richard Smith0ad23f72012-12-18 09:30:21 +0000168 case Diag::AK_Mangled: {
Peter Collingbournec1a1ed62013-10-25 23:03:29 +0000169 Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
Richard Smith0ad23f72012-12-18 09:30:21 +0000170 break;
171 }
Richard Smith25ee97f2012-12-18 06:30:32 +0000172 case Diag::AK_SInt:
Richard Smith6ebe4512012-10-09 19:34:32 +0000173 // 'long long' is guaranteed to be at least 64 bits wide.
174 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
Richard Smithf4932202012-11-13 23:42:05 +0000175 Printf("%lld", (long long)A.SInt);
Richard Smith6ebe4512012-10-09 19:34:32 +0000176 else
177 PrintHex(A.SInt);
178 break;
Richard Smith25ee97f2012-12-18 06:30:32 +0000179 case Diag::AK_UInt:
Richard Smith6ebe4512012-10-09 19:34:32 +0000180 if (A.UInt <= UINT64_MAX)
Richard Smithf4932202012-11-13 23:42:05 +0000181 Printf("%llu", (unsigned long long)A.UInt);
Richard Smith6ebe4512012-10-09 19:34:32 +0000182 else
183 PrintHex(A.UInt);
184 break;
Richard Smith25ee97f2012-12-18 06:30:32 +0000185 case Diag::AK_Float: {
Richard Smithf4932202012-11-13 23:42:05 +0000186 // FIXME: Support floating-point formatting in sanitizer_common's
187 // printf, and stop using snprintf here.
188 char Buffer[32];
189 snprintf(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float);
190 Printf("%s", Buffer);
Richard Smith58561702012-10-12 22:57:15 +0000191 break;
Richard Smithf4932202012-11-13 23:42:05 +0000192 }
Richard Smith25ee97f2012-12-18 06:30:32 +0000193 case Diag::AK_Pointer:
Richard Smithc1939532013-01-10 22:39:40 +0000194 Printf("%p", A.Pointer);
Richard Smith6ebe4512012-10-09 19:34:32 +0000195 break;
196 }
197 }
198 }
Richard Smith25ee97f2012-12-18 06:30:32 +0000199}
200
201/// Find the earliest-starting range in Ranges which ends after Loc.
202static Range *upperBound(MemoryLocation Loc, Range *Ranges,
203 unsigned NumRanges) {
204 Range *Best = 0;
205 for (unsigned I = 0; I != NumRanges; ++I)
206 if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
207 (!Best ||
208 Best->getStart().getMemoryLocation() >
209 Ranges[I].getStart().getMemoryLocation()))
210 Best = &Ranges[I];
211 return Best;
212}
213
Stephen Hines6d186232014-11-26 17:56:19 -0800214static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
215 return (LHS < RHS) ? 0 : LHS - RHS;
216}
217
218static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
219 const uptr Limit = (uptr)-1;
220 return (LHS > Limit - RHS) ? Limit : LHS + RHS;
221}
222
Richard Smith25ee97f2012-12-18 06:30:32 +0000223/// Render a snippet of the address space near a location.
Stephen Hines6a211c52014-07-21 00:49:56 -0700224static void renderMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
Richard Smith25ee97f2012-12-18 06:30:32 +0000225 Range *Ranges, unsigned NumRanges,
226 const Diag::Arg *Args) {
Richard Smith25ee97f2012-12-18 06:30:32 +0000227 // Show at least the 8 bytes surrounding Loc.
Stephen Hines6d186232014-11-26 17:56:19 -0800228 const unsigned MinBytesNearLoc = 4;
229 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
230 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
231 MemoryLocation OrigMin = Min;
Richard Smith25ee97f2012-12-18 06:30:32 +0000232 for (unsigned I = 0; I < NumRanges; ++I) {
233 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
234 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
235 }
236
237 // If we have too many interesting bytes, prefer to show bytes after Loc.
Stephen Hines6d186232014-11-26 17:56:19 -0800238 const unsigned BytesToShow = 32;
Richard Smith25ee97f2012-12-18 06:30:32 +0000239 if (Max - Min > BytesToShow)
Stephen Hines6d186232014-11-26 17:56:19 -0800240 Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
241 Max = addNoOverflow(Min, BytesToShow);
242
243 if (!IsAccessibleMemoryRange(Min, Max - Min)) {
244 Printf("<memory cannot be printed>\n");
245 return;
246 }
Richard Smith25ee97f2012-12-18 06:30:32 +0000247
248 // Emit data.
249 for (uptr P = Min; P != Max; ++P) {
Richard Smith25ee97f2012-12-18 06:30:32 +0000250 unsigned char C = *reinterpret_cast<const unsigned char*>(P);
251 Printf("%s%02x", (P % 8 == 0) ? " " : " ", C);
252 }
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000253 Printf("\n");
Richard Smith25ee97f2012-12-18 06:30:32 +0000254
255 // Emit highlights.
Stephen Hines6a211c52014-07-21 00:49:56 -0700256 Printf(Decor.Highlight());
Richard Smith25ee97f2012-12-18 06:30:32 +0000257 Range *InRange = upperBound(Min, Ranges, NumRanges);
258 for (uptr P = Min; P != Max; ++P) {
259 char Pad = ' ', Byte = ' ';
260 if (InRange && InRange->getEnd().getMemoryLocation() == P)
261 InRange = upperBound(P, Ranges, NumRanges);
262 if (!InRange && P > Loc)
263 break;
264 if (InRange && InRange->getStart().getMemoryLocation() < P)
265 Pad = '~';
266 if (InRange && InRange->getStart().getMemoryLocation() <= P)
267 Byte = '~';
268 char Buffer[] = { Pad, Pad, P == Loc ? '^' : Byte, Byte, 0 };
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000269 Printf((P % 8 == 0) ? Buffer : &Buffer[1]);
Richard Smith25ee97f2012-12-18 06:30:32 +0000270 }
Stephen Hines6a211c52014-07-21 00:49:56 -0700271 Printf("%s\n", Decor.EndHighlight());
Richard Smith25ee97f2012-12-18 06:30:32 +0000272
273 // Go over the line again, and print names for the ranges.
274 InRange = 0;
275 unsigned Spaces = 0;
276 for (uptr P = Min; P != Max; ++P) {
277 if (!InRange || InRange->getEnd().getMemoryLocation() == P)
278 InRange = upperBound(P, Ranges, NumRanges);
279 if (!InRange)
280 break;
281
282 Spaces += (P % 8) == 0 ? 2 : 1;
283
284 if (InRange && InRange->getStart().getMemoryLocation() == P) {
285 while (Spaces--)
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000286 Printf(" ");
Richard Smith25ee97f2012-12-18 06:30:32 +0000287 renderText(InRange->getText(), Args);
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000288 Printf("\n");
Richard Smith25ee97f2012-12-18 06:30:32 +0000289 // FIXME: We only support naming one range for now!
290 break;
291 }
292
293 Spaces += 2;
294 }
295
296 // FIXME: Print names for anything we can identify within the line:
297 //
298 // * If we can identify the memory itself as belonging to a particular
299 // global, stack variable, or dynamic allocation, then do so.
300 //
301 // * If we have a pointer-size, pointer-aligned range highlighted,
302 // determine whether the value of that range is a pointer to an
303 // entity which we can name, and if so, print that name.
304 //
305 // This needs an external symbolizer, or (preferably) ASan instrumentation.
306}
307
308Diag::~Diag() {
Stephen Hines6d186232014-11-26 17:56:19 -0800309 // All diagnostics should be printed under report mutex.
310 CommonSanitizerReportMutex.CheckLocked();
Stephen Hines6a211c52014-07-21 00:49:56 -0700311 Decorator Decor;
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000312 Printf(Decor.Bold());
Richard Smith25ee97f2012-12-18 06:30:32 +0000313
314 renderLocation(Loc);
315
316 switch (Level) {
317 case DL_Error:
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000318 Printf("%s runtime error: %s%s",
Stephen Hines6a211c52014-07-21 00:49:56 -0700319 Decor.Warning(), Decor.EndWarning(), Decor.Bold());
Richard Smith25ee97f2012-12-18 06:30:32 +0000320 break;
321
322 case DL_Note:
Stephen Hines6a211c52014-07-21 00:49:56 -0700323 Printf("%s note: %s", Decor.Note(), Decor.EndNote());
Richard Smith25ee97f2012-12-18 06:30:32 +0000324 break;
325 }
326
327 renderText(Message, Args);
328
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000329 Printf("%s\n", Decor.Default());
Richard Smith25ee97f2012-12-18 06:30:32 +0000330
331 if (Loc.isMemoryLocation())
Alexey Samsonov8f72f7c2013-02-27 12:58:24 +0000332 renderMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges,
Richard Smithc2424462013-02-12 22:12:10 +0000333 NumRanges, Args);
Richard Smith6ebe4512012-10-09 19:34:32 +0000334}
Stephen Hines6d186232014-11-26 17:56:19 -0800335
336ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc)
337 : Opts(Opts), SummaryLoc(SummaryLoc) {
Pirama Arumuga Nainar259f7062015-05-06 11:49:53 -0700338 InitAsStandaloneIfNecessary();
Stephen Hines6d186232014-11-26 17:56:19 -0800339 CommonSanitizerReportMutex.Lock();
340}
341
342ScopedReport::~ScopedReport() {
343 MaybePrintStackTrace(Opts.pc, Opts.bp);
344 MaybeReportErrorSummary(SummaryLoc);
345 CommonSanitizerReportMutex.Unlock();
346 if (Opts.DieAfterReport || flags()->halt_on_error)
347 Die();
348}
349
Stephen Hines86277eb2015-03-23 12:06:32 -0700350ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];
351static SuppressionContext *suppression_ctx = nullptr;
352static const char kVptrCheck[] = "vptr_check";
353static const char *kSuppressionTypes[] = { kVptrCheck };
354
355void __ubsan::InitializeSuppressions() {
356 CHECK_EQ(nullptr, suppression_ctx);
357 suppression_ctx = new (suppression_placeholder) // NOLINT
358 SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));
359 suppression_ctx->ParseFromFile(flags()->suppressions);
360}
361
362bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {
Pirama Arumuga Nainar259f7062015-05-06 11:49:53 -0700363 InitAsStandaloneIfNecessary();
Stephen Hines86277eb2015-03-23 12:06:32 -0700364 CHECK(suppression_ctx);
365 Suppression *s;
366 return suppression_ctx->Match(TypeName, kVptrCheck, &s);
Stephen Hines6d186232014-11-26 17:56:19 -0800367}
Pirama Arumuga Nainar7c915052015-04-08 08:58:29 -0700368
369#endif // CAN_SANITIZE_UB