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