1 //===-- asan_report.cc ----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 // This file contains error reporting code.
13 //===----------------------------------------------------------------------===//
15 #include "asan_errors.h"
16 #include "asan_flags.h"
17 #include "asan_descriptions.h"
18 #include "asan_internal.h"
19 #include "asan_mapping.h"
20 #include "asan_report.h"
21 #include "asan_scariness_score.h"
22 #include "asan_stack.h"
23 #include "asan_thread.h"
24 #include "sanitizer_common/sanitizer_common.h"
25 #include "sanitizer_common/sanitizer_flags.h"
26 #include "sanitizer_common/sanitizer_report_decorator.h"
27 #include "sanitizer_common/sanitizer_stackdepot.h"
28 #include "sanitizer_common/sanitizer_symbolizer.h"
32 // -------------------- User-specified callbacks ----------------- {{{1
33 static void (*error_report_callback)(const char*);
34 static char *error_message_buffer = nullptr;
35 static uptr error_message_buffer_pos = 0;
36 static BlockingMutex error_message_buf_mutex(LINKER_INITIALIZED);
37 static const unsigned kAsanBuggyPcPoolSize = 25;
38 static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];
40 void AppendToErrorMessageBuffer(const char *buffer) {
41 BlockingMutexLock l(&error_message_buf_mutex);
42 if (!error_message_buffer) {
43 error_message_buffer =
44 (char*)MmapOrDieQuietly(kErrorMessageBufferSize, __func__);
45 error_message_buffer_pos = 0;
47 uptr length = internal_strlen(buffer);
48 RAW_CHECK(kErrorMessageBufferSize >= error_message_buffer_pos);
49 uptr remaining = kErrorMessageBufferSize - error_message_buffer_pos;
50 internal_strncpy(error_message_buffer + error_message_buffer_pos,
52 error_message_buffer[kErrorMessageBufferSize - 1] = '\0';
53 // FIXME: reallocate the buffer instead of truncating the message.
54 error_message_buffer_pos += Min(remaining, length);
57 // ---------------------- Helper functions ----------------------- {{{1
59 void PrintMemoryByte(InternalScopedString *str, const char *before, u8 byte,
60 bool in_shadow, const char *after) {
62 str->append("%s%s%x%x%s%s", before,
63 in_shadow ? d.ShadowByte(byte) : d.MemoryByte(),
65 in_shadow ? d.EndShadowByte() : d.EndMemoryByte(), after);
68 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
69 const char *zone_name) {
72 Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
73 ptr, zone_ptr, zone_name);
75 Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
79 Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
83 // ---------------------- Address Descriptions ------------------- {{{1
85 bool ParseFrameDescription(const char *frame_descr,
86 InternalMmapVector<StackVarDescr> *vars) {
89 // This string is created by the compiler and has the following form:
90 // "n alloc_1 alloc_2 ... alloc_n"
91 // where alloc_i looks like "offset size len ObjectName".
92 uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
96 for (uptr i = 0; i < n_objects; i++) {
97 uptr beg = (uptr)internal_simple_strtoll(p, &p, 10);
98 uptr size = (uptr)internal_simple_strtoll(p, &p, 10);
99 uptr len = (uptr)internal_simple_strtoll(p, &p, 10);
100 if (beg == 0 || size == 0 || *p != ' ') {
104 StackVarDescr var = {beg, size, p, len};
105 vars->push_back(var);
112 // -------------------- Different kinds of reports ----------------- {{{1
114 // Use ScopedInErrorReport to run common actions just before and
115 // immediately after printing error report.
116 class ScopedInErrorReport {
118 explicit ScopedInErrorReport(bool fatal = false) {
119 halt_on_error_ = fatal || flags()->halt_on_error;
121 if (lock_.TryLock()) {
126 // ASan found two bugs in different threads simultaneously.
128 u32 current_tid = GetCurrentTidOrInvalid();
129 if (reporting_thread_tid_ == current_tid ||
130 reporting_thread_tid_ == kInvalidTid) {
131 // This is either asynch signal or nested error during error reporting.
132 // Fail simple to avoid deadlocks in Report().
134 // Can't use Report() here because of potential deadlocks
135 // in nested signal handlers.
136 const char msg[] = "AddressSanitizer: nested bug in the same thread, "
138 WriteToFile(kStderrFd, msg, sizeof(msg));
140 internal__exit(common_flags()->exitcode);
143 if (halt_on_error_) {
144 // Do not print more than one report, otherwise they will mix up.
145 // Error reporting functions shouldn't return at this situation, as
146 // they are effectively no-returns.
148 Report("AddressSanitizer: while reporting a bug found another one. "
151 // Sleep long enough to make sure that the thread which started
152 // to print an error report will finish doing it.
153 SleepForSeconds(Max(100, flags()->sleep_before_dying + 1));
155 // If we're still not dead for some reason, use raw _exit() instead of
156 // Die() to bypass any additional checks.
157 internal__exit(common_flags()->exitcode);
159 // The other thread will eventually finish reporting
160 // so it's safe to wait
167 ~ScopedInErrorReport() {
169 if (current_error_.IsValid()) current_error_.Print();
171 // Make sure the current thread is announced.
172 DescribeThread(GetCurrentThread());
173 // We may want to grab this lock again when printing stats.
174 asanThreadRegistry().Unlock();
175 // Print memory stats.
176 if (flags()->print_stats)
177 __asan_print_accumulated_stats();
179 if (common_flags()->print_cmdline)
182 if (common_flags()->print_module_map == 2) PrintModuleMap();
184 // Copy the message buffer so that we could start logging without holding a
185 // lock that gets aquired during printing.
186 InternalScopedBuffer<char> buffer_copy(kErrorMessageBufferSize);
188 BlockingMutexLock l(&error_message_buf_mutex);
189 internal_memcpy(buffer_copy.data(),
190 error_message_buffer, kErrorMessageBufferSize);
193 LogFullErrorReport(buffer_copy.data());
195 if (error_report_callback) {
196 error_report_callback(buffer_copy.data());
199 // In halt_on_error = false mode, reset the current error object (before
202 internal_memset(¤t_error_, 0, sizeof(current_error_));
204 CommonSanitizerReportMutex.Unlock();
205 reporting_thread_tid_ = kInvalidTid;
207 if (halt_on_error_) {
208 Report("ABORTING\n");
213 void ReportError(const ErrorDescription &description) {
214 // Can only report one error per ScopedInErrorReport.
215 CHECK_EQ(current_error_.kind, kErrorKindInvalid);
216 current_error_ = description;
219 static ErrorDescription &CurrentError() {
220 return current_error_;
224 void StartReporting() {
225 // Make sure the registry and sanitizer report mutexes are locked while
226 // we're printing an error report.
227 // We can lock them only here to avoid self-deadlock in case of
228 // recursive reports.
229 asanThreadRegistry().Lock();
230 CommonSanitizerReportMutex.Lock();
231 reporting_thread_tid_ = GetCurrentTidOrInvalid();
232 Printf("===================================================="
236 static StaticSpinMutex lock_;
237 static u32 reporting_thread_tid_;
238 // Error currently being reported. This enables the destructor to interact
239 // with the debugger and point it to an error description.
240 static ErrorDescription current_error_;
244 StaticSpinMutex ScopedInErrorReport::lock_;
245 u32 ScopedInErrorReport::reporting_thread_tid_ = kInvalidTid;
246 ErrorDescription ScopedInErrorReport::current_error_;
248 void ReportStackOverflow(const SignalContext &sig) {
249 ScopedInErrorReport in_report(/*fatal*/ true);
250 ErrorStackOverflow error(GetCurrentTidOrInvalid(), sig);
251 in_report.ReportError(error);
254 void ReportDeadlySignal(int signo, const SignalContext &sig) {
255 ScopedInErrorReport in_report(/*fatal*/ true);
256 ErrorDeadlySignal error(GetCurrentTidOrInvalid(), sig, signo);
257 in_report.ReportError(error);
260 void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {
261 ScopedInErrorReport in_report;
262 ErrorDoubleFree error(GetCurrentTidOrInvalid(), free_stack, addr);
263 in_report.ReportError(error);
266 void ReportNewDeleteSizeMismatch(uptr addr, uptr delete_size,
267 BufferedStackTrace *free_stack) {
268 ScopedInErrorReport in_report;
269 ErrorNewDeleteSizeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
271 in_report.ReportError(error);
274 void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {
275 ScopedInErrorReport in_report;
276 ErrorFreeNotMalloced error(GetCurrentTidOrInvalid(), free_stack, addr);
277 in_report.ReportError(error);
280 void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,
281 AllocType alloc_type,
282 AllocType dealloc_type) {
283 ScopedInErrorReport in_report;
284 ErrorAllocTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
285 alloc_type, dealloc_type);
286 in_report.ReportError(error);
289 void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {
290 ScopedInErrorReport in_report;
291 ErrorMallocUsableSizeNotOwned error(GetCurrentTidOrInvalid(), stack, addr);
292 in_report.ReportError(error);
295 void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,
296 BufferedStackTrace *stack) {
297 ScopedInErrorReport in_report;
298 ErrorSanitizerGetAllocatedSizeNotOwned error(GetCurrentTidOrInvalid(), stack,
300 in_report.ReportError(error);
303 void ReportStringFunctionMemoryRangesOverlap(const char *function,
304 const char *offset1, uptr length1,
305 const char *offset2, uptr length2,
306 BufferedStackTrace *stack) {
307 ScopedInErrorReport in_report;
308 ErrorStringFunctionMemoryRangesOverlap error(
309 GetCurrentTidOrInvalid(), stack, (uptr)offset1, length1, (uptr)offset2,
311 in_report.ReportError(error);
314 void ReportStringFunctionSizeOverflow(uptr offset, uptr size,
315 BufferedStackTrace *stack) {
316 ScopedInErrorReport in_report;
317 ErrorStringFunctionSizeOverflow error(GetCurrentTidOrInvalid(), stack, offset,
319 in_report.ReportError(error);
322 void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,
323 uptr old_mid, uptr new_mid,
324 BufferedStackTrace *stack) {
325 ScopedInErrorReport in_report;
326 ErrorBadParamsToAnnotateContiguousContainer error(
327 GetCurrentTidOrInvalid(), stack, beg, end, old_mid, new_mid);
328 in_report.ReportError(error);
331 void ReportODRViolation(const __asan_global *g1, u32 stack_id1,
332 const __asan_global *g2, u32 stack_id2) {
333 ScopedInErrorReport in_report;
334 ErrorODRViolation error(GetCurrentTidOrInvalid(), g1, stack_id1, g2,
336 in_report.ReportError(error);
339 // ----------------------- CheckForInvalidPointerPair ----------- {{{1
340 static NOINLINE void ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp,
342 ScopedInErrorReport in_report;
343 ErrorInvalidPointerPair error(GetCurrentTidOrInvalid(), pc, bp, sp, a1, a2);
344 in_report.ReportError(error);
347 static INLINE void CheckForInvalidPointerPair(void *p1, void *p2) {
348 if (!flags()->detect_invalid_pointer_pairs) return;
349 uptr a1 = reinterpret_cast<uptr>(p1);
350 uptr a2 = reinterpret_cast<uptr>(p2);
351 AsanChunkView chunk1 = FindHeapChunkByAddress(a1);
352 AsanChunkView chunk2 = FindHeapChunkByAddress(a2);
353 bool valid1 = chunk1.IsAllocated();
354 bool valid2 = chunk2.IsAllocated();
355 if (!valid1 || !valid2 || !chunk1.Eq(chunk2)) {
357 return ReportInvalidPointerPair(pc, bp, sp, a1, a2);
360 // ----------------------- Mac-specific reports ----------------- {{{1
362 void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,
363 BufferedStackTrace *stack) {
364 ScopedInErrorReport in_report;
365 Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
366 "This is an unrecoverable problem, exiting now.\n",
368 PrintZoneForPointer(addr, zone_ptr, zone_name);
370 DescribeAddressIfHeap(addr);
373 // -------------- SuppressErrorReport -------------- {{{1
374 // Avoid error reports duplicating for ASan recover mode.
375 static bool SuppressErrorReport(uptr pc) {
376 if (!common_flags()->suppress_equal_pcs) return false;
377 for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {
378 uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);
379 if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,
380 pc, memory_order_relaxed))
382 if (cmp == pc) return true;
387 void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,
388 uptr access_size, u32 exp, bool fatal) {
389 if (!fatal && SuppressErrorReport(pc)) return;
390 ENABLE_FRAME_POINTER;
392 // Optimization experiments.
393 // The experiments can be used to evaluate potential optimizations that remove
394 // instrumentation (assess false negatives). Instead of completely removing
395 // some instrumentation, compiler can emit special calls into runtime
396 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass
397 // mask of experiments (exp).
398 // The reaction to a non-zero value of exp is to be defined.
401 ScopedInErrorReport in_report(fatal);
402 ErrorGeneric error(GetCurrentTidOrInvalid(), pc, bp, sp, addr, is_write,
404 in_report.ReportError(error);
407 } // namespace __asan
409 // --------------------------- Interface --------------------- {{{1
410 using namespace __asan; // NOLINT
412 void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
413 uptr access_size, u32 exp) {
414 ENABLE_FRAME_POINTER;
415 bool fatal = flags()->halt_on_error;
416 ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);
419 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
420 BlockingMutexLock l(&error_message_buf_mutex);
421 error_report_callback = callback;
424 void __asan_describe_address(uptr addr) {
425 // Thread registry must be locked while we're describing an address.
426 asanThreadRegistry().Lock();
427 PrintAddressDescription(addr, 1, "");
428 asanThreadRegistry().Unlock();
431 int __asan_report_present() {
432 return ScopedInErrorReport::CurrentError().kind != kErrorKindInvalid;
435 uptr __asan_get_report_pc() {
436 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
437 return ScopedInErrorReport::CurrentError().Generic.pc;
441 uptr __asan_get_report_bp() {
442 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
443 return ScopedInErrorReport::CurrentError().Generic.bp;
447 uptr __asan_get_report_sp() {
448 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
449 return ScopedInErrorReport::CurrentError().Generic.sp;
453 uptr __asan_get_report_address() {
454 ErrorDescription &err = ScopedInErrorReport::CurrentError();
455 if (err.kind == kErrorKindGeneric)
456 return err.Generic.addr_description.Address();
457 else if (err.kind == kErrorKindDoubleFree)
458 return err.DoubleFree.addr_description.addr;
462 int __asan_get_report_access_type() {
463 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
464 return ScopedInErrorReport::CurrentError().Generic.is_write;
468 uptr __asan_get_report_access_size() {
469 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
470 return ScopedInErrorReport::CurrentError().Generic.access_size;
474 const char *__asan_get_report_description() {
475 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
476 return ScopedInErrorReport::CurrentError().Generic.bug_descr;
477 return ScopedInErrorReport::CurrentError().Base.scariness.GetDescription();
481 SANITIZER_INTERFACE_ATTRIBUTE
482 void __sanitizer_ptr_sub(void *a, void *b) {
483 CheckForInvalidPointerPair(a, b);
485 SANITIZER_INTERFACE_ATTRIBUTE
486 void __sanitizer_ptr_cmp(void *a, void *b) {
487 CheckForInvalidPointerPair(a, b);
491 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
492 // Provide default implementation of __asan_on_error that does nothing
493 // and may be overriden by user.
494 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE
495 void __asan_on_error() {}