[gcc/testsuite]
[official-gcc.git] / libsanitizer / asan / asan_report.cc
blob84d67646b403a6e03934c1cec6650e024c642f5f
1 //===-- asan_report.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 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // This file contains error reporting code.
11 //===----------------------------------------------------------------------===//
13 #include "asan_errors.h"
14 #include "asan_flags.h"
15 #include "asan_descriptions.h"
16 #include "asan_internal.h"
17 #include "asan_mapping.h"
18 #include "asan_report.h"
19 #include "asan_scariness_score.h"
20 #include "asan_stack.h"
21 #include "asan_thread.h"
22 #include "sanitizer_common/sanitizer_common.h"
23 #include "sanitizer_common/sanitizer_flags.h"
24 #include "sanitizer_common/sanitizer_report_decorator.h"
25 #include "sanitizer_common/sanitizer_stackdepot.h"
26 #include "sanitizer_common/sanitizer_symbolizer.h"
28 namespace __asan {
30 // -------------------- User-specified callbacks ----------------- {{{1
31 static void (*error_report_callback)(const char*);
32 static char *error_message_buffer = nullptr;
33 static uptr error_message_buffer_pos = 0;
34 static BlockingMutex error_message_buf_mutex(LINKER_INITIALIZED);
35 static const unsigned kAsanBuggyPcPoolSize = 25;
36 static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];
38 void AppendToErrorMessageBuffer(const char *buffer) {
39 BlockingMutexLock l(&error_message_buf_mutex);
40 if (!error_message_buffer) {
41 error_message_buffer =
42 (char*)MmapOrDieQuietly(kErrorMessageBufferSize, __func__);
43 error_message_buffer_pos = 0;
45 uptr length = internal_strlen(buffer);
46 RAW_CHECK(kErrorMessageBufferSize >= error_message_buffer_pos);
47 uptr remaining = kErrorMessageBufferSize - error_message_buffer_pos;
48 internal_strncpy(error_message_buffer + error_message_buffer_pos,
49 buffer, remaining);
50 error_message_buffer[kErrorMessageBufferSize - 1] = '\0';
51 // FIXME: reallocate the buffer instead of truncating the message.
52 error_message_buffer_pos += Min(remaining, length);
55 // ---------------------- Helper functions ----------------------- {{{1
57 void PrintMemoryByte(InternalScopedString *str, const char *before, u8 byte,
58 bool in_shadow, const char *after) {
59 Decorator d;
60 str->append("%s%s%x%x%s%s", before,
61 in_shadow ? d.ShadowByte(byte) : d.MemoryByte(),
62 byte >> 4, byte & 15,
63 in_shadow ? d.EndShadowByte() : d.EndMemoryByte(), after);
66 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
67 const char *zone_name) {
68 if (zone_ptr) {
69 if (zone_name) {
70 Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
71 ptr, zone_ptr, zone_name);
72 } else {
73 Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
74 ptr, zone_ptr);
76 } else {
77 Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
81 // ---------------------- Address Descriptions ------------------- {{{1
83 bool ParseFrameDescription(const char *frame_descr,
84 InternalMmapVector<StackVarDescr> *vars) {
85 CHECK(frame_descr);
86 char *p;
87 // This string is created by the compiler and has the following form:
88 // "n alloc_1 alloc_2 ... alloc_n"
89 // where alloc_i looks like "offset size len ObjectName".
90 uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
91 if (n_objects == 0)
92 return false;
94 for (uptr i = 0; i < n_objects; i++) {
95 uptr beg = (uptr)internal_simple_strtoll(p, &p, 10);
96 uptr size = (uptr)internal_simple_strtoll(p, &p, 10);
97 uptr len = (uptr)internal_simple_strtoll(p, &p, 10);
98 if (beg == 0 || size == 0 || *p != ' ') {
99 return false;
101 p++;
102 StackVarDescr var = {beg, size, p, len};
103 vars->push_back(var);
104 p += len;
107 return true;
110 // -------------------- Different kinds of reports ----------------- {{{1
112 // Use ScopedInErrorReport to run common actions just before and
113 // immediately after printing error report.
114 class ScopedInErrorReport {
115 public:
116 explicit ScopedInErrorReport(bool fatal = false) {
117 halt_on_error_ = fatal || flags()->halt_on_error;
119 if (lock_.TryLock()) {
120 StartReporting();
121 return;
124 // ASan found two bugs in different threads simultaneously.
126 u32 current_tid = GetCurrentTidOrInvalid();
127 if (reporting_thread_tid_ == current_tid ||
128 reporting_thread_tid_ == kInvalidTid) {
129 // This is either asynch signal or nested error during error reporting.
130 // Fail simple to avoid deadlocks in Report().
132 // Can't use Report() here because of potential deadlocks
133 // in nested signal handlers.
134 const char msg[] = "AddressSanitizer: nested bug in the same thread, "
135 "aborting.\n";
136 WriteToFile(kStderrFd, msg, sizeof(msg));
138 internal__exit(common_flags()->exitcode);
141 if (halt_on_error_) {
142 // Do not print more than one report, otherwise they will mix up.
143 // Error reporting functions shouldn't return at this situation, as
144 // they are effectively no-returns.
146 Report("AddressSanitizer: while reporting a bug found another one. "
147 "Ignoring.\n");
149 // Sleep long enough to make sure that the thread which started
150 // to print an error report will finish doing it.
151 SleepForSeconds(Max(100, flags()->sleep_before_dying + 1));
153 // If we're still not dead for some reason, use raw _exit() instead of
154 // Die() to bypass any additional checks.
155 internal__exit(common_flags()->exitcode);
156 } else {
157 // The other thread will eventually finish reporting
158 // so it's safe to wait
159 lock_.Lock();
162 StartReporting();
165 ~ScopedInErrorReport() {
166 ASAN_ON_ERROR();
167 if (current_error_.IsValid()) current_error_.Print();
169 // Make sure the current thread is announced.
170 DescribeThread(GetCurrentThread());
171 // We may want to grab this lock again when printing stats.
172 asanThreadRegistry().Unlock();
173 // Print memory stats.
174 if (flags()->print_stats)
175 __asan_print_accumulated_stats();
177 if (common_flags()->print_cmdline)
178 PrintCmdline();
180 // Copy the message buffer so that we could start logging without holding a
181 // lock that gets aquired during printing.
182 InternalScopedBuffer<char> buffer_copy(kErrorMessageBufferSize);
184 BlockingMutexLock l(&error_message_buf_mutex);
185 internal_memcpy(buffer_copy.data(),
186 error_message_buffer, kErrorMessageBufferSize);
189 LogFullErrorReport(buffer_copy.data());
191 if (error_report_callback) {
192 error_report_callback(buffer_copy.data());
195 // In halt_on_error = false mode, reset the current error object (before
196 // unlocking).
197 if (!halt_on_error_)
198 internal_memset(&current_error_, 0, sizeof(current_error_));
200 CommonSanitizerReportMutex.Unlock();
201 reporting_thread_tid_ = kInvalidTid;
202 lock_.Unlock();
203 if (halt_on_error_) {
204 Report("ABORTING\n");
205 Die();
209 void ReportError(const ErrorDescription &description) {
210 // Can only report one error per ScopedInErrorReport.
211 CHECK_EQ(current_error_.kind, kErrorKindInvalid);
212 current_error_ = description;
215 static ErrorDescription &CurrentError() {
216 return current_error_;
219 private:
220 void StartReporting() {
221 // Make sure the registry and sanitizer report mutexes are locked while
222 // we're printing an error report.
223 // We can lock them only here to avoid self-deadlock in case of
224 // recursive reports.
225 asanThreadRegistry().Lock();
226 CommonSanitizerReportMutex.Lock();
227 reporting_thread_tid_ = GetCurrentTidOrInvalid();
228 Printf("===================================================="
229 "=============\n");
232 static StaticSpinMutex lock_;
233 static u32 reporting_thread_tid_;
234 // Error currently being reported. This enables the destructor to interact
235 // with the debugger and point it to an error description.
236 static ErrorDescription current_error_;
237 bool halt_on_error_;
240 StaticSpinMutex ScopedInErrorReport::lock_;
241 u32 ScopedInErrorReport::reporting_thread_tid_ = kInvalidTid;
242 ErrorDescription ScopedInErrorReport::current_error_;
244 void ReportStackOverflow(const SignalContext &sig) {
245 ScopedInErrorReport in_report(/*fatal*/ true);
246 ErrorStackOverflow error(GetCurrentTidOrInvalid(), sig);
247 in_report.ReportError(error);
250 void ReportDeadlySignal(int signo, const SignalContext &sig) {
251 ScopedInErrorReport in_report(/*fatal*/ true);
252 ErrorDeadlySignal error(GetCurrentTidOrInvalid(), sig, signo);
253 in_report.ReportError(error);
256 void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {
257 ScopedInErrorReport in_report;
258 ErrorDoubleFree error(GetCurrentTidOrInvalid(), free_stack, addr);
259 in_report.ReportError(error);
262 void ReportNewDeleteSizeMismatch(uptr addr, uptr delete_size,
263 BufferedStackTrace *free_stack) {
264 ScopedInErrorReport in_report;
265 ErrorNewDeleteSizeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
266 delete_size);
267 in_report.ReportError(error);
270 void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {
271 ScopedInErrorReport in_report;
272 ErrorFreeNotMalloced error(GetCurrentTidOrInvalid(), free_stack, addr);
273 in_report.ReportError(error);
276 void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,
277 AllocType alloc_type,
278 AllocType dealloc_type) {
279 ScopedInErrorReport in_report;
280 ErrorAllocTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
281 alloc_type, dealloc_type);
282 in_report.ReportError(error);
285 void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {
286 ScopedInErrorReport in_report;
287 ErrorMallocUsableSizeNotOwned error(GetCurrentTidOrInvalid(), stack, addr);
288 in_report.ReportError(error);
291 void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,
292 BufferedStackTrace *stack) {
293 ScopedInErrorReport in_report;
294 ErrorSanitizerGetAllocatedSizeNotOwned error(GetCurrentTidOrInvalid(), stack,
295 addr);
296 in_report.ReportError(error);
299 void ReportStringFunctionMemoryRangesOverlap(const char *function,
300 const char *offset1, uptr length1,
301 const char *offset2, uptr length2,
302 BufferedStackTrace *stack) {
303 ScopedInErrorReport in_report;
304 ErrorStringFunctionMemoryRangesOverlap error(
305 GetCurrentTidOrInvalid(), stack, (uptr)offset1, length1, (uptr)offset2,
306 length2, function);
307 in_report.ReportError(error);
310 void ReportStringFunctionSizeOverflow(uptr offset, uptr size,
311 BufferedStackTrace *stack) {
312 ScopedInErrorReport in_report;
313 ErrorStringFunctionSizeOverflow error(GetCurrentTidOrInvalid(), stack, offset,
314 size);
315 in_report.ReportError(error);
318 void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,
319 uptr old_mid, uptr new_mid,
320 BufferedStackTrace *stack) {
321 ScopedInErrorReport in_report;
322 ErrorBadParamsToAnnotateContiguousContainer error(
323 GetCurrentTidOrInvalid(), stack, beg, end, old_mid, new_mid);
324 in_report.ReportError(error);
327 void ReportODRViolation(const __asan_global *g1, u32 stack_id1,
328 const __asan_global *g2, u32 stack_id2) {
329 ScopedInErrorReport in_report;
330 ErrorODRViolation error(GetCurrentTidOrInvalid(), g1, stack_id1, g2,
331 stack_id2);
332 in_report.ReportError(error);
335 // ----------------------- CheckForInvalidPointerPair ----------- {{{1
336 static NOINLINE void ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp,
337 uptr a1, uptr a2) {
338 ScopedInErrorReport in_report;
339 ErrorInvalidPointerPair error(GetCurrentTidOrInvalid(), pc, bp, sp, a1, a2);
340 in_report.ReportError(error);
343 static INLINE void CheckForInvalidPointerPair(void *p1, void *p2) {
344 if (!flags()->detect_invalid_pointer_pairs) return;
345 uptr a1 = reinterpret_cast<uptr>(p1);
346 uptr a2 = reinterpret_cast<uptr>(p2);
347 AsanChunkView chunk1 = FindHeapChunkByAddress(a1);
348 AsanChunkView chunk2 = FindHeapChunkByAddress(a2);
349 bool valid1 = chunk1.IsAllocated();
350 bool valid2 = chunk2.IsAllocated();
351 if (!valid1 || !valid2 || !chunk1.Eq(chunk2)) {
352 GET_CALLER_PC_BP_SP;
353 return ReportInvalidPointerPair(pc, bp, sp, a1, a2);
356 // ----------------------- Mac-specific reports ----------------- {{{1
358 void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,
359 BufferedStackTrace *stack) {
360 ScopedInErrorReport in_report;
361 Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
362 "This is an unrecoverable problem, exiting now.\n",
363 addr);
364 PrintZoneForPointer(addr, zone_ptr, zone_name);
365 stack->Print();
366 DescribeAddressIfHeap(addr);
369 // -------------- SuppressErrorReport -------------- {{{1
370 // Avoid error reports duplicating for ASan recover mode.
371 static bool SuppressErrorReport(uptr pc) {
372 if (!common_flags()->suppress_equal_pcs) return false;
373 for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {
374 uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);
375 if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,
376 pc, memory_order_relaxed))
377 return false;
378 if (cmp == pc) return true;
380 Die();
383 void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,
384 uptr access_size, u32 exp, bool fatal) {
385 if (!fatal && SuppressErrorReport(pc)) return;
386 ENABLE_FRAME_POINTER;
388 // Optimization experiments.
389 // The experiments can be used to evaluate potential optimizations that remove
390 // instrumentation (assess false negatives). Instead of completely removing
391 // some instrumentation, compiler can emit special calls into runtime
392 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass
393 // mask of experiments (exp).
394 // The reaction to a non-zero value of exp is to be defined.
395 (void)exp;
397 ScopedInErrorReport in_report(fatal);
398 ErrorGeneric error(GetCurrentTidOrInvalid(), pc, bp, sp, addr, is_write,
399 access_size);
400 in_report.ReportError(error);
403 } // namespace __asan
405 // --------------------------- Interface --------------------- {{{1
406 using namespace __asan; // NOLINT
408 void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
409 uptr access_size, u32 exp) {
410 ENABLE_FRAME_POINTER;
411 bool fatal = flags()->halt_on_error;
412 ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);
415 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
416 BlockingMutexLock l(&error_message_buf_mutex);
417 error_report_callback = callback;
420 void __asan_describe_address(uptr addr) {
421 // Thread registry must be locked while we're describing an address.
422 asanThreadRegistry().Lock();
423 PrintAddressDescription(addr, 1, "");
424 asanThreadRegistry().Unlock();
427 int __asan_report_present() {
428 return ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric;
431 uptr __asan_get_report_pc() {
432 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
433 return ScopedInErrorReport::CurrentError().Generic.pc;
434 return 0;
437 uptr __asan_get_report_bp() {
438 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
439 return ScopedInErrorReport::CurrentError().Generic.bp;
440 return 0;
443 uptr __asan_get_report_sp() {
444 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
445 return ScopedInErrorReport::CurrentError().Generic.sp;
446 return 0;
449 uptr __asan_get_report_address() {
450 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
451 return ScopedInErrorReport::CurrentError()
452 .Generic.addr_description.Address();
453 return 0;
456 int __asan_get_report_access_type() {
457 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
458 return ScopedInErrorReport::CurrentError().Generic.is_write;
459 return 0;
462 uptr __asan_get_report_access_size() {
463 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
464 return ScopedInErrorReport::CurrentError().Generic.access_size;
465 return 0;
468 const char *__asan_get_report_description() {
469 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
470 return ScopedInErrorReport::CurrentError().Generic.bug_descr;
471 return nullptr;
474 extern "C" {
475 SANITIZER_INTERFACE_ATTRIBUTE
476 void __sanitizer_ptr_sub(void *a, void *b) {
477 CheckForInvalidPointerPair(a, b);
479 SANITIZER_INTERFACE_ATTRIBUTE
480 void __sanitizer_ptr_cmp(void *a, void *b) {
481 CheckForInvalidPointerPair(a, b);
483 } // extern "C"
485 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
486 // Provide default implementation of __asan_on_error that does nothing
487 // and may be overriden by user.
488 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE
489 void __asan_on_error() {}
490 #endif