* Add missing ChangeLog entry.
[official-gcc.git] / libsanitizer / ubsan / ubsan_diag.cc
blob828127ab84d95b5e711acdd73aef834ad2185ffb
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 //===----------------------------------------------------------------------===//
12 #include "ubsan_diag.h"
13 #include "ubsan_init.h"
14 #include "ubsan_flags.h"
15 #include "sanitizer_common/sanitizer_report_decorator.h"
16 #include "sanitizer_common/sanitizer_stacktrace.h"
17 #include "sanitizer_common/sanitizer_symbolizer.h"
18 #include <stdio.h>
20 using namespace __ubsan;
22 static void MaybePrintStackTrace(uptr pc, uptr bp) {
23 // We assume that flags are already parsed: InitIfNecessary
24 // will definitely be called when we print the first diagnostics message.
25 if (!flags()->print_stacktrace)
26 return;
27 // We can only use slow unwind, as we don't have any information about stack
28 // top/bottom.
29 // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and
30 // fetch stack top/bottom information if we have it (e.g. if we're running
31 // under ASan).
32 if (StackTrace::WillUseFastUnwind(false))
33 return;
34 StackTrace stack;
35 stack.Unwind(kStackTraceMax, pc, bp, 0, 0, 0, false);
36 stack.Print();
39 static void MaybeReportErrorSummary(Location Loc) {
40 if (!common_flags()->print_summary)
41 return;
42 // Don't try to unwind the stack trace in UBSan summaries: just use the
43 // provided location.
44 if (Loc.isSourceLocation()) {
45 SourceLocation SLoc = Loc.getSourceLocation();
46 if (!SLoc.isInvalid()) {
47 ReportErrorSummary("runtime-error", SLoc.getFilename(), SLoc.getLine(),
48 "");
49 return;
52 ReportErrorSummary("runtime-error");
55 namespace {
56 class Decorator : public SanitizerCommonDecorator {
57 public:
58 Decorator() : SanitizerCommonDecorator() {}
59 const char *Highlight() const { return Green(); }
60 const char *EndHighlight() const { return Default(); }
61 const char *Note() const { return Black(); }
62 const char *EndNote() const { return Default(); }
66 Location __ubsan::getCallerLocation(uptr CallerLoc) {
67 if (!CallerLoc)
68 return Location();
70 uptr Loc = StackTrace::GetPreviousInstructionPc(CallerLoc);
71 return getFunctionLocation(Loc, 0);
74 Location __ubsan::getFunctionLocation(uptr Loc, const char **FName) {
75 if (!Loc)
76 return Location();
77 InitIfNecessary();
79 AddressInfo Info;
80 if (!Symbolizer::GetOrInit()->SymbolizePC(Loc, &Info, 1) || !Info.module ||
81 !*Info.module)
82 return Location(Loc);
84 if (FName && Info.function)
85 *FName = Info.function;
87 if (!Info.file)
88 return ModuleLocation(Info.module, Info.module_offset);
90 return SourceLocation(Info.file, Info.line, Info.column);
93 Diag &Diag::operator<<(const TypeDescriptor &V) {
94 return AddArg(V.getTypeName());
97 Diag &Diag::operator<<(const Value &V) {
98 if (V.getType().isSignedIntegerTy())
99 AddArg(V.getSIntValue());
100 else if (V.getType().isUnsignedIntegerTy())
101 AddArg(V.getUIntValue());
102 else if (V.getType().isFloatTy())
103 AddArg(V.getFloatValue());
104 else
105 AddArg("<unknown>");
106 return *this;
109 /// Hexadecimal printing for numbers too large for Printf to handle directly.
110 static void PrintHex(UIntMax Val) {
111 #if HAVE_INT128_T
112 Printf("0x%08x%08x%08x%08x",
113 (unsigned int)(Val >> 96),
114 (unsigned int)(Val >> 64),
115 (unsigned int)(Val >> 32),
116 (unsigned int)(Val));
117 #else
118 UNREACHABLE("long long smaller than 64 bits?");
119 #endif
122 static void renderLocation(Location Loc) {
123 InternalScopedString LocBuffer(1024);
124 switch (Loc.getKind()) {
125 case Location::LK_Source: {
126 SourceLocation SLoc = Loc.getSourceLocation();
127 if (SLoc.isInvalid())
128 LocBuffer.append("<unknown>");
129 else
130 PrintSourceLocation(&LocBuffer, SLoc.getFilename(), SLoc.getLine(),
131 SLoc.getColumn());
132 break;
134 case Location::LK_Module:
135 PrintModuleAndOffset(&LocBuffer, Loc.getModuleLocation().getModuleName(),
136 Loc.getModuleLocation().getOffset());
137 break;
138 case Location::LK_Memory:
139 LocBuffer.append("%p", Loc.getMemoryLocation());
140 break;
141 case Location::LK_Null:
142 LocBuffer.append("<unknown>");
143 break;
145 Printf("%s:", LocBuffer.data());
148 static void renderText(const char *Message, const Diag::Arg *Args) {
149 for (const char *Msg = Message; *Msg; ++Msg) {
150 if (*Msg != '%') {
151 char Buffer[64];
152 unsigned I;
153 for (I = 0; Msg[I] && Msg[I] != '%' && I != 63; ++I)
154 Buffer[I] = Msg[I];
155 Buffer[I] = '\0';
156 Printf(Buffer);
157 Msg += I - 1;
158 } else {
159 const Diag::Arg &A = Args[*++Msg - '0'];
160 switch (A.Kind) {
161 case Diag::AK_String:
162 Printf("%s", A.String);
163 break;
164 case Diag::AK_Mangled: {
165 Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));
166 break;
168 case Diag::AK_SInt:
169 // 'long long' is guaranteed to be at least 64 bits wide.
170 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)
171 Printf("%lld", (long long)A.SInt);
172 else
173 PrintHex(A.SInt);
174 break;
175 case Diag::AK_UInt:
176 if (A.UInt <= UINT64_MAX)
177 Printf("%llu", (unsigned long long)A.UInt);
178 else
179 PrintHex(A.UInt);
180 break;
181 case Diag::AK_Float: {
182 // FIXME: Support floating-point formatting in sanitizer_common's
183 // printf, and stop using snprintf here.
184 char Buffer[32];
185 snprintf(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float);
186 Printf("%s", Buffer);
187 break;
189 case Diag::AK_Pointer:
190 Printf("%p", A.Pointer);
191 break;
197 /// Find the earliest-starting range in Ranges which ends after Loc.
198 static Range *upperBound(MemoryLocation Loc, Range *Ranges,
199 unsigned NumRanges) {
200 Range *Best = 0;
201 for (unsigned I = 0; I != NumRanges; ++I)
202 if (Ranges[I].getEnd().getMemoryLocation() > Loc &&
203 (!Best ||
204 Best->getStart().getMemoryLocation() >
205 Ranges[I].getStart().getMemoryLocation()))
206 Best = &Ranges[I];
207 return Best;
210 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {
211 return (LHS < RHS) ? 0 : LHS - RHS;
214 static inline uptr addNoOverflow(uptr LHS, uptr RHS) {
215 const uptr Limit = (uptr)-1;
216 return (LHS > Limit - RHS) ? Limit : LHS + RHS;
219 /// Render a snippet of the address space near a location.
220 static void renderMemorySnippet(const Decorator &Decor, MemoryLocation Loc,
221 Range *Ranges, unsigned NumRanges,
222 const Diag::Arg *Args) {
223 // Show at least the 8 bytes surrounding Loc.
224 const unsigned MinBytesNearLoc = 4;
225 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);
226 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);
227 MemoryLocation OrigMin = Min;
228 for (unsigned I = 0; I < NumRanges; ++I) {
229 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);
230 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);
233 // If we have too many interesting bytes, prefer to show bytes after Loc.
234 const unsigned BytesToShow = 32;
235 if (Max - Min > BytesToShow)
236 Min = __sanitizer::Min(Max - BytesToShow, OrigMin);
237 Max = addNoOverflow(Min, BytesToShow);
239 if (!IsAccessibleMemoryRange(Min, Max - Min)) {
240 Printf("<memory cannot be printed>\n");
241 return;
244 // Emit data.
245 for (uptr P = Min; P != Max; ++P) {
246 unsigned char C = *reinterpret_cast<const unsigned char*>(P);
247 Printf("%s%02x", (P % 8 == 0) ? " " : " ", C);
249 Printf("\n");
251 // Emit highlights.
252 Printf(Decor.Highlight());
253 Range *InRange = upperBound(Min, Ranges, NumRanges);
254 for (uptr P = Min; P != Max; ++P) {
255 char Pad = ' ', Byte = ' ';
256 if (InRange && InRange->getEnd().getMemoryLocation() == P)
257 InRange = upperBound(P, Ranges, NumRanges);
258 if (!InRange && P > Loc)
259 break;
260 if (InRange && InRange->getStart().getMemoryLocation() < P)
261 Pad = '~';
262 if (InRange && InRange->getStart().getMemoryLocation() <= P)
263 Byte = '~';
264 char Buffer[] = { Pad, Pad, P == Loc ? '^' : Byte, Byte, 0 };
265 Printf((P % 8 == 0) ? Buffer : &Buffer[1]);
267 Printf("%s\n", Decor.EndHighlight());
269 // Go over the line again, and print names for the ranges.
270 InRange = 0;
271 unsigned Spaces = 0;
272 for (uptr P = Min; P != Max; ++P) {
273 if (!InRange || InRange->getEnd().getMemoryLocation() == P)
274 InRange = upperBound(P, Ranges, NumRanges);
275 if (!InRange)
276 break;
278 Spaces += (P % 8) == 0 ? 2 : 1;
280 if (InRange && InRange->getStart().getMemoryLocation() == P) {
281 while (Spaces--)
282 Printf(" ");
283 renderText(InRange->getText(), Args);
284 Printf("\n");
285 // FIXME: We only support naming one range for now!
286 break;
289 Spaces += 2;
292 // FIXME: Print names for anything we can identify within the line:
294 // * If we can identify the memory itself as belonging to a particular
295 // global, stack variable, or dynamic allocation, then do so.
297 // * If we have a pointer-size, pointer-aligned range highlighted,
298 // determine whether the value of that range is a pointer to an
299 // entity which we can name, and if so, print that name.
301 // This needs an external symbolizer, or (preferably) ASan instrumentation.
304 Diag::~Diag() {
305 // All diagnostics should be printed under report mutex.
306 CommonSanitizerReportMutex.CheckLocked();
307 Decorator Decor;
308 Printf(Decor.Bold());
310 renderLocation(Loc);
312 switch (Level) {
313 case DL_Error:
314 Printf("%s runtime error: %s%s",
315 Decor.Warning(), Decor.EndWarning(), Decor.Bold());
316 break;
318 case DL_Note:
319 Printf("%s note: %s", Decor.Note(), Decor.EndNote());
320 break;
323 renderText(Message, Args);
325 Printf("%s\n", Decor.Default());
327 if (Loc.isMemoryLocation())
328 renderMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges,
329 NumRanges, Args);
332 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc)
333 : Opts(Opts), SummaryLoc(SummaryLoc) {
334 InitIfNecessary();
335 CommonSanitizerReportMutex.Lock();
338 ScopedReport::~ScopedReport() {
339 MaybePrintStackTrace(Opts.pc, Opts.bp);
340 MaybeReportErrorSummary(SummaryLoc);
341 CommonSanitizerReportMutex.Unlock();
342 if (Opts.DieAfterReport || flags()->halt_on_error)
343 Die();
346 bool __ubsan::MatchSuppression(const char *Str, SuppressionType Type) {
347 Suppression *s;
348 // If .preinit_array is not used, it is possible that the UBSan runtime is not
349 // initialized.
350 if (!SANITIZER_CAN_USE_PREINIT_ARRAY)
351 InitIfNecessary();
352 return SuppressionContext::Get()->Match(Str, Type, &s);