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