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