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