2014-04-30 Bernd Edlinger <bernd.edlinger@hotmail.de>
[official-gcc.git] / libsanitizer / asan / asan_report.cc
blob70c4b481a2f1d863e61a7055cbde958d46c4dbed
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 //===----------------------------------------------------------------------===//
12 #include "asan_flags.h"
13 #include "asan_internal.h"
14 #include "asan_mapping.h"
15 #include "asan_report.h"
16 #include "asan_stack.h"
17 #include "asan_thread.h"
18 #include "sanitizer_common/sanitizer_common.h"
19 #include "sanitizer_common/sanitizer_flags.h"
20 #include "sanitizer_common/sanitizer_report_decorator.h"
21 #include "sanitizer_common/sanitizer_stackdepot.h"
22 #include "sanitizer_common/sanitizer_symbolizer.h"
24 namespace __asan {
26 // -------------------- User-specified callbacks ----------------- {{{1
27 static void (*error_report_callback)(const char*);
28 static char *error_message_buffer = 0;
29 static uptr error_message_buffer_pos = 0;
30 static uptr error_message_buffer_size = 0;
32 void AppendToErrorMessageBuffer(const char *buffer) {
33 if (error_message_buffer) {
34 uptr length = internal_strlen(buffer);
35 CHECK_GE(error_message_buffer_size, error_message_buffer_pos);
36 uptr remaining = error_message_buffer_size - error_message_buffer_pos;
37 internal_strncpy(error_message_buffer + error_message_buffer_pos,
38 buffer, remaining);
39 error_message_buffer[error_message_buffer_size - 1] = '\0';
40 // FIXME: reallocate the buffer instead of truncating the message.
41 error_message_buffer_pos += remaining > length ? length : remaining;
45 // ---------------------- Decorator ------------------------------ {{{1
46 class Decorator: private __sanitizer::AnsiColorDecorator {
47 public:
48 Decorator() : __sanitizer::AnsiColorDecorator(PrintsToTtyCached()) { }
49 const char *Warning() { return Red(); }
50 const char *EndWarning() { return Default(); }
51 const char *Access() { return Blue(); }
52 const char *EndAccess() { return Default(); }
53 const char *Location() { return Green(); }
54 const char *EndLocation() { return Default(); }
55 const char *Allocation() { return Magenta(); }
56 const char *EndAllocation() { return Default(); }
58 const char *ShadowByte(u8 byte) {
59 switch (byte) {
60 case kAsanHeapLeftRedzoneMagic:
61 case kAsanHeapRightRedzoneMagic:
62 return Red();
63 case kAsanHeapFreeMagic:
64 return Magenta();
65 case kAsanStackLeftRedzoneMagic:
66 case kAsanStackMidRedzoneMagic:
67 case kAsanStackRightRedzoneMagic:
68 case kAsanStackPartialRedzoneMagic:
69 return Red();
70 case kAsanStackAfterReturnMagic:
71 return Magenta();
72 case kAsanInitializationOrderMagic:
73 return Cyan();
74 case kAsanUserPoisonedMemoryMagic:
75 case kAsanContiguousContainerOOBMagic:
76 return Blue();
77 case kAsanStackUseAfterScopeMagic:
78 return Magenta();
79 case kAsanGlobalRedzoneMagic:
80 return Red();
81 case kAsanInternalHeapMagic:
82 return Yellow();
83 default:
84 return Default();
87 const char *EndShadowByte() { return Default(); }
90 // ---------------------- Helper functions ----------------------- {{{1
92 static void PrintShadowByte(const char *before, u8 byte,
93 const char *after = "\n") {
94 Decorator d;
95 Printf("%s%s%x%x%s%s", before,
96 d.ShadowByte(byte), byte >> 4, byte & 15, d.EndShadowByte(), after);
99 static void PrintShadowBytes(const char *before, u8 *bytes,
100 u8 *guilty, uptr n) {
101 Decorator d;
102 if (before)
103 Printf("%s%p:", before, bytes);
104 for (uptr i = 0; i < n; i++) {
105 u8 *p = bytes + i;
106 const char *before = p == guilty ? "[" :
107 (p - 1 == guilty && i != 0) ? "" : " ";
108 const char *after = p == guilty ? "]" : "";
109 PrintShadowByte(before, *p, after);
111 Printf("\n");
114 static void PrintLegend() {
115 Printf("Shadow byte legend (one shadow byte represents %d "
116 "application bytes):\n", (int)SHADOW_GRANULARITY);
117 PrintShadowByte(" Addressable: ", 0);
118 Printf(" Partially addressable: ");
119 for (u8 i = 1; i < SHADOW_GRANULARITY; i++)
120 PrintShadowByte("", i, " ");
121 Printf("\n");
122 PrintShadowByte(" Heap left redzone: ", kAsanHeapLeftRedzoneMagic);
123 PrintShadowByte(" Heap right redzone: ", kAsanHeapRightRedzoneMagic);
124 PrintShadowByte(" Freed heap region: ", kAsanHeapFreeMagic);
125 PrintShadowByte(" Stack left redzone: ", kAsanStackLeftRedzoneMagic);
126 PrintShadowByte(" Stack mid redzone: ", kAsanStackMidRedzoneMagic);
127 PrintShadowByte(" Stack right redzone: ", kAsanStackRightRedzoneMagic);
128 PrintShadowByte(" Stack partial redzone: ", kAsanStackPartialRedzoneMagic);
129 PrintShadowByte(" Stack after return: ", kAsanStackAfterReturnMagic);
130 PrintShadowByte(" Stack use after scope: ", kAsanStackUseAfterScopeMagic);
131 PrintShadowByte(" Global redzone: ", kAsanGlobalRedzoneMagic);
132 PrintShadowByte(" Global init order: ", kAsanInitializationOrderMagic);
133 PrintShadowByte(" Poisoned by user: ", kAsanUserPoisonedMemoryMagic);
134 PrintShadowByte(" Contiguous container OOB:",
135 kAsanContiguousContainerOOBMagic);
136 PrintShadowByte(" ASan internal: ", kAsanInternalHeapMagic);
139 static void PrintShadowMemoryForAddress(uptr addr) {
140 if (!AddrIsInMem(addr))
141 return;
142 uptr shadow_addr = MemToShadow(addr);
143 const uptr n_bytes_per_row = 16;
144 uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1);
145 Printf("Shadow bytes around the buggy address:\n");
146 for (int i = -5; i <= 5; i++) {
147 const char *prefix = (i == 0) ? "=>" : " ";
148 PrintShadowBytes(prefix,
149 (u8*)(aligned_shadow + i * n_bytes_per_row),
150 (u8*)shadow_addr, n_bytes_per_row);
152 if (flags()->print_legend)
153 PrintLegend();
156 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
157 const char *zone_name) {
158 if (zone_ptr) {
159 if (zone_name) {
160 Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
161 ptr, zone_ptr, zone_name);
162 } else {
163 Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
164 ptr, zone_ptr);
166 } else {
167 Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
171 static void DescribeThread(AsanThread *t) {
172 if (t)
173 DescribeThread(t->context());
176 // ---------------------- Address Descriptions ------------------- {{{1
178 static bool IsASCII(unsigned char c) {
179 return /*0x00 <= c &&*/ c <= 0x7F;
182 static const char *MaybeDemangleGlobalName(const char *name) {
183 // We can spoil names of globals with C linkage, so use an heuristic
184 // approach to check if the name should be demangled.
185 return (name[0] == '_' && name[1] == 'Z')
186 ? Symbolizer::Get()->Demangle(name)
187 : name;
190 // Check if the global is a zero-terminated ASCII string. If so, print it.
191 static void PrintGlobalNameIfASCII(const __asan_global &g) {
192 for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
193 unsigned char c = *(unsigned char*)p;
194 if (c == '\0' || !IsASCII(c)) return;
196 if (*(char*)(g.beg + g.size - 1) != '\0') return;
197 Printf(" '%s' is ascii string '%s'\n",
198 MaybeDemangleGlobalName(g.name), (char*)g.beg);
201 bool DescribeAddressRelativeToGlobal(uptr addr, uptr size,
202 const __asan_global &g) {
203 static const uptr kMinimalDistanceFromAnotherGlobal = 64;
204 if (addr <= g.beg - kMinimalDistanceFromAnotherGlobal) return false;
205 if (addr >= g.beg + g.size_with_redzone) return false;
206 Decorator d;
207 Printf("%s", d.Location());
208 if (addr < g.beg) {
209 Printf("%p is located %zd bytes to the left", (void*)addr, g.beg - addr);
210 } else if (addr + size > g.beg + g.size) {
211 if (addr < g.beg + g.size)
212 addr = g.beg + g.size;
213 Printf("%p is located %zd bytes to the right", (void*)addr,
214 addr - (g.beg + g.size));
215 } else {
216 // Can it happen?
217 Printf("%p is located %zd bytes inside", (void*)addr, addr - g.beg);
219 Printf(" of global variable '%s' from '%s' (0x%zx) of size %zu\n",
220 MaybeDemangleGlobalName(g.name), g.module_name, g.beg, g.size);
221 Printf("%s", d.EndLocation());
222 PrintGlobalNameIfASCII(g);
223 return true;
226 bool DescribeAddressIfShadow(uptr addr) {
227 if (AddrIsInMem(addr))
228 return false;
229 static const char kAddrInShadowReport[] =
230 "Address %p is located in the %s.\n";
231 if (AddrIsInShadowGap(addr)) {
232 Printf(kAddrInShadowReport, addr, "shadow gap area");
233 return true;
235 if (AddrIsInHighShadow(addr)) {
236 Printf(kAddrInShadowReport, addr, "high shadow area");
237 return true;
239 if (AddrIsInLowShadow(addr)) {
240 Printf(kAddrInShadowReport, addr, "low shadow area");
241 return true;
243 CHECK(0 && "Address is not in memory and not in shadow?");
244 return false;
247 // Return " (thread_name) " or an empty string if the name is empty.
248 const char *ThreadNameWithParenthesis(AsanThreadContext *t, char buff[],
249 uptr buff_len) {
250 const char *name = t->name;
251 if (name[0] == '\0') return "";
252 buff[0] = 0;
253 internal_strncat(buff, " (", 3);
254 internal_strncat(buff, name, buff_len - 4);
255 internal_strncat(buff, ")", 2);
256 return buff;
259 const char *ThreadNameWithParenthesis(u32 tid, char buff[],
260 uptr buff_len) {
261 if (tid == kInvalidTid) return "";
262 asanThreadRegistry().CheckLocked();
263 AsanThreadContext *t = GetThreadContextByTidLocked(tid);
264 return ThreadNameWithParenthesis(t, buff, buff_len);
267 void PrintAccessAndVarIntersection(const char *var_name,
268 uptr var_beg, uptr var_size,
269 uptr addr, uptr access_size,
270 uptr prev_var_end, uptr next_var_beg) {
271 uptr var_end = var_beg + var_size;
272 uptr addr_end = addr + access_size;
273 const char *pos_descr = 0;
274 // If the variable [var_beg, var_end) is the nearest variable to the
275 // current memory access, indicate it in the log.
276 if (addr >= var_beg) {
277 if (addr_end <= var_end)
278 pos_descr = "is inside"; // May happen if this is a use-after-return.
279 else if (addr < var_end)
280 pos_descr = "partially overflows";
281 else if (addr_end <= next_var_beg &&
282 next_var_beg - addr_end >= addr - var_end)
283 pos_descr = "overflows";
284 } else {
285 if (addr_end > var_beg)
286 pos_descr = "partially underflows";
287 else if (addr >= prev_var_end &&
288 addr - prev_var_end >= var_beg - addr_end)
289 pos_descr = "underflows";
291 Printf(" [%zd, %zd) '%s'", var_beg, var_beg + var_size, var_name);
292 if (pos_descr) {
293 Decorator d;
294 // FIXME: we may want to also print the size of the access here,
295 // but in case of accesses generated by memset it may be confusing.
296 Printf("%s <== Memory access at offset %zd %s this variable%s\n",
297 d.Location(), addr, pos_descr, d.EndLocation());
298 } else {
299 Printf("\n");
303 struct StackVarDescr {
304 uptr beg;
305 uptr size;
306 const char *name_pos;
307 uptr name_len;
310 bool DescribeAddressIfStack(uptr addr, uptr access_size) {
311 AsanThread *t = FindThreadByStackAddress(addr);
312 if (!t) return false;
313 const uptr kBufSize = 4095;
314 char buf[kBufSize];
315 uptr offset = 0;
316 uptr frame_pc = 0;
317 char tname[128];
318 const char *frame_descr = t->GetFrameNameByAddr(addr, &offset, &frame_pc);
320 #ifdef __powerpc64__
321 // On PowerPC64, the address of a function actually points to a
322 // three-doubleword data structure with the first field containing
323 // the address of the function's code.
324 frame_pc = *reinterpret_cast<uptr *>(frame_pc);
325 #endif
327 // This string is created by the compiler and has the following form:
328 // "n alloc_1 alloc_2 ... alloc_n"
329 // where alloc_i looks like "offset size len ObjectName ".
330 CHECK(frame_descr);
331 Decorator d;
332 Printf("%s", d.Location());
333 Printf("Address %p is located in stack of thread T%d%s "
334 "at offset %zu in frame\n",
335 addr, t->tid(),
336 ThreadNameWithParenthesis(t->tid(), tname, sizeof(tname)),
337 offset);
338 // Now we print the frame where the alloca has happened.
339 // We print this frame as a stack trace with one element.
340 // The symbolizer may print more than one frame if inlining was involved.
341 // The frame numbers may be different than those in the stack trace printed
342 // previously. That's unfortunate, but I have no better solution,
343 // especially given that the alloca may be from entirely different place
344 // (e.g. use-after-scope, or different thread's stack).
345 StackTrace alloca_stack;
346 alloca_stack.trace[0] = frame_pc + 16;
347 alloca_stack.size = 1;
348 Printf("%s", d.EndLocation());
349 PrintStack(&alloca_stack);
350 // Report the number of stack objects.
351 char *p;
352 uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
353 CHECK_GT(n_objects, 0);
354 Printf(" This frame has %zu object(s):\n", n_objects);
356 // Report all objects in this frame.
357 InternalScopedBuffer<StackVarDescr> vars(n_objects);
358 for (uptr i = 0; i < n_objects; i++) {
359 uptr beg, size;
360 uptr len;
361 beg = (uptr)internal_simple_strtoll(p, &p, 10);
362 size = (uptr)internal_simple_strtoll(p, &p, 10);
363 len = (uptr)internal_simple_strtoll(p, &p, 10);
364 if (beg == 0 || size == 0 || *p != ' ') {
365 Printf("AddressSanitizer can't parse the stack frame "
366 "descriptor: |%s|\n", frame_descr);
367 break;
369 p++;
370 vars[i].beg = beg;
371 vars[i].size = size;
372 vars[i].name_pos = p;
373 vars[i].name_len = len;
374 p += len;
376 for (uptr i = 0; i < n_objects; i++) {
377 buf[0] = 0;
378 internal_strncat(buf, vars[i].name_pos,
379 static_cast<uptr>(Min(kBufSize, vars[i].name_len)));
380 uptr prev_var_end = i ? vars[i - 1].beg + vars[i - 1].size : 0;
381 uptr next_var_beg = i + 1 < n_objects ? vars[i + 1].beg : ~(0UL);
382 PrintAccessAndVarIntersection(buf, vars[i].beg, vars[i].size,
383 offset, access_size,
384 prev_var_end, next_var_beg);
386 Printf("HINT: this may be a false positive if your program uses "
387 "some custom stack unwind mechanism or swapcontext\n"
388 " (longjmp and C++ exceptions *are* supported)\n");
389 DescribeThread(t);
390 return true;
393 static void DescribeAccessToHeapChunk(AsanChunkView chunk, uptr addr,
394 uptr access_size) {
395 sptr offset;
396 Decorator d;
397 Printf("%s", d.Location());
398 if (chunk.AddrIsAtLeft(addr, access_size, &offset)) {
399 Printf("%p is located %zd bytes to the left of", (void*)addr, offset);
400 } else if (chunk.AddrIsAtRight(addr, access_size, &offset)) {
401 if (offset < 0) {
402 addr -= offset;
403 offset = 0;
405 Printf("%p is located %zd bytes to the right of", (void*)addr, offset);
406 } else if (chunk.AddrIsInside(addr, access_size, &offset)) {
407 Printf("%p is located %zd bytes inside of", (void*)addr, offset);
408 } else {
409 Printf("%p is located somewhere around (this is AddressSanitizer bug!)",
410 (void*)addr);
412 Printf(" %zu-byte region [%p,%p)\n", chunk.UsedSize(),
413 (void*)(chunk.Beg()), (void*)(chunk.End()));
414 Printf("%s", d.EndLocation());
417 void DescribeHeapAddress(uptr addr, uptr access_size) {
418 AsanChunkView chunk = FindHeapChunkByAddress(addr);
419 if (!chunk.IsValid()) {
420 Printf("AddressSanitizer can not describe address in more detail "
421 "(wild memory access suspected).\n");
422 return;
424 DescribeAccessToHeapChunk(chunk, addr, access_size);
425 CHECK(chunk.AllocTid() != kInvalidTid);
426 asanThreadRegistry().CheckLocked();
427 AsanThreadContext *alloc_thread =
428 GetThreadContextByTidLocked(chunk.AllocTid());
429 StackTrace alloc_stack;
430 chunk.GetAllocStack(&alloc_stack);
431 char tname[128];
432 Decorator d;
433 AsanThreadContext *free_thread = 0;
434 if (chunk.FreeTid() != kInvalidTid) {
435 free_thread = GetThreadContextByTidLocked(chunk.FreeTid());
436 Printf("%sfreed by thread T%d%s here:%s\n", d.Allocation(),
437 free_thread->tid,
438 ThreadNameWithParenthesis(free_thread, tname, sizeof(tname)),
439 d.EndAllocation());
440 StackTrace free_stack;
441 chunk.GetFreeStack(&free_stack);
442 PrintStack(&free_stack);
443 Printf("%spreviously allocated by thread T%d%s here:%s\n",
444 d.Allocation(), alloc_thread->tid,
445 ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
446 d.EndAllocation());
447 } else {
448 Printf("%sallocated by thread T%d%s here:%s\n", d.Allocation(),
449 alloc_thread->tid,
450 ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
451 d.EndAllocation());
453 PrintStack(&alloc_stack);
454 DescribeThread(GetCurrentThread());
455 if (free_thread)
456 DescribeThread(free_thread);
457 DescribeThread(alloc_thread);
460 void DescribeAddress(uptr addr, uptr access_size) {
461 // Check if this is shadow or shadow gap.
462 if (DescribeAddressIfShadow(addr))
463 return;
464 CHECK(AddrIsInMem(addr));
465 if (DescribeAddressIfGlobal(addr, access_size))
466 return;
467 if (DescribeAddressIfStack(addr, access_size))
468 return;
469 // Assume it is a heap address.
470 DescribeHeapAddress(addr, access_size);
473 // ------------------- Thread description -------------------- {{{1
475 void DescribeThread(AsanThreadContext *context) {
476 CHECK(context);
477 asanThreadRegistry().CheckLocked();
478 // No need to announce the main thread.
479 if (context->tid == 0 || context->announced) {
480 return;
482 context->announced = true;
483 char tname[128];
484 Printf("Thread T%d%s", context->tid,
485 ThreadNameWithParenthesis(context->tid, tname, sizeof(tname)));
486 Printf(" created by T%d%s here:\n",
487 context->parent_tid,
488 ThreadNameWithParenthesis(context->parent_tid,
489 tname, sizeof(tname)));
490 uptr stack_size;
491 const uptr *stack_trace = StackDepotGet(context->stack_id, &stack_size);
492 PrintStack(stack_trace, stack_size);
493 // Recursively described parent thread if needed.
494 if (flags()->print_full_thread_history) {
495 AsanThreadContext *parent_context =
496 GetThreadContextByTidLocked(context->parent_tid);
497 DescribeThread(parent_context);
501 // -------------------- Different kinds of reports ----------------- {{{1
503 // Use ScopedInErrorReport to run common actions just before and
504 // immediately after printing error report.
505 class ScopedInErrorReport {
506 public:
507 ScopedInErrorReport() {
508 static atomic_uint32_t num_calls;
509 static u32 reporting_thread_tid;
510 if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
511 // Do not print more than one report, otherwise they will mix up.
512 // Error reporting functions shouldn't return at this situation, as
513 // they are defined as no-return.
514 Report("AddressSanitizer: while reporting a bug found another one."
515 "Ignoring.\n");
516 u32 current_tid = GetCurrentTidOrInvalid();
517 if (current_tid != reporting_thread_tid) {
518 // ASan found two bugs in different threads simultaneously. Sleep
519 // long enough to make sure that the thread which started to print
520 // an error report will finish doing it.
521 SleepForSeconds(Max(100, flags()->sleep_before_dying + 1));
523 // If we're still not dead for some reason, use raw _exit() instead of
524 // Die() to bypass any additional checks.
525 internal__exit(flags()->exitcode);
527 ASAN_ON_ERROR();
528 // Make sure the registry and sanitizer report mutexes are locked while
529 // we're printing an error report.
530 // We can lock them only here to avoid self-deadlock in case of
531 // recursive reports.
532 asanThreadRegistry().Lock();
533 CommonSanitizerReportMutex.Lock();
534 reporting_thread_tid = GetCurrentTidOrInvalid();
535 Printf("===================================================="
536 "=============\n");
538 // Destructor is NORETURN, as functions that report errors are.
539 NORETURN ~ScopedInErrorReport() {
540 // Make sure the current thread is announced.
541 DescribeThread(GetCurrentThread());
542 // Print memory stats.
543 if (flags()->print_stats)
544 __asan_print_accumulated_stats();
545 if (error_report_callback) {
546 error_report_callback(error_message_buffer);
548 Report("ABORTING\n");
549 Die();
553 void ReportSIGSEGV(uptr pc, uptr sp, uptr bp, uptr addr) {
554 ScopedInErrorReport in_report;
555 Decorator d;
556 Printf("%s", d.Warning());
557 Report("ERROR: AddressSanitizer: SEGV on unknown address %p"
558 " (pc %p sp %p bp %p T%d)\n",
559 (void*)addr, (void*)pc, (void*)sp, (void*)bp,
560 GetCurrentTidOrInvalid());
561 Printf("%s", d.EndWarning());
562 GET_STACK_TRACE_FATAL(pc, bp);
563 PrintStack(&stack);
564 Printf("AddressSanitizer can not provide additional info.\n");
565 ReportErrorSummary("SEGV", &stack);
568 void ReportDoubleFree(uptr addr, StackTrace *free_stack) {
569 ScopedInErrorReport in_report;
570 Decorator d;
571 Printf("%s", d.Warning());
572 char tname[128];
573 u32 curr_tid = GetCurrentTidOrInvalid();
574 Report("ERROR: AddressSanitizer: attempting double-free on %p in "
575 "thread T%d%s:\n",
576 addr, curr_tid,
577 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
578 Printf("%s", d.EndWarning());
579 CHECK_GT(free_stack->size, 0);
580 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
581 PrintStack(&stack);
582 DescribeHeapAddress(addr, 1);
583 ReportErrorSummary("double-free", &stack);
586 void ReportFreeNotMalloced(uptr addr, StackTrace *free_stack) {
587 ScopedInErrorReport in_report;
588 Decorator d;
589 Printf("%s", d.Warning());
590 char tname[128];
591 u32 curr_tid = GetCurrentTidOrInvalid();
592 Report("ERROR: AddressSanitizer: attempting free on address "
593 "which was not malloc()-ed: %p in thread T%d%s\n", addr,
594 curr_tid, ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
595 Printf("%s", d.EndWarning());
596 CHECK_GT(free_stack->size, 0);
597 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
598 PrintStack(&stack);
599 DescribeHeapAddress(addr, 1);
600 ReportErrorSummary("bad-free", &stack);
603 void ReportAllocTypeMismatch(uptr addr, StackTrace *free_stack,
604 AllocType alloc_type,
605 AllocType dealloc_type) {
606 static const char *alloc_names[] =
607 {"INVALID", "malloc", "operator new", "operator new []"};
608 static const char *dealloc_names[] =
609 {"INVALID", "free", "operator delete", "operator delete []"};
610 CHECK_NE(alloc_type, dealloc_type);
611 ScopedInErrorReport in_report;
612 Decorator d;
613 Printf("%s", d.Warning());
614 Report("ERROR: AddressSanitizer: alloc-dealloc-mismatch (%s vs %s) on %p\n",
615 alloc_names[alloc_type], dealloc_names[dealloc_type], addr);
616 Printf("%s", d.EndWarning());
617 CHECK_GT(free_stack->size, 0);
618 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
619 PrintStack(&stack);
620 DescribeHeapAddress(addr, 1);
621 ReportErrorSummary("alloc-dealloc-mismatch", &stack);
622 Report("HINT: if you don't care about these warnings you may set "
623 "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n");
626 void ReportMallocUsableSizeNotOwned(uptr addr, StackTrace *stack) {
627 ScopedInErrorReport in_report;
628 Decorator d;
629 Printf("%s", d.Warning());
630 Report("ERROR: AddressSanitizer: attempting to call "
631 "malloc_usable_size() for pointer which is "
632 "not owned: %p\n", addr);
633 Printf("%s", d.EndWarning());
634 PrintStack(stack);
635 DescribeHeapAddress(addr, 1);
636 ReportErrorSummary("bad-malloc_usable_size", stack);
639 void ReportAsanGetAllocatedSizeNotOwned(uptr addr, StackTrace *stack) {
640 ScopedInErrorReport in_report;
641 Decorator d;
642 Printf("%s", d.Warning());
643 Report("ERROR: AddressSanitizer: attempting to call "
644 "__asan_get_allocated_size() for pointer which is "
645 "not owned: %p\n", addr);
646 Printf("%s", d.EndWarning());
647 PrintStack(stack);
648 DescribeHeapAddress(addr, 1);
649 ReportErrorSummary("bad-__asan_get_allocated_size", stack);
652 void ReportStringFunctionMemoryRangesOverlap(
653 const char *function, const char *offset1, uptr length1,
654 const char *offset2, uptr length2, StackTrace *stack) {
655 ScopedInErrorReport in_report;
656 Decorator d;
657 char bug_type[100];
658 internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function);
659 Printf("%s", d.Warning());
660 Report("ERROR: AddressSanitizer: %s: "
661 "memory ranges [%p,%p) and [%p, %p) overlap\n", \
662 bug_type, offset1, offset1 + length1, offset2, offset2 + length2);
663 Printf("%s", d.EndWarning());
664 PrintStack(stack);
665 DescribeAddress((uptr)offset1, length1);
666 DescribeAddress((uptr)offset2, length2);
667 ReportErrorSummary(bug_type, stack);
670 // ----------------------- Mac-specific reports ----------------- {{{1
672 void WarnMacFreeUnallocated(
673 uptr addr, uptr zone_ptr, const char *zone_name, StackTrace *stack) {
674 // Just print a warning here.
675 Printf("free_common(%p) -- attempting to free unallocated memory.\n"
676 "AddressSanitizer is ignoring this error on Mac OS now.\n",
677 addr);
678 PrintZoneForPointer(addr, zone_ptr, zone_name);
679 PrintStack(stack);
680 DescribeHeapAddress(addr, 1);
683 void ReportMacMzReallocUnknown(
684 uptr addr, uptr zone_ptr, const char *zone_name, StackTrace *stack) {
685 ScopedInErrorReport in_report;
686 Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
687 "This is an unrecoverable problem, exiting now.\n",
688 addr);
689 PrintZoneForPointer(addr, zone_ptr, zone_name);
690 PrintStack(stack);
691 DescribeHeapAddress(addr, 1);
694 void ReportMacCfReallocUnknown(
695 uptr addr, uptr zone_ptr, const char *zone_name, StackTrace *stack) {
696 ScopedInErrorReport in_report;
697 Printf("cf_realloc(%p) -- attempting to realloc unallocated memory.\n"
698 "This is an unrecoverable problem, exiting now.\n",
699 addr);
700 PrintZoneForPointer(addr, zone_ptr, zone_name);
701 PrintStack(stack);
702 DescribeHeapAddress(addr, 1);
705 } // namespace __asan
707 // --------------------------- Interface --------------------- {{{1
708 using namespace __asan; // NOLINT
710 void __asan_report_error(uptr pc, uptr bp, uptr sp,
711 uptr addr, bool is_write, uptr access_size) {
712 ScopedInErrorReport in_report;
714 // Determine the error type.
715 const char *bug_descr = "unknown-crash";
716 if (AddrIsInMem(addr)) {
717 u8 *shadow_addr = (u8*)MemToShadow(addr);
718 // If we are accessing 16 bytes, look at the second shadow byte.
719 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
720 shadow_addr++;
721 // If we are in the partial right redzone, look at the next shadow byte.
722 if (*shadow_addr > 0 && *shadow_addr < 128)
723 shadow_addr++;
724 switch (*shadow_addr) {
725 case kAsanHeapLeftRedzoneMagic:
726 case kAsanHeapRightRedzoneMagic:
727 bug_descr = "heap-buffer-overflow";
728 break;
729 case kAsanHeapFreeMagic:
730 bug_descr = "heap-use-after-free";
731 break;
732 case kAsanStackLeftRedzoneMagic:
733 bug_descr = "stack-buffer-underflow";
734 break;
735 case kAsanInitializationOrderMagic:
736 bug_descr = "initialization-order-fiasco";
737 break;
738 case kAsanStackMidRedzoneMagic:
739 case kAsanStackRightRedzoneMagic:
740 case kAsanStackPartialRedzoneMagic:
741 bug_descr = "stack-buffer-overflow";
742 break;
743 case kAsanStackAfterReturnMagic:
744 bug_descr = "stack-use-after-return";
745 break;
746 case kAsanUserPoisonedMemoryMagic:
747 bug_descr = "use-after-poison";
748 break;
749 case kAsanContiguousContainerOOBMagic:
750 bug_descr = "container-overflow";
751 break;
752 case kAsanStackUseAfterScopeMagic:
753 bug_descr = "stack-use-after-scope";
754 break;
755 case kAsanGlobalRedzoneMagic:
756 bug_descr = "global-buffer-overflow";
757 break;
760 Decorator d;
761 Printf("%s", d.Warning());
762 Report("ERROR: AddressSanitizer: %s on address "
763 "%p at pc 0x%zx bp 0x%zx sp 0x%zx\n",
764 bug_descr, (void*)addr, pc, bp, sp);
765 Printf("%s", d.EndWarning());
767 u32 curr_tid = GetCurrentTidOrInvalid();
768 char tname[128];
769 Printf("%s%s of size %zu at %p thread T%d%s%s\n",
770 d.Access(),
771 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
772 access_size, (void*)addr, curr_tid,
773 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)),
774 d.EndAccess());
776 GET_STACK_TRACE_FATAL(pc, bp);
777 PrintStack(&stack);
779 DescribeAddress(addr, access_size);
780 ReportErrorSummary(bug_descr, &stack);
781 PrintShadowMemoryForAddress(addr);
784 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
785 error_report_callback = callback;
786 if (callback) {
787 error_message_buffer_size = 1 << 16;
788 error_message_buffer =
789 (char*)MmapOrDie(error_message_buffer_size, __FUNCTION__);
790 error_message_buffer_pos = 0;
794 void __asan_describe_address(uptr addr) {
795 DescribeAddress(addr, 1);
798 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
799 // Provide default implementation of __asan_on_error that does nothing
800 // and may be overriden by user.
801 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE
802 void __asan_on_error() {}
803 #endif