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_flags.h"
16 #include "asan_internal.h"
17 #include "asan_mapping.h"
18 #include "asan_report.h"
19 #include "asan_stack.h"
20 #include "asan_thread.h"
21 #include "sanitizer_common/sanitizer_common.h"
22 #include "sanitizer_common/sanitizer_flags.h"
23 #include "sanitizer_common/sanitizer_report_decorator.h"
24 #include "sanitizer_common/sanitizer_stackdepot.h"
25 #include "sanitizer_common/sanitizer_symbolizer.h"
29 // -------------------- User-specified callbacks ----------------- {{{1
30 static void (*error_report_callback)(const char*);
31 static char *error_message_buffer = nullptr;
32 static uptr error_message_buffer_pos = 0;
33 static BlockingMutex error_message_buf_mutex(LINKER_INITIALIZED);
34 static const unsigned kAsanBuggyPcPoolSize = 25;
35 static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];
44 const char *description;
47 static bool report_happened = false;
48 static ReportData report_data = {};
50 void AppendToErrorMessageBuffer(const char *buffer) {
51 BlockingMutexLock l(&error_message_buf_mutex);
52 if (!error_message_buffer) {
53 error_message_buffer =
54 (char*)MmapOrDieQuietly(kErrorMessageBufferSize, __func__);
55 error_message_buffer_pos = 0;
57 uptr length = internal_strlen(buffer);
58 RAW_CHECK(kErrorMessageBufferSize >= error_message_buffer_pos);
59 uptr remaining = kErrorMessageBufferSize - error_message_buffer_pos;
60 internal_strncpy(error_message_buffer + error_message_buffer_pos,
62 error_message_buffer[kErrorMessageBufferSize - 1] = '\0';
63 // FIXME: reallocate the buffer instead of truncating the message.
64 error_message_buffer_pos += Min(remaining, length);
67 // ---------------------- Decorator ------------------------------ {{{1
68 class Decorator: public __sanitizer::SanitizerCommonDecorator {
70 Decorator() : SanitizerCommonDecorator() { }
71 const char *Access() { return Blue(); }
72 const char *EndAccess() { return Default(); }
73 const char *Location() { return Green(); }
74 const char *EndLocation() { return Default(); }
75 const char *Allocation() { return Magenta(); }
76 const char *EndAllocation() { return Default(); }
78 const char *ShadowByte(u8 byte) {
80 case kAsanHeapLeftRedzoneMagic:
81 case kAsanHeapRightRedzoneMagic:
82 case kAsanArrayCookieMagic:
84 case kAsanHeapFreeMagic:
86 case kAsanStackLeftRedzoneMagic:
87 case kAsanStackMidRedzoneMagic:
88 case kAsanStackRightRedzoneMagic:
89 case kAsanStackPartialRedzoneMagic:
91 case kAsanStackAfterReturnMagic:
93 case kAsanInitializationOrderMagic:
95 case kAsanUserPoisonedMemoryMagic:
96 case kAsanContiguousContainerOOBMagic:
97 case kAsanAllocaLeftMagic:
98 case kAsanAllocaRightMagic:
100 case kAsanStackUseAfterScopeMagic:
102 case kAsanGlobalRedzoneMagic:
104 case kAsanInternalHeapMagic:
106 case kAsanIntraObjectRedzone:
112 const char *EndShadowByte() { return Default(); }
113 const char *MemoryByte() { return Magenta(); }
114 const char *EndMemoryByte() { return Default(); }
117 // ---------------------- Helper functions ----------------------- {{{1
119 static void PrintMemoryByte(InternalScopedString *str, const char *before,
120 u8 byte, bool in_shadow, const char *after = "\n") {
122 str->append("%s%s%x%x%s%s", before,
123 in_shadow ? d.ShadowByte(byte) : d.MemoryByte(),
124 byte >> 4, byte & 15,
125 in_shadow ? d.EndShadowByte() : d.EndMemoryByte(), after);
128 static void PrintShadowByte(InternalScopedString *str, const char *before,
129 u8 byte, const char *after = "\n") {
130 PrintMemoryByte(str, before, byte, /*in_shadow*/true, after);
133 static void PrintShadowBytes(InternalScopedString *str, const char *before,
134 u8 *bytes, u8 *guilty, uptr n) {
136 if (before) str->append("%s%p:", before, bytes);
137 for (uptr i = 0; i < n; i++) {
140 p == guilty ? "[" : (p - 1 == guilty && i != 0) ? "" : " ";
141 const char *after = p == guilty ? "]" : "";
142 PrintShadowByte(str, before, *p, after);
147 static void PrintLegend(InternalScopedString *str) {
149 "Shadow byte legend (one shadow byte represents %d "
150 "application bytes):\n",
151 (int)SHADOW_GRANULARITY);
152 PrintShadowByte(str, " Addressable: ", 0);
153 str->append(" Partially addressable: ");
154 for (u8 i = 1; i < SHADOW_GRANULARITY; i++) PrintShadowByte(str, "", i, " ");
156 PrintShadowByte(str, " Heap left redzone: ",
157 kAsanHeapLeftRedzoneMagic);
158 PrintShadowByte(str, " Heap right redzone: ",
159 kAsanHeapRightRedzoneMagic);
160 PrintShadowByte(str, " Freed heap region: ", kAsanHeapFreeMagic);
161 PrintShadowByte(str, " Stack left redzone: ",
162 kAsanStackLeftRedzoneMagic);
163 PrintShadowByte(str, " Stack mid redzone: ",
164 kAsanStackMidRedzoneMagic);
165 PrintShadowByte(str, " Stack right redzone: ",
166 kAsanStackRightRedzoneMagic);
167 PrintShadowByte(str, " Stack partial redzone: ",
168 kAsanStackPartialRedzoneMagic);
169 PrintShadowByte(str, " Stack after return: ",
170 kAsanStackAfterReturnMagic);
171 PrintShadowByte(str, " Stack use after scope: ",
172 kAsanStackUseAfterScopeMagic);
173 PrintShadowByte(str, " Global redzone: ", kAsanGlobalRedzoneMagic);
174 PrintShadowByte(str, " Global init order: ",
175 kAsanInitializationOrderMagic);
176 PrintShadowByte(str, " Poisoned by user: ",
177 kAsanUserPoisonedMemoryMagic);
178 PrintShadowByte(str, " Container overflow: ",
179 kAsanContiguousContainerOOBMagic);
180 PrintShadowByte(str, " Array cookie: ",
181 kAsanArrayCookieMagic);
182 PrintShadowByte(str, " Intra object redzone: ",
183 kAsanIntraObjectRedzone);
184 PrintShadowByte(str, " ASan internal: ", kAsanInternalHeapMagic);
185 PrintShadowByte(str, " Left alloca redzone: ", kAsanAllocaLeftMagic);
186 PrintShadowByte(str, " Right alloca redzone: ", kAsanAllocaRightMagic);
189 void MaybeDumpInstructionBytes(uptr pc) {
190 if (!flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
192 InternalScopedString str(1024);
193 str.append("First 16 instruction bytes at pc: ");
194 if (IsAccessibleMemoryRange(pc, 16)) {
195 for (int i = 0; i < 16; ++i) {
196 PrintMemoryByte(&str, "", ((u8 *)pc)[i], /*in_shadow*/false, " ");
200 str.append("unaccessible\n");
202 Report("%s", str.data());
205 static void PrintShadowMemoryForAddress(uptr addr) {
206 if (!AddrIsInMem(addr)) return;
207 uptr shadow_addr = MemToShadow(addr);
208 const uptr n_bytes_per_row = 16;
209 uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1);
210 InternalScopedString str(4096 * 8);
211 str.append("Shadow bytes around the buggy address:\n");
212 for (int i = -5; i <= 5; i++) {
213 const char *prefix = (i == 0) ? "=>" : " ";
214 PrintShadowBytes(&str, prefix, (u8 *)(aligned_shadow + i * n_bytes_per_row),
215 (u8 *)shadow_addr, n_bytes_per_row);
217 if (flags()->print_legend) PrintLegend(&str);
218 Printf("%s", str.data());
221 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
222 const char *zone_name) {
225 Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
226 ptr, zone_ptr, zone_name);
228 Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
232 Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
236 static void DescribeThread(AsanThread *t) {
238 DescribeThread(t->context());
241 // ---------------------- Address Descriptions ------------------- {{{1
243 static bool IsASCII(unsigned char c) {
244 return /*0x00 <= c &&*/ c <= 0x7F;
247 static const char *MaybeDemangleGlobalName(const char *name) {
248 // We can spoil names of globals with C linkage, so use an heuristic
249 // approach to check if the name should be demangled.
250 bool should_demangle = false;
251 if (name[0] == '_' && name[1] == 'Z')
252 should_demangle = true;
253 else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')
254 should_demangle = true;
256 return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;
259 // Check if the global is a zero-terminated ASCII string. If so, print it.
260 static void PrintGlobalNameIfASCII(InternalScopedString *str,
261 const __asan_global &g) {
262 for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
263 unsigned char c = *(unsigned char*)p;
264 if (c == '\0' || !IsASCII(c)) return;
266 if (*(char*)(g.beg + g.size - 1) != '\0') return;
267 str->append(" '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),
271 static const char *GlobalFilename(const __asan_global &g) {
272 const char *res = g.module_name;
273 // Prefer the filename from source location, if is available.
275 res = g.location->filename;
280 static void PrintGlobalLocation(InternalScopedString *str,
281 const __asan_global &g) {
282 str->append("%s", GlobalFilename(g));
285 if (g.location->line_no)
286 str->append(":%d", g.location->line_no);
287 if (g.location->column_no)
288 str->append(":%d", g.location->column_no);
291 static void DescribeAddressRelativeToGlobal(uptr addr, uptr size,
292 const __asan_global &g) {
293 InternalScopedString str(4096);
295 str.append("%s", d.Location());
297 str.append("%p is located %zd bytes to the left", (void *)addr,
299 } else if (addr + size > g.beg + g.size) {
300 if (addr < g.beg + g.size)
301 addr = g.beg + g.size;
302 str.append("%p is located %zd bytes to the right", (void *)addr,
303 addr - (g.beg + g.size));
306 str.append("%p is located %zd bytes inside", (void *)addr, addr - g.beg);
308 str.append(" of global variable '%s' defined in '",
309 MaybeDemangleGlobalName(g.name));
310 PrintGlobalLocation(&str, g);
311 str.append("' (0x%zx) of size %zu\n", g.beg, g.size);
312 str.append("%s", d.EndLocation());
313 PrintGlobalNameIfASCII(&str, g);
314 Printf("%s", str.data());
317 static bool DescribeAddressIfGlobal(uptr addr, uptr size,
318 const char *bug_type) {
319 // Assume address is close to at most four globals.
320 const int kMaxGlobalsInReport = 4;
321 __asan_global globals[kMaxGlobalsInReport];
322 u32 reg_sites[kMaxGlobalsInReport];
324 GetGlobalsForAddress(addr, globals, reg_sites, ARRAY_SIZE(globals));
325 if (globals_num == 0)
327 for (int i = 0; i < globals_num; i++) {
328 DescribeAddressRelativeToGlobal(addr, size, globals[i]);
329 if (0 == internal_strcmp(bug_type, "initialization-order-fiasco") &&
331 Printf(" registered at:\n");
332 StackDepotGet(reg_sites[i]).Print();
338 bool DescribeAddressIfShadow(uptr addr, AddressDescription *descr, bool print) {
339 if (AddrIsInMem(addr))
341 const char *area_type = nullptr;
342 if (AddrIsInShadowGap(addr)) area_type = "shadow gap";
343 else if (AddrIsInHighShadow(addr)) area_type = "high shadow";
344 else if (AddrIsInLowShadow(addr)) area_type = "low shadow";
345 if (area_type != nullptr) {
347 Printf("Address %p is located in the %s area.\n", addr, area_type);
350 descr->region_kind = area_type;
354 CHECK(0 && "Address is not in memory and not in shadow?");
358 // Return " (thread_name) " or an empty string if the name is empty.
359 const char *ThreadNameWithParenthesis(AsanThreadContext *t, char buff[],
361 const char *name = t->name;
362 if (name[0] == '\0') return "";
364 internal_strncat(buff, " (", 3);
365 internal_strncat(buff, name, buff_len - 4);
366 internal_strncat(buff, ")", 2);
370 const char *ThreadNameWithParenthesis(u32 tid, char buff[],
372 if (tid == kInvalidTid) return "";
373 asanThreadRegistry().CheckLocked();
374 AsanThreadContext *t = GetThreadContextByTidLocked(tid);
375 return ThreadNameWithParenthesis(t, buff, buff_len);
378 static void PrintAccessAndVarIntersection(const StackVarDescr &var, uptr addr,
379 uptr access_size, uptr prev_var_end,
381 uptr var_end = var.beg + var.size;
382 uptr addr_end = addr + access_size;
383 const char *pos_descr = nullptr;
384 // If the variable [var.beg, var_end) is the nearest variable to the
385 // current memory access, indicate it in the log.
386 if (addr >= var.beg) {
387 if (addr_end <= var_end)
388 pos_descr = "is inside"; // May happen if this is a use-after-return.
389 else if (addr < var_end)
390 pos_descr = "partially overflows";
391 else if (addr_end <= next_var_beg &&
392 next_var_beg - addr_end >= addr - var_end)
393 pos_descr = "overflows";
395 if (addr_end > var.beg)
396 pos_descr = "partially underflows";
397 else if (addr >= prev_var_end &&
398 addr - prev_var_end >= var.beg - addr_end)
399 pos_descr = "underflows";
401 InternalScopedString str(1024);
402 str.append(" [%zd, %zd)", var.beg, var_end);
403 // Render variable name.
405 for (uptr i = 0; i < var.name_len; ++i) {
406 str.append("%c", var.name_pos[i]);
411 // FIXME: we may want to also print the size of the access here,
412 // but in case of accesses generated by memset it may be confusing.
413 str.append("%s <== Memory access at offset %zd %s this variable%s\n",
414 d.Location(), addr, pos_descr, d.EndLocation());
418 Printf("%s", str.data());
421 bool ParseFrameDescription(const char *frame_descr,
422 InternalMmapVector<StackVarDescr> *vars) {
425 // This string is created by the compiler and has the following form:
426 // "n alloc_1 alloc_2 ... alloc_n"
427 // where alloc_i looks like "offset size len ObjectName".
428 uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
432 for (uptr i = 0; i < n_objects; i++) {
433 uptr beg = (uptr)internal_simple_strtoll(p, &p, 10);
434 uptr size = (uptr)internal_simple_strtoll(p, &p, 10);
435 uptr len = (uptr)internal_simple_strtoll(p, &p, 10);
436 if (beg == 0 || size == 0 || *p != ' ') {
440 StackVarDescr var = {beg, size, p, len};
441 vars->push_back(var);
448 bool DescribeAddressIfStack(uptr addr, uptr access_size) {
449 AsanThread *t = FindThreadByStackAddress(addr);
450 if (!t) return false;
454 Printf("%s", d.Location());
455 Printf("Address %p is located in stack of thread T%d%s", addr, t->tid(),
456 ThreadNameWithParenthesis(t->tid(), tname, sizeof(tname)));
458 // Try to fetch precise stack frame for this access.
459 AsanThread::StackFrameAccess access;
460 if (!t->GetStackFrameAccessByAddr(addr, &access)) {
461 Printf("%s\n", d.EndLocation());
464 Printf(" at offset %zu in frame%s\n", access.offset, d.EndLocation());
466 // Now we print the frame where the alloca has happened.
467 // We print this frame as a stack trace with one element.
468 // The symbolizer may print more than one frame if inlining was involved.
469 // The frame numbers may be different than those in the stack trace printed
470 // previously. That's unfortunate, but I have no better solution,
471 // especially given that the alloca may be from entirely different place
472 // (e.g. use-after-scope, or different thread's stack).
473 #if defined(__powerpc64__) && defined(__BIG_ENDIAN__)
474 // On PowerPC64 ELFv1, the address of a function actually points to a
475 // three-doubleword data structure with the first field containing
476 // the address of the function's code.
477 access.frame_pc = *reinterpret_cast<uptr *>(access.frame_pc);
479 access.frame_pc += 16;
480 Printf("%s", d.EndLocation());
481 StackTrace alloca_stack(&access.frame_pc, 1);
482 alloca_stack.Print();
484 InternalMmapVector<StackVarDescr> vars(16);
485 if (!ParseFrameDescription(access.frame_descr, &vars)) {
486 Printf("AddressSanitizer can't parse the stack frame "
487 "descriptor: |%s|\n", access.frame_descr);
488 // 'addr' is a stack address, so return true even if we can't parse frame
491 uptr n_objects = vars.size();
492 // Report the number of stack objects.
493 Printf(" This frame has %zu object(s):\n", n_objects);
495 // Report all objects in this frame.
496 for (uptr i = 0; i < n_objects; i++) {
497 uptr prev_var_end = i ? vars[i - 1].beg + vars[i - 1].size : 0;
498 uptr next_var_beg = i + 1 < n_objects ? vars[i + 1].beg : ~(0UL);
499 PrintAccessAndVarIntersection(vars[i], access.offset, access_size,
500 prev_var_end, next_var_beg);
502 Printf("HINT: this may be a false positive if your program uses "
503 "some custom stack unwind mechanism or swapcontext\n");
504 if (SANITIZER_WINDOWS)
505 Printf(" (longjmp, SEH and C++ exceptions *are* supported)\n");
507 Printf(" (longjmp and C++ exceptions *are* supported)\n");
513 static void DescribeAccessToHeapChunk(AsanChunkView chunk, uptr addr,
517 InternalScopedString str(4096);
518 str.append("%s", d.Location());
519 if (chunk.AddrIsAtLeft(addr, access_size, &offset)) {
520 str.append("%p is located %zd bytes to the left of", (void *)addr, offset);
521 } else if (chunk.AddrIsAtRight(addr, access_size, &offset)) {
526 str.append("%p is located %zd bytes to the right of", (void *)addr, offset);
527 } else if (chunk.AddrIsInside(addr, access_size, &offset)) {
528 str.append("%p is located %zd bytes inside of", (void*)addr, offset);
530 str.append("%p is located somewhere around (this is AddressSanitizer bug!)",
533 str.append(" %zu-byte region [%p,%p)\n", chunk.UsedSize(),
534 (void *)(chunk.Beg()), (void *)(chunk.End()));
535 str.append("%s", d.EndLocation());
536 Printf("%s", str.data());
539 void DescribeHeapAddress(uptr addr, uptr access_size) {
540 AsanChunkView chunk = FindHeapChunkByAddress(addr);
541 if (!chunk.IsValid()) {
542 Printf("AddressSanitizer can not describe address in more detail "
543 "(wild memory access suspected).\n");
546 DescribeAccessToHeapChunk(chunk, addr, access_size);
547 CHECK(chunk.AllocTid() != kInvalidTid);
548 asanThreadRegistry().CheckLocked();
549 AsanThreadContext *alloc_thread =
550 GetThreadContextByTidLocked(chunk.AllocTid());
551 StackTrace alloc_stack = chunk.GetAllocStack();
554 AsanThreadContext *free_thread = nullptr;
555 if (chunk.FreeTid() != kInvalidTid) {
556 free_thread = GetThreadContextByTidLocked(chunk.FreeTid());
557 Printf("%sfreed by thread T%d%s here:%s\n", d.Allocation(),
559 ThreadNameWithParenthesis(free_thread, tname, sizeof(tname)),
561 StackTrace free_stack = chunk.GetFreeStack();
563 Printf("%spreviously allocated by thread T%d%s here:%s\n",
564 d.Allocation(), alloc_thread->tid,
565 ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
568 Printf("%sallocated by thread T%d%s here:%s\n", d.Allocation(),
570 ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
574 DescribeThread(GetCurrentThread());
576 DescribeThread(free_thread);
577 DescribeThread(alloc_thread);
580 static void DescribeAddress(uptr addr, uptr access_size, const char *bug_type) {
581 // Check if this is shadow or shadow gap.
582 if (DescribeAddressIfShadow(addr))
584 CHECK(AddrIsInMem(addr));
585 if (DescribeAddressIfGlobal(addr, access_size, bug_type))
587 if (DescribeAddressIfStack(addr, access_size))
589 // Assume it is a heap address.
590 DescribeHeapAddress(addr, access_size);
593 // ------------------- Thread description -------------------- {{{1
595 void DescribeThread(AsanThreadContext *context) {
597 asanThreadRegistry().CheckLocked();
598 // No need to announce the main thread.
599 if (context->tid == 0 || context->announced) {
602 context->announced = true;
604 InternalScopedString str(1024);
605 str.append("Thread T%d%s", context->tid,
606 ThreadNameWithParenthesis(context->tid, tname, sizeof(tname)));
607 if (context->parent_tid == kInvalidTid) {
608 str.append(" created by unknown thread\n");
609 Printf("%s", str.data());
613 " created by T%d%s here:\n", context->parent_tid,
614 ThreadNameWithParenthesis(context->parent_tid, tname, sizeof(tname)));
615 Printf("%s", str.data());
616 StackDepotGet(context->stack_id).Print();
617 // Recursively described parent thread if needed.
618 if (flags()->print_full_thread_history) {
619 AsanThreadContext *parent_context =
620 GetThreadContextByTidLocked(context->parent_tid);
621 DescribeThread(parent_context);
625 // -------------------- Different kinds of reports ----------------- {{{1
627 // Use ScopedInErrorReport to run common actions just before and
628 // immediately after printing error report.
629 class ScopedInErrorReport {
631 explicit ScopedInErrorReport(ReportData *report = nullptr,
632 bool fatal = false) {
633 halt_on_error_ = fatal || flags()->halt_on_error;
635 if (lock_.TryLock()) {
636 StartReporting(report);
640 // ASan found two bugs in different threads simultaneously.
642 u32 current_tid = GetCurrentTidOrInvalid();
643 if (reporting_thread_tid_ == current_tid ||
644 reporting_thread_tid_ == kInvalidTid) {
645 // This is either asynch signal or nested error during error reporting.
646 // Fail simple to avoid deadlocks in Report().
648 // Can't use Report() here because of potential deadlocks
649 // in nested signal handlers.
650 const char msg[] = "AddressSanitizer: nested bug in the same thread, "
652 WriteToFile(kStderrFd, msg, sizeof(msg));
654 internal__exit(common_flags()->exitcode);
657 if (halt_on_error_) {
658 // Do not print more than one report, otherwise they will mix up.
659 // Error reporting functions shouldn't return at this situation, as
660 // they are effectively no-returns.
662 Report("AddressSanitizer: while reporting a bug found another one. "
665 // Sleep long enough to make sure that the thread which started
666 // to print an error report will finish doing it.
667 SleepForSeconds(Max(100, flags()->sleep_before_dying + 1));
669 // If we're still not dead for some reason, use raw _exit() instead of
670 // Die() to bypass any additional checks.
671 internal__exit(common_flags()->exitcode);
673 // The other thread will eventually finish reporting
674 // so it's safe to wait
678 StartReporting(report);
681 ~ScopedInErrorReport() {
682 // Make sure the current thread is announced.
683 DescribeThread(GetCurrentThread());
684 // We may want to grab this lock again when printing stats.
685 asanThreadRegistry().Unlock();
686 // Print memory stats.
687 if (flags()->print_stats)
688 __asan_print_accumulated_stats();
690 // Copy the message buffer so that we could start logging without holding a
691 // lock that gets aquired during printing.
692 InternalScopedBuffer<char> buffer_copy(kErrorMessageBufferSize);
694 BlockingMutexLock l(&error_message_buf_mutex);
695 internal_memcpy(buffer_copy.data(),
696 error_message_buffer, kErrorMessageBufferSize);
699 LogFullErrorReport(buffer_copy.data());
701 if (error_report_callback) {
702 error_report_callback(buffer_copy.data());
704 CommonSanitizerReportMutex.Unlock();
705 reporting_thread_tid_ = kInvalidTid;
707 if (halt_on_error_) {
708 Report("ABORTING\n");
714 void StartReporting(ReportData *report) {
715 if (report) report_data = *report;
716 report_happened = true;
718 // Make sure the registry and sanitizer report mutexes are locked while
719 // we're printing an error report.
720 // We can lock them only here to avoid self-deadlock in case of
721 // recursive reports.
722 asanThreadRegistry().Lock();
723 CommonSanitizerReportMutex.Lock();
724 reporting_thread_tid_ = GetCurrentTidOrInvalid();
725 Printf("===================================================="
729 static StaticSpinMutex lock_;
730 static u32 reporting_thread_tid_;
734 StaticSpinMutex ScopedInErrorReport::lock_;
735 u32 ScopedInErrorReport::reporting_thread_tid_;
737 void ReportStackOverflow(const SignalContext &sig) {
738 ScopedInErrorReport in_report;
740 Printf("%s", d.Warning());
742 "ERROR: AddressSanitizer: stack-overflow on address %p"
743 " (pc %p bp %p sp %p T%d)\n",
744 (void *)sig.addr, (void *)sig.pc, (void *)sig.bp, (void *)sig.sp,
745 GetCurrentTidOrInvalid());
746 Printf("%s", d.EndWarning());
747 GET_STACK_TRACE_SIGNAL(sig);
749 ReportErrorSummary("stack-overflow", &stack);
752 void ReportDeadlySignal(const char *description, const SignalContext &sig) {
753 ScopedInErrorReport in_report(/*report*/nullptr, /*fatal*/true);
755 Printf("%s", d.Warning());
757 "ERROR: AddressSanitizer: %s on unknown address %p"
758 " (pc %p bp %p sp %p T%d)\n",
759 description, (void *)sig.addr, (void *)sig.pc, (void *)sig.bp,
760 (void *)sig.sp, GetCurrentTidOrInvalid());
761 if (sig.pc < GetPageSizeCached()) {
762 Report("Hint: pc points to the zero page.\n");
764 Printf("%s", d.EndWarning());
765 GET_STACK_TRACE_SIGNAL(sig);
767 MaybeDumpInstructionBytes(sig.pc);
768 Printf("AddressSanitizer can not provide additional info.\n");
769 ReportErrorSummary(description, &stack);
772 void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {
773 ScopedInErrorReport in_report;
775 Printf("%s", d.Warning());
777 u32 curr_tid = GetCurrentTidOrInvalid();
778 Report("ERROR: AddressSanitizer: attempting double-free on %p in "
781 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
782 Printf("%s", d.EndWarning());
783 CHECK_GT(free_stack->size, 0);
784 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
786 DescribeHeapAddress(addr, 1);
787 ReportErrorSummary("double-free", &stack);
790 void ReportNewDeleteSizeMismatch(uptr addr, uptr delete_size,
791 BufferedStackTrace *free_stack) {
792 ScopedInErrorReport in_report;
794 Printf("%s", d.Warning());
796 u32 curr_tid = GetCurrentTidOrInvalid();
797 Report("ERROR: AddressSanitizer: new-delete-type-mismatch on %p in "
800 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
801 Printf("%s object passed to delete has wrong type:\n", d.EndWarning());
802 Printf(" size of the allocated type: %zd bytes;\n"
803 " size of the deallocated type: %zd bytes.\n",
804 asan_mz_size(reinterpret_cast<void*>(addr)), delete_size);
805 CHECK_GT(free_stack->size, 0);
806 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
808 DescribeHeapAddress(addr, 1);
809 ReportErrorSummary("new-delete-type-mismatch", &stack);
810 Report("HINT: if you don't care about these errors you may set "
811 "ASAN_OPTIONS=new_delete_type_mismatch=0\n");
814 void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {
815 ScopedInErrorReport in_report;
817 Printf("%s", d.Warning());
819 u32 curr_tid = GetCurrentTidOrInvalid();
820 Report("ERROR: AddressSanitizer: attempting free on address "
821 "which was not malloc()-ed: %p in thread T%d%s\n", addr,
822 curr_tid, ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
823 Printf("%s", d.EndWarning());
824 CHECK_GT(free_stack->size, 0);
825 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
827 DescribeHeapAddress(addr, 1);
828 ReportErrorSummary("bad-free", &stack);
831 void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,
832 AllocType alloc_type,
833 AllocType dealloc_type) {
834 static const char *alloc_names[] =
835 {"INVALID", "malloc", "operator new", "operator new []"};
836 static const char *dealloc_names[] =
837 {"INVALID", "free", "operator delete", "operator delete []"};
838 CHECK_NE(alloc_type, dealloc_type);
839 ScopedInErrorReport in_report;
841 Printf("%s", d.Warning());
842 Report("ERROR: AddressSanitizer: alloc-dealloc-mismatch (%s vs %s) on %p\n",
843 alloc_names[alloc_type], dealloc_names[dealloc_type], addr);
844 Printf("%s", d.EndWarning());
845 CHECK_GT(free_stack->size, 0);
846 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
848 DescribeHeapAddress(addr, 1);
849 ReportErrorSummary("alloc-dealloc-mismatch", &stack);
850 Report("HINT: if you don't care about these errors you may set "
851 "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n");
854 void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {
855 ScopedInErrorReport in_report;
857 Printf("%s", d.Warning());
858 Report("ERROR: AddressSanitizer: attempting to call "
859 "malloc_usable_size() for pointer which is "
860 "not owned: %p\n", addr);
861 Printf("%s", d.EndWarning());
863 DescribeHeapAddress(addr, 1);
864 ReportErrorSummary("bad-malloc_usable_size", stack);
867 void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,
868 BufferedStackTrace *stack) {
869 ScopedInErrorReport in_report;
871 Printf("%s", d.Warning());
872 Report("ERROR: AddressSanitizer: attempting to call "
873 "__sanitizer_get_allocated_size() for pointer which is "
874 "not owned: %p\n", addr);
875 Printf("%s", d.EndWarning());
877 DescribeHeapAddress(addr, 1);
878 ReportErrorSummary("bad-__sanitizer_get_allocated_size", stack);
881 void ReportStringFunctionMemoryRangesOverlap(const char *function,
882 const char *offset1, uptr length1,
883 const char *offset2, uptr length2,
884 BufferedStackTrace *stack) {
885 ScopedInErrorReport in_report;
888 internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function);
889 Printf("%s", d.Warning());
890 Report("ERROR: AddressSanitizer: %s: "
891 "memory ranges [%p,%p) and [%p, %p) overlap\n", \
892 bug_type, offset1, offset1 + length1, offset2, offset2 + length2);
893 Printf("%s", d.EndWarning());
895 DescribeAddress((uptr)offset1, length1, bug_type);
896 DescribeAddress((uptr)offset2, length2, bug_type);
897 ReportErrorSummary(bug_type, stack);
900 void ReportStringFunctionSizeOverflow(uptr offset, uptr size,
901 BufferedStackTrace *stack) {
902 ScopedInErrorReport in_report;
904 const char *bug_type = "negative-size-param";
905 Printf("%s", d.Warning());
906 Report("ERROR: AddressSanitizer: %s: (size=%zd)\n", bug_type, size);
907 Printf("%s", d.EndWarning());
909 DescribeAddress(offset, size, bug_type);
910 ReportErrorSummary(bug_type, stack);
913 void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,
914 uptr old_mid, uptr new_mid,
915 BufferedStackTrace *stack) {
916 ScopedInErrorReport in_report;
917 Report("ERROR: AddressSanitizer: bad parameters to "
918 "__sanitizer_annotate_contiguous_container:\n"
923 beg, end, old_mid, new_mid);
924 uptr granularity = SHADOW_GRANULARITY;
925 if (!IsAligned(beg, granularity))
926 Report("ERROR: beg is not aligned by %d\n", granularity);
928 ReportErrorSummary("bad-__sanitizer_annotate_contiguous_container", stack);
931 void ReportODRViolation(const __asan_global *g1, u32 stack_id1,
932 const __asan_global *g2, u32 stack_id2) {
933 ScopedInErrorReport in_report;
935 Printf("%s", d.Warning());
936 Report("ERROR: AddressSanitizer: odr-violation (%p):\n", g1->beg);
937 Printf("%s", d.EndWarning());
938 InternalScopedString g1_loc(256), g2_loc(256);
939 PrintGlobalLocation(&g1_loc, *g1);
940 PrintGlobalLocation(&g2_loc, *g2);
941 Printf(" [1] size=%zd '%s' %s\n", g1->size,
942 MaybeDemangleGlobalName(g1->name), g1_loc.data());
943 Printf(" [2] size=%zd '%s' %s\n", g2->size,
944 MaybeDemangleGlobalName(g2->name), g2_loc.data());
945 if (stack_id1 && stack_id2) {
946 Printf("These globals were registered at these points:\n");
948 StackDepotGet(stack_id1).Print();
950 StackDepotGet(stack_id2).Print();
952 Report("HINT: if you don't care about these errors you may set "
953 "ASAN_OPTIONS=detect_odr_violation=0\n");
954 InternalScopedString error_msg(256);
955 error_msg.append("odr-violation: global '%s' at %s",
956 MaybeDemangleGlobalName(g1->name), g1_loc.data());
957 ReportErrorSummary(error_msg.data());
960 // ----------------------- CheckForInvalidPointerPair ----------- {{{1
962 ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp, uptr a1, uptr a2) {
963 ScopedInErrorReport in_report;
964 const char *bug_type = "invalid-pointer-pair";
966 Printf("%s", d.Warning());
967 Report("ERROR: AddressSanitizer: invalid-pointer-pair: %p %p\n", a1, a2);
968 Printf("%s", d.EndWarning());
969 GET_STACK_TRACE_FATAL(pc, bp);
971 DescribeAddress(a1, 1, bug_type);
972 DescribeAddress(a2, 1, bug_type);
973 ReportErrorSummary(bug_type, &stack);
976 static INLINE void CheckForInvalidPointerPair(void *p1, void *p2) {
977 if (!flags()->detect_invalid_pointer_pairs) return;
978 uptr a1 = reinterpret_cast<uptr>(p1);
979 uptr a2 = reinterpret_cast<uptr>(p2);
980 AsanChunkView chunk1 = FindHeapChunkByAddress(a1);
981 AsanChunkView chunk2 = FindHeapChunkByAddress(a2);
982 bool valid1 = chunk1.IsValid();
983 bool valid2 = chunk2.IsValid();
984 if ((valid1 != valid2) || (valid1 && valid2 && !chunk1.Eq(chunk2))) {
985 GET_CALLER_PC_BP_SP; \
986 return ReportInvalidPointerPair(pc, bp, sp, a1, a2);
989 // ----------------------- Mac-specific reports ----------------- {{{1
991 void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,
992 BufferedStackTrace *stack) {
993 ScopedInErrorReport in_report;
994 Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
995 "This is an unrecoverable problem, exiting now.\n",
997 PrintZoneForPointer(addr, zone_ptr, zone_name);
999 DescribeHeapAddress(addr, 1);
1002 // -------------- SuppressErrorReport -------------- {{{1
1003 // Avoid error reports duplicating for ASan recover mode.
1004 static bool SuppressErrorReport(uptr pc) {
1005 if (!common_flags()->suppress_equal_pcs) return false;
1006 for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {
1007 uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);
1008 if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,
1009 pc, memory_order_relaxed))
1011 if (cmp == pc) return true;
1016 void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,
1017 uptr access_size, u32 exp, bool fatal) {
1018 if (!fatal && SuppressErrorReport(pc)) return;
1019 ENABLE_FRAME_POINTER;
1021 // Optimization experiments.
1022 // The experiments can be used to evaluate potential optimizations that remove
1023 // instrumentation (assess false negatives). Instead of completely removing
1024 // some instrumentation, compiler can emit special calls into runtime
1025 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass
1026 // mask of experiments (exp).
1027 // The reaction to a non-zero value of exp is to be defined.
1030 // Determine the error type.
1031 const char *bug_descr = "unknown-crash";
1032 if (AddrIsInMem(addr)) {
1033 u8 *shadow_addr = (u8*)MemToShadow(addr);
1034 // If we are accessing 16 bytes, look at the second shadow byte.
1035 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
1037 // If we are in the partial right redzone, look at the next shadow byte.
1038 if (*shadow_addr > 0 && *shadow_addr < 128)
1040 switch (*shadow_addr) {
1041 case kAsanHeapLeftRedzoneMagic:
1042 case kAsanHeapRightRedzoneMagic:
1043 case kAsanArrayCookieMagic:
1044 bug_descr = "heap-buffer-overflow";
1046 case kAsanHeapFreeMagic:
1047 bug_descr = "heap-use-after-free";
1049 case kAsanStackLeftRedzoneMagic:
1050 bug_descr = "stack-buffer-underflow";
1052 case kAsanInitializationOrderMagic:
1053 bug_descr = "initialization-order-fiasco";
1055 case kAsanStackMidRedzoneMagic:
1056 case kAsanStackRightRedzoneMagic:
1057 case kAsanStackPartialRedzoneMagic:
1058 bug_descr = "stack-buffer-overflow";
1060 case kAsanStackAfterReturnMagic:
1061 bug_descr = "stack-use-after-return";
1063 case kAsanUserPoisonedMemoryMagic:
1064 bug_descr = "use-after-poison";
1066 case kAsanContiguousContainerOOBMagic:
1067 bug_descr = "container-overflow";
1069 case kAsanStackUseAfterScopeMagic:
1070 bug_descr = "stack-use-after-scope";
1072 case kAsanGlobalRedzoneMagic:
1073 bug_descr = "global-buffer-overflow";
1075 case kAsanIntraObjectRedzone:
1076 bug_descr = "intra-object-overflow";
1078 case kAsanAllocaLeftMagic:
1079 case kAsanAllocaRightMagic:
1080 bug_descr = "dynamic-stack-buffer-overflow";
1085 ReportData report = { pc, sp, bp, addr, (bool)is_write, access_size,
1087 ScopedInErrorReport in_report(&report, fatal);
1090 Printf("%s", d.Warning());
1091 Report("ERROR: AddressSanitizer: %s on address "
1092 "%p at pc %p bp %p sp %p\n",
1093 bug_descr, (void*)addr, pc, bp, sp);
1094 Printf("%s", d.EndWarning());
1096 u32 curr_tid = GetCurrentTidOrInvalid();
1098 Printf("%s%s of size %zu at %p thread T%d%s%s\n",
1100 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
1101 access_size, (void*)addr, curr_tid,
1102 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)),
1105 GET_STACK_TRACE_FATAL(pc, bp);
1108 DescribeAddress(addr, access_size, bug_descr);
1109 ReportErrorSummary(bug_descr, &stack);
1110 PrintShadowMemoryForAddress(addr);
1113 } // namespace __asan
1115 // --------------------------- Interface --------------------- {{{1
1116 using namespace __asan; // NOLINT
1118 void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
1119 uptr access_size, u32 exp) {
1120 ENABLE_FRAME_POINTER;
1121 bool fatal = flags()->halt_on_error;
1122 ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);
1125 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
1126 BlockingMutexLock l(&error_message_buf_mutex);
1127 error_report_callback = callback;
1130 void __asan_describe_address(uptr addr) {
1131 // Thread registry must be locked while we're describing an address.
1132 asanThreadRegistry().Lock();
1133 DescribeAddress(addr, 1, "");
1134 asanThreadRegistry().Unlock();
1137 int __asan_report_present() {
1138 return report_happened ? 1 : 0;
1141 uptr __asan_get_report_pc() {
1142 return report_data.pc;
1145 uptr __asan_get_report_bp() {
1146 return report_data.bp;
1149 uptr __asan_get_report_sp() {
1150 return report_data.sp;
1153 uptr __asan_get_report_address() {
1154 return report_data.addr;
1157 int __asan_get_report_access_type() {
1158 return report_data.is_write ? 1 : 0;
1161 uptr __asan_get_report_access_size() {
1162 return report_data.access_size;
1165 const char *__asan_get_report_description() {
1166 return report_data.description;
1170 SANITIZER_INTERFACE_ATTRIBUTE
1171 void __sanitizer_ptr_sub(void *a, void *b) {
1172 CheckForInvalidPointerPair(a, b);
1174 SANITIZER_INTERFACE_ATTRIBUTE
1175 void __sanitizer_ptr_cmp(void *a, void *b) {
1176 CheckForInvalidPointerPair(a, b);
1180 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
1181 // Provide default implementation of __asan_on_error that does nothing
1182 // and may be overriden by user.
1183 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE
1184 void __asan_on_error() {}