asan_report.cc revision 9514a53d7b56be6302c666291b21c0387f7ceca8
1//===-- asan_report.cc ----------------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11//
12// This file contains error reporting code.
13//===----------------------------------------------------------------------===//
14#include "asan_flags.h"
15#include "asan_internal.h"
16#include "asan_mapping.h"
17#include "asan_report.h"
18#include "asan_stack.h"
19#include "asan_thread.h"
20#include "asan_thread_registry.h"
21#include "sanitizer_common/sanitizer_common.h"
22#include "sanitizer_common/sanitizer_report_decorator.h"
23
24namespace __asan {
25
26// -------------------- User-specified callbacks ----------------- {{{1
27static void (*error_report_callback)(const char*);
28static char *error_message_buffer = 0;
29static uptr error_message_buffer_pos = 0;
30static uptr error_message_buffer_size = 0;
31
32void 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;
42  }
43}
44
45// ---------------------- Decorator ------------------------------ {{{1
46bool PrintsToTtyCached() {
47  static int cached = 0;
48  static bool prints_to_tty;
49  if (!cached) {  // Ok wrt threads since we are printing only from one thread.
50    prints_to_tty = PrintsToTty();
51    cached = 1;
52  }
53  return prints_to_tty;
54}
55class Decorator: private __sanitizer::AnsiColorDecorator {
56 public:
57  Decorator() : __sanitizer::AnsiColorDecorator(PrintsToTtyCached()) { }
58  const char *Warning()    { return Red(); }
59  const char *EndWarning() { return Default(); }
60  const char *Access()     { return Blue(); }
61  const char *EndAccess()  { return Default(); }
62  const char *Location()   { return Green(); }
63  const char *EndLocation() { return Default(); }
64  const char *Allocation()  { return Magenta(); }
65  const char *EndAllocation()  { return Default(); }
66
67  const char *ShadowByte(u8 byte) {
68    switch (byte) {
69      case kAsanHeapLeftRedzoneMagic:
70      case kAsanHeapRightRedzoneMagic:
71        return Red();
72      case kAsanHeapFreeMagic:
73        return Magenta();
74      case kAsanStackLeftRedzoneMagic:
75      case kAsanStackMidRedzoneMagic:
76      case kAsanStackRightRedzoneMagic:
77      case kAsanStackPartialRedzoneMagic:
78        return Red();
79      case kAsanStackAfterReturnMagic:
80        return Magenta();
81      case kAsanInitializationOrderMagic:
82        return Cyan();
83      case kAsanUserPoisonedMemoryMagic:
84        return Blue();
85      case kAsanStackUseAfterScopeMagic:
86        return Magenta();
87      case kAsanGlobalRedzoneMagic:
88        return Red();
89      case kAsanInternalHeapMagic:
90        return Yellow();
91      default:
92        return Default();
93    }
94  }
95  const char *EndShadowByte() { return Default(); }
96};
97
98// ---------------------- Helper functions ----------------------- {{{1
99
100static void PrintShadowByte(const char *before, u8 byte,
101                            const char *after = "\n") {
102  Decorator d;
103  Printf("%s%s%x%x%s%s", before,
104         d.ShadowByte(byte), byte >> 4, byte & 15, d.EndShadowByte(), after);
105}
106
107static void PrintShadowBytes(const char *before, u8 *bytes,
108                             u8 *guilty, uptr n) {
109  Decorator d;
110  if (before)
111    Printf("%s%p:", before, bytes);
112  for (uptr i = 0; i < n; i++) {
113    u8 *p = bytes + i;
114    const char *before = p == guilty ? "[" :
115        p - 1 == guilty ? "" : " ";
116    const char *after = p == guilty ? "]" : "";
117    PrintShadowByte(before, *p, after);
118  }
119  Printf("\n");
120}
121
122static void PrintShadowMemoryForAddress(uptr addr) {
123  if (!AddrIsInMem(addr))
124    return;
125  uptr shadow_addr = MemToShadow(addr);
126  const uptr n_bytes_per_row = 16;
127  uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1);
128  Printf("Shadow bytes around the buggy address:\n");
129  for (int i = -5; i <= 5; i++) {
130    const char *prefix = (i == 0) ? "=>" : "  ";
131    PrintShadowBytes(prefix,
132                     (u8*)(aligned_shadow + i * n_bytes_per_row),
133                     (u8*)shadow_addr, n_bytes_per_row);
134  }
135  Printf("Shadow byte legend (one shadow byte represents %d "
136         "application bytes):\n", (int)SHADOW_GRANULARITY);
137  PrintShadowByte("  Addressable:           ", 0);
138  Printf("  Partially addressable: ");
139  for (uptr i = 1; i < SHADOW_GRANULARITY; i++)
140    PrintShadowByte("", i, " ");
141  Printf("\n");
142  PrintShadowByte("  Heap left redzone:     ", kAsanHeapLeftRedzoneMagic);
143  PrintShadowByte("  Heap righ redzone:     ", kAsanHeapRightRedzoneMagic);
144  PrintShadowByte("  Freed Heap region:     ", kAsanHeapFreeMagic);
145  PrintShadowByte("  Stack left redzone:    ", kAsanStackLeftRedzoneMagic);
146  PrintShadowByte("  Stack mid redzone:     ", kAsanStackMidRedzoneMagic);
147  PrintShadowByte("  Stack right redzone:   ", kAsanStackRightRedzoneMagic);
148  PrintShadowByte("  Stack partial redzone: ", kAsanStackPartialRedzoneMagic);
149  PrintShadowByte("  Stack right redzone:   ", kAsanStackRightRedzoneMagic);
150  PrintShadowByte("  Stack after return:    ", kAsanStackAfterReturnMagic);
151  PrintShadowByte("  Stack use after scope: ", kAsanStackUseAfterScopeMagic);
152  PrintShadowByte("  Global redzone:        ", kAsanGlobalRedzoneMagic);
153  PrintShadowByte("  Global init order:     ", kAsanInitializationOrderMagic);
154  PrintShadowByte("  Poisoned by user:      ", kAsanUserPoisonedMemoryMagic);
155  PrintShadowByte("  ASan internal:         ", kAsanInternalHeapMagic);
156}
157
158static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
159                                const char *zone_name) {
160  if (zone_ptr) {
161    if (zone_name) {
162      Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
163                 ptr, zone_ptr, zone_name);
164    } else {
165      Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
166                 ptr, zone_ptr);
167    }
168  } else {
169    Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
170  }
171}
172
173// ---------------------- Address Descriptions ------------------- {{{1
174
175static bool IsASCII(unsigned char c) {
176  return /*0x00 <= c &&*/ c <= 0x7F;
177}
178
179// Check if the global is a zero-terminated ASCII string. If so, print it.
180static void PrintGlobalNameIfASCII(const __asan_global &g) {
181  for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
182    if (!IsASCII(*(unsigned char*)p)) return;
183  }
184  if (*(char*)(g.beg + g.size - 1) != 0) return;
185  Printf("  '%s' is ascii string '%s'\n", g.name, (char*)g.beg);
186}
187
188bool DescribeAddressRelativeToGlobal(uptr addr, const __asan_global &g) {
189  if (addr < g.beg - kGlobalAndStackRedzone) return false;
190  if (addr >= g.beg + g.size_with_redzone) return false;
191  Decorator d;
192  Printf("%s", d.Location());
193  Printf("%p is located ", (void*)addr);
194  if (addr < g.beg) {
195    Printf("%zd bytes to the left", g.beg - addr);
196  } else if (addr >= g.beg + g.size) {
197    Printf("%zd bytes to the right", addr - (g.beg + g.size));
198  } else {
199    Printf("%zd bytes inside", addr - g.beg);  // Can it happen?
200  }
201  Printf(" of global variable '%s' (0x%zx) of size %zu\n",
202             g.name, g.beg, g.size);
203  Printf("%s", d.EndLocation());
204  PrintGlobalNameIfASCII(g);
205  return true;
206}
207
208bool DescribeAddressIfShadow(uptr addr) {
209  if (AddrIsInMem(addr))
210    return false;
211  static const char kAddrInShadowReport[] =
212      "Address %p is located in the %s.\n";
213  if (AddrIsInShadowGap(addr)) {
214    Printf(kAddrInShadowReport, addr, "shadow gap area");
215    return true;
216  }
217  if (AddrIsInHighShadow(addr)) {
218    Printf(kAddrInShadowReport, addr, "high shadow area");
219    return true;
220  }
221  if (AddrIsInLowShadow(addr)) {
222    Printf(kAddrInShadowReport, addr, "low shadow area");
223    return true;
224  }
225  CHECK(0 && "Address is not in memory and not in shadow?");
226  return false;
227}
228
229bool DescribeAddressIfStack(uptr addr, uptr access_size) {
230  AsanThread *t = asanThreadRegistry().FindThreadByStackAddress(addr);
231  if (!t) return false;
232  const sptr kBufSize = 4095;
233  char buf[kBufSize];
234  uptr offset = 0;
235  const char *frame_descr = t->GetFrameNameByAddr(addr, &offset);
236  // This string is created by the compiler and has the following form:
237  // "FunctioName n alloc_1 alloc_2 ... alloc_n"
238  // where alloc_i looks like "offset size len ObjectName ".
239  CHECK(frame_descr);
240  // Report the function name and the offset.
241  const char *name_end = internal_strchr(frame_descr, ' ');
242  CHECK(name_end);
243  buf[0] = 0;
244  internal_strncat(buf, frame_descr,
245                   Min(kBufSize,
246                       static_cast<sptr>(name_end - frame_descr)));
247  Decorator d;
248  Printf("%s", d.Location());
249  Printf("Address %p is located at offset %zu "
250             "in frame <%s> of T%d's stack:\n",
251             (void*)addr, offset, buf, t->tid());
252  Printf("%s", d.EndLocation());
253  // Report the number of stack objects.
254  char *p;
255  uptr n_objects = internal_simple_strtoll(name_end, &p, 10);
256  CHECK(n_objects > 0);
257  Printf("  This frame has %zu object(s):\n", n_objects);
258  // Report all objects in this frame.
259  for (uptr i = 0; i < n_objects; i++) {
260    uptr beg, size;
261    sptr len;
262    beg  = internal_simple_strtoll(p, &p, 10);
263    size = internal_simple_strtoll(p, &p, 10);
264    len  = internal_simple_strtoll(p, &p, 10);
265    if (beg <= 0 || size <= 0 || len < 0 || *p != ' ') {
266      Printf("AddressSanitizer can't parse the stack frame "
267                 "descriptor: |%s|\n", frame_descr);
268      break;
269    }
270    p++;
271    buf[0] = 0;
272    internal_strncat(buf, p, Min(kBufSize, len));
273    p += len;
274    Printf("    [%zu, %zu) '%s'\n", beg, beg + size, buf);
275  }
276  Printf("HINT: this may be a false positive if your program uses "
277             "some custom stack unwind mechanism or swapcontext\n"
278             "      (longjmp and C++ exceptions *are* supported)\n");
279  DescribeThread(t->summary());
280  return true;
281}
282
283static void DescribeAccessToHeapChunk(AsanChunkView chunk, uptr addr,
284                                      uptr access_size) {
285  uptr offset;
286  Decorator d;
287  Printf("%s", d.Location());
288  Printf("%p is located ", (void*)addr);
289  if (chunk.AddrIsInside(addr, access_size, &offset)) {
290    Printf("%zu bytes inside of", offset);
291  } else if (chunk.AddrIsAtLeft(addr, access_size, &offset)) {
292    Printf("%zu bytes to the left of", offset);
293  } else if (chunk.AddrIsAtRight(addr, access_size, &offset)) {
294    Printf("%zu bytes to the right of", offset);
295  } else {
296    Printf(" somewhere around (this is AddressSanitizer bug!)");
297  }
298  Printf(" %zu-byte region [%p,%p)\n", chunk.UsedSize(),
299         (void*)(chunk.Beg()), (void*)(chunk.End()));
300  Printf("%s", d.EndLocation());
301}
302
303// Return " (thread_name) " or an empty string if the name is empty.
304const char *ThreadNameWithParenthesis(AsanThreadSummary *t, char buff[],
305                                      uptr buff_len) {
306  const char *name = t->name();
307  if (*name == 0) return "";
308  buff[0] = 0;
309  internal_strncat(buff, " (", 3);
310  internal_strncat(buff, name, buff_len - 4);
311  internal_strncat(buff, ")", 2);
312  return buff;
313}
314
315const char *ThreadNameWithParenthesis(u32 tid, char buff[],
316                                      uptr buff_len) {
317  if (tid == kInvalidTid) return "";
318  AsanThreadSummary *t = asanThreadRegistry().FindByTid(tid);
319  return ThreadNameWithParenthesis(t, buff, buff_len);
320}
321
322void DescribeHeapAddress(uptr addr, uptr access_size) {
323  AsanChunkView chunk = FindHeapChunkByAddress(addr);
324  if (!chunk.IsValid()) return;
325  DescribeAccessToHeapChunk(chunk, addr, access_size);
326  CHECK(chunk.AllocTid() != kInvalidTid);
327  AsanThreadSummary *alloc_thread =
328      asanThreadRegistry().FindByTid(chunk.AllocTid());
329  StackTrace alloc_stack;
330  chunk.GetAllocStack(&alloc_stack);
331  AsanThread *t = asanThreadRegistry().GetCurrent();
332  CHECK(t);
333  char tname[128];
334  Decorator d;
335  if (chunk.FreeTid() != kInvalidTid) {
336    AsanThreadSummary *free_thread =
337        asanThreadRegistry().FindByTid(chunk.FreeTid());
338    Printf("%sfreed by thread T%d%s here:%s\n", d.Allocation(),
339           free_thread->tid(),
340           ThreadNameWithParenthesis(free_thread, tname, sizeof(tname)),
341           d.EndAllocation());
342    StackTrace free_stack;
343    chunk.GetFreeStack(&free_stack);
344    PrintStack(&free_stack);
345    Printf("%spreviously allocated by thread T%d%s here:%s\n",
346           d.Allocation(), alloc_thread->tid(),
347           ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
348           d.EndAllocation());
349    PrintStack(&alloc_stack);
350    DescribeThread(t->summary());
351    DescribeThread(free_thread);
352    DescribeThread(alloc_thread);
353  } else {
354    Printf("%sallocated by thread T%d%s here:%s\n", d.Allocation(),
355           alloc_thread->tid(),
356           ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
357           d.EndAllocation());
358    PrintStack(&alloc_stack);
359    DescribeThread(t->summary());
360    DescribeThread(alloc_thread);
361  }
362}
363
364void DescribeAddress(uptr addr, uptr access_size) {
365  // Check if this is shadow or shadow gap.
366  if (DescribeAddressIfShadow(addr))
367    return;
368  CHECK(AddrIsInMem(addr));
369  if (DescribeAddressIfGlobal(addr))
370    return;
371  if (DescribeAddressIfStack(addr, access_size))
372    return;
373  // Assume it is a heap address.
374  DescribeHeapAddress(addr, access_size);
375}
376
377// ------------------- Thread description -------------------- {{{1
378
379void DescribeThread(AsanThreadSummary *summary) {
380  CHECK(summary);
381  // No need to announce the main thread.
382  if (summary->tid() == 0 || summary->announced()) {
383    return;
384  }
385  summary->set_announced(true);
386  char tname[128];
387  Printf("Thread T%d%s", summary->tid(),
388         ThreadNameWithParenthesis(summary->tid(), tname, sizeof(tname)));
389  Printf(" created by T%d%s here:\n",
390         summary->parent_tid(),
391         ThreadNameWithParenthesis(summary->parent_tid(),
392                                   tname, sizeof(tname)));
393  PrintStack(summary->stack());
394  // Recursively described parent thread if needed.
395  if (flags()->print_full_thread_history) {
396    AsanThreadSummary *parent_summary =
397        asanThreadRegistry().FindByTid(summary->parent_tid());
398    DescribeThread(parent_summary);
399  }
400}
401
402// -------------------- Different kinds of reports ----------------- {{{1
403
404// Use ScopedInErrorReport to run common actions just before and
405// immediately after printing error report.
406class ScopedInErrorReport {
407 public:
408  ScopedInErrorReport() {
409    static atomic_uint32_t num_calls;
410    static u32 reporting_thread_tid;
411    if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) {
412      // Do not print more than one report, otherwise they will mix up.
413      // Error reporting functions shouldn't return at this situation, as
414      // they are defined as no-return.
415      Report("AddressSanitizer: while reporting a bug found another one."
416                 "Ignoring.\n");
417      u32 current_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
418      if (current_tid != reporting_thread_tid) {
419        // ASan found two bugs in different threads simultaneously. Sleep
420        // long enough to make sure that the thread which started to print
421        // an error report will finish doing it.
422        SleepForSeconds(Max(100, flags()->sleep_before_dying + 1));
423      }
424      // If we're still not dead for some reason, use raw Exit() instead of
425      // Die() to bypass any additional checks.
426      Exit(flags()->exitcode);
427    }
428    ASAN_ON_ERROR();
429    reporting_thread_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
430    Printf("===================================================="
431           "=============\n");
432    if (reporting_thread_tid != kInvalidTid) {
433      // We started reporting an error message. Stop using the fake stack
434      // in case we call an instrumented function from a symbolizer.
435      AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
436      CHECK(curr_thread);
437      curr_thread->fake_stack().StopUsingFakeStack();
438    }
439  }
440  // Destructor is NORETURN, as functions that report errors are.
441  NORETURN ~ScopedInErrorReport() {
442    // Make sure the current thread is announced.
443    AsanThread *curr_thread = asanThreadRegistry().GetCurrent();
444    if (curr_thread) {
445      DescribeThread(curr_thread->summary());
446    }
447    // Print memory stats.
448    __asan_print_accumulated_stats();
449    if (error_report_callback) {
450      error_report_callback(error_message_buffer);
451    }
452    Report("ABORTING\n");
453    Die();
454  }
455};
456
457void ReportSIGSEGV(uptr pc, uptr sp, uptr bp, uptr addr) {
458  ScopedInErrorReport in_report;
459  Decorator d;
460  Printf("%s", d.Warning());
461  Report("ERROR: AddressSanitizer: SEGV on unknown address %p"
462             " (pc %p sp %p bp %p T%d)\n",
463             (void*)addr, (void*)pc, (void*)sp, (void*)bp,
464             asanThreadRegistry().GetCurrentTidOrInvalid());
465  Printf("%s", d.EndWarning());
466  Printf("AddressSanitizer can not provide additional info.\n");
467  GET_STACK_TRACE_FATAL(pc, bp);
468  PrintStack(&stack);
469}
470
471void ReportDoubleFree(uptr addr, StackTrace *stack) {
472  ScopedInErrorReport in_report;
473  Decorator d;
474  Printf("%s", d.Warning());
475  Report("ERROR: AddressSanitizer: attempting double-free on %p:\n", addr);
476  Printf("%s", d.EndWarning());
477  PrintStack(stack);
478  DescribeHeapAddress(addr, 1);
479}
480
481void ReportFreeNotMalloced(uptr addr, StackTrace *stack) {
482  ScopedInErrorReport in_report;
483  Decorator d;
484  Printf("%s", d.Warning());
485  Report("ERROR: AddressSanitizer: attempting free on address "
486             "which was not malloc()-ed: %p\n", addr);
487  Printf("%s", d.EndWarning());
488  PrintStack(stack);
489  DescribeHeapAddress(addr, 1);
490}
491
492void ReportMallocUsableSizeNotOwned(uptr addr, StackTrace *stack) {
493  ScopedInErrorReport in_report;
494  Decorator d;
495  Printf("%s", d.Warning());
496  Report("ERROR: AddressSanitizer: attempting to call "
497             "malloc_usable_size() for pointer which is "
498             "not owned: %p\n", addr);
499  Printf("%s", d.EndWarning());
500  PrintStack(stack);
501  DescribeHeapAddress(addr, 1);
502}
503
504void ReportAsanGetAllocatedSizeNotOwned(uptr addr, StackTrace *stack) {
505  ScopedInErrorReport in_report;
506  Decorator d;
507  Printf("%s", d.Warning());
508  Report("ERROR: AddressSanitizer: attempting to call "
509             "__asan_get_allocated_size() for pointer which is "
510             "not owned: %p\n", addr);
511  Printf("%s", d.EndWarning());
512  PrintStack(stack);
513  DescribeHeapAddress(addr, 1);
514}
515
516void ReportStringFunctionMemoryRangesOverlap(
517    const char *function, const char *offset1, uptr length1,
518    const char *offset2, uptr length2, StackTrace *stack) {
519  ScopedInErrorReport in_report;
520  Decorator d;
521  Printf("%s", d.Warning());
522  Report("ERROR: AddressSanitizer: %s-param-overlap: "
523             "memory ranges [%p,%p) and [%p, %p) overlap\n", \
524             function, offset1, offset1 + length1, offset2, offset2 + length2);
525  Printf("%s", d.EndWarning());
526  PrintStack(stack);
527  DescribeAddress((uptr)offset1, length1);
528  DescribeAddress((uptr)offset2, length2);
529}
530
531// ----------------------- Mac-specific reports ----------------- {{{1
532
533void WarnMacFreeUnallocated(
534    uptr addr, uptr zone_ptr, const char *zone_name, StackTrace *stack) {
535  // Just print a warning here.
536  Printf("free_common(%p) -- attempting to free unallocated memory.\n"
537             "AddressSanitizer is ignoring this error on Mac OS now.\n",
538             addr);
539  PrintZoneForPointer(addr, zone_ptr, zone_name);
540  PrintStack(stack);
541  DescribeHeapAddress(addr, 1);
542}
543
544void ReportMacMzReallocUnknown(
545    uptr addr, uptr zone_ptr, const char *zone_name, StackTrace *stack) {
546  ScopedInErrorReport in_report;
547  Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
548             "This is an unrecoverable problem, exiting now.\n",
549             addr);
550  PrintZoneForPointer(addr, zone_ptr, zone_name);
551  PrintStack(stack);
552  DescribeHeapAddress(addr, 1);
553}
554
555void ReportMacCfReallocUnknown(
556    uptr addr, uptr zone_ptr, const char *zone_name, StackTrace *stack) {
557  ScopedInErrorReport in_report;
558  Printf("cf_realloc(%p) -- attempting to realloc unallocated memory.\n"
559             "This is an unrecoverable problem, exiting now.\n",
560             addr);
561  PrintZoneForPointer(addr, zone_ptr, zone_name);
562  PrintStack(stack);
563  DescribeHeapAddress(addr, 1);
564}
565
566}  // namespace __asan
567
568// --------------------------- Interface --------------------- {{{1
569using namespace __asan;  // NOLINT
570
571void __asan_report_error(uptr pc, uptr bp, uptr sp,
572                         uptr addr, bool is_write, uptr access_size) {
573  ScopedInErrorReport in_report;
574
575  // Determine the error type.
576  const char *bug_descr = "unknown-crash";
577  if (AddrIsInMem(addr)) {
578    u8 *shadow_addr = (u8*)MemToShadow(addr);
579    // If we are accessing 16 bytes, look at the second shadow byte.
580    if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
581      shadow_addr++;
582    // If we are in the partial right redzone, look at the next shadow byte.
583    if (*shadow_addr > 0 && *shadow_addr < 128)
584      shadow_addr++;
585    switch (*shadow_addr) {
586      case kAsanHeapLeftRedzoneMagic:
587      case kAsanHeapRightRedzoneMagic:
588        bug_descr = "heap-buffer-overflow";
589        break;
590      case kAsanHeapFreeMagic:
591        bug_descr = "heap-use-after-free";
592        break;
593      case kAsanStackLeftRedzoneMagic:
594        bug_descr = "stack-buffer-underflow";
595        break;
596      case kAsanInitializationOrderMagic:
597        bug_descr = "initialization-order-fiasco";
598        break;
599      case kAsanStackMidRedzoneMagic:
600      case kAsanStackRightRedzoneMagic:
601      case kAsanStackPartialRedzoneMagic:
602        bug_descr = "stack-buffer-overflow";
603        break;
604      case kAsanStackAfterReturnMagic:
605        bug_descr = "stack-use-after-return";
606        break;
607      case kAsanUserPoisonedMemoryMagic:
608        bug_descr = "use-after-poison";
609        break;
610      case kAsanStackUseAfterScopeMagic:
611        bug_descr = "stack-use-after-scope";
612        break;
613      case kAsanGlobalRedzoneMagic:
614        bug_descr = "global-buffer-overflow";
615        break;
616    }
617  }
618  Decorator d;
619  Printf("%s", d.Warning());
620  Report("ERROR: AddressSanitizer: %s on address "
621             "%p at pc 0x%zx bp 0x%zx sp 0x%zx\n",
622             bug_descr, (void*)addr, pc, bp, sp);
623  Printf("%s", d.EndWarning());
624
625  u32 curr_tid = asanThreadRegistry().GetCurrentTidOrInvalid();
626  char tname[128];
627  Printf("%s%s of size %zu at %p thread T%d%s%s\n",
628         d.Access(),
629         access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
630         access_size, (void*)addr, curr_tid,
631         ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)),
632         d.EndAccess());
633
634  GET_STACK_TRACE_FATAL(pc, bp);
635  PrintStack(&stack);
636
637  DescribeAddress(addr, access_size);
638
639  PrintShadowMemoryForAddress(addr);
640}
641
642void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
643  error_report_callback = callback;
644  if (callback) {
645    error_message_buffer_size = 1 << 16;
646    error_message_buffer =
647        (char*)MmapOrDie(error_message_buffer_size, __FUNCTION__);
648    error_message_buffer_pos = 0;
649  }
650}
651
652#if !SANITIZER_SUPPORTS_WEAK_HOOKS
653// Provide default implementation of __asan_on_error that does nothing
654// and may be overriden by user.
655SANITIZER_WEAK_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE NOINLINE
656void __asan_on_error() {}
657#endif
658