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