]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_report.cc
Merge compiler-rt release_38 branch r258968.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_report.cc
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
15 #include "asan_flags.h"
16 #include "asan_internal.h"
17 #include "asan_mapping.h"
18 #include "asan_report.h"
19 #include "asan_stack.h"
20 #include "asan_thread.h"
21 #include "sanitizer_common/sanitizer_common.h"
22 #include "sanitizer_common/sanitizer_flags.h"
23 #include "sanitizer_common/sanitizer_report_decorator.h"
24 #include "sanitizer_common/sanitizer_stackdepot.h"
25 #include "sanitizer_common/sanitizer_symbolizer.h"
26
27 namespace __asan {
28
29 // -------------------- User-specified callbacks ----------------- {{{1
30 static void (*error_report_callback)(const char*);
31 static char *error_message_buffer = nullptr;
32 static uptr error_message_buffer_pos = 0;
33 static BlockingMutex error_message_buf_mutex(LINKER_INITIALIZED);
34 static const unsigned kAsanBuggyPcPoolSize = 25;
35 static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];
36
37 struct ReportData {
38   uptr pc;
39   uptr sp;
40   uptr bp;
41   uptr addr;
42   bool is_write;
43   uptr access_size;
44   const char *description;
45 };
46
47 static bool report_happened = false;
48 static ReportData report_data = {};
49
50 void AppendToErrorMessageBuffer(const char *buffer) {
51   BlockingMutexLock l(&error_message_buf_mutex);
52   if (!error_message_buffer) {
53     error_message_buffer =
54       (char*)MmapOrDieQuietly(kErrorMessageBufferSize, __func__);
55     error_message_buffer_pos = 0;
56   }
57   uptr length = internal_strlen(buffer);
58   RAW_CHECK(kErrorMessageBufferSize >= error_message_buffer_pos);
59   uptr remaining = kErrorMessageBufferSize - error_message_buffer_pos;
60   internal_strncpy(error_message_buffer + error_message_buffer_pos,
61                    buffer, remaining);
62   error_message_buffer[kErrorMessageBufferSize - 1] = '\0';
63   // FIXME: reallocate the buffer instead of truncating the message.
64   error_message_buffer_pos += Min(remaining, length);
65 }
66
67 // ---------------------- Decorator ------------------------------ {{{1
68 class Decorator: public __sanitizer::SanitizerCommonDecorator {
69  public:
70   Decorator() : SanitizerCommonDecorator() { }
71   const char *Access()     { return Blue(); }
72   const char *EndAccess()  { return Default(); }
73   const char *Location()   { return Green(); }
74   const char *EndLocation() { return Default(); }
75   const char *Allocation()  { return Magenta(); }
76   const char *EndAllocation()  { return Default(); }
77
78   const char *ShadowByte(u8 byte) {
79     switch (byte) {
80       case kAsanHeapLeftRedzoneMagic:
81       case kAsanHeapRightRedzoneMagic:
82       case kAsanArrayCookieMagic:
83         return Red();
84       case kAsanHeapFreeMagic:
85         return Magenta();
86       case kAsanStackLeftRedzoneMagic:
87       case kAsanStackMidRedzoneMagic:
88       case kAsanStackRightRedzoneMagic:
89       case kAsanStackPartialRedzoneMagic:
90         return Red();
91       case kAsanStackAfterReturnMagic:
92         return Magenta();
93       case kAsanInitializationOrderMagic:
94         return Cyan();
95       case kAsanUserPoisonedMemoryMagic:
96       case kAsanContiguousContainerOOBMagic:
97       case kAsanAllocaLeftMagic:
98       case kAsanAllocaRightMagic:
99         return Blue();
100       case kAsanStackUseAfterScopeMagic:
101         return Magenta();
102       case kAsanGlobalRedzoneMagic:
103         return Red();
104       case kAsanInternalHeapMagic:
105         return Yellow();
106       case kAsanIntraObjectRedzone:
107         return Yellow();
108       default:
109         return Default();
110     }
111   }
112   const char *EndShadowByte() { return Default(); }
113   const char *MemoryByte() { return Magenta(); }
114   const char *EndMemoryByte() { return Default(); }
115 };
116
117 // ---------------------- Helper functions ----------------------- {{{1
118
119 static void PrintMemoryByte(InternalScopedString *str, const char *before,
120     u8 byte, bool in_shadow, const char *after = "\n") {
121   Decorator d;
122   str->append("%s%s%x%x%s%s", before,
123               in_shadow ? d.ShadowByte(byte) : d.MemoryByte(),
124               byte >> 4, byte & 15,
125               in_shadow ? d.EndShadowByte() : d.EndMemoryByte(), after);
126 }
127
128 static void PrintShadowByte(InternalScopedString *str, const char *before,
129     u8 byte, const char *after = "\n") {
130   PrintMemoryByte(str, before, byte, /*in_shadow*/true, after);
131 }
132
133 static void PrintShadowBytes(InternalScopedString *str, const char *before,
134                              u8 *bytes, u8 *guilty, uptr n) {
135   Decorator d;
136   if (before) str->append("%s%p:", before, bytes);
137   for (uptr i = 0; i < n; i++) {
138     u8 *p = bytes + i;
139     const char *before =
140         p == guilty ? "[" : (p - 1 == guilty && i != 0) ? "" : " ";
141     const char *after = p == guilty ? "]" : "";
142     PrintShadowByte(str, before, *p, after);
143   }
144   str->append("\n");
145 }
146
147 static void PrintLegend(InternalScopedString *str) {
148   str->append(
149       "Shadow byte legend (one shadow byte represents %d "
150       "application bytes):\n",
151       (int)SHADOW_GRANULARITY);
152   PrintShadowByte(str, "  Addressable:           ", 0);
153   str->append("  Partially addressable: ");
154   for (u8 i = 1; i < SHADOW_GRANULARITY; i++) PrintShadowByte(str, "", i, " ");
155   str->append("\n");
156   PrintShadowByte(str, "  Heap left redzone:       ",
157                   kAsanHeapLeftRedzoneMagic);
158   PrintShadowByte(str, "  Heap right redzone:      ",
159                   kAsanHeapRightRedzoneMagic);
160   PrintShadowByte(str, "  Freed heap region:       ", kAsanHeapFreeMagic);
161   PrintShadowByte(str, "  Stack left redzone:      ",
162                   kAsanStackLeftRedzoneMagic);
163   PrintShadowByte(str, "  Stack mid redzone:       ",
164                   kAsanStackMidRedzoneMagic);
165   PrintShadowByte(str, "  Stack right redzone:     ",
166                   kAsanStackRightRedzoneMagic);
167   PrintShadowByte(str, "  Stack partial redzone:   ",
168                   kAsanStackPartialRedzoneMagic);
169   PrintShadowByte(str, "  Stack after return:      ",
170                   kAsanStackAfterReturnMagic);
171   PrintShadowByte(str, "  Stack use after scope:   ",
172                   kAsanStackUseAfterScopeMagic);
173   PrintShadowByte(str, "  Global redzone:          ", kAsanGlobalRedzoneMagic);
174   PrintShadowByte(str, "  Global init order:       ",
175                   kAsanInitializationOrderMagic);
176   PrintShadowByte(str, "  Poisoned by user:        ",
177                   kAsanUserPoisonedMemoryMagic);
178   PrintShadowByte(str, "  Container overflow:      ",
179                   kAsanContiguousContainerOOBMagic);
180   PrintShadowByte(str, "  Array cookie:            ",
181                   kAsanArrayCookieMagic);
182   PrintShadowByte(str, "  Intra object redzone:    ",
183                   kAsanIntraObjectRedzone);
184   PrintShadowByte(str, "  ASan internal:           ", kAsanInternalHeapMagic);
185   PrintShadowByte(str, "  Left alloca redzone:     ", kAsanAllocaLeftMagic);
186   PrintShadowByte(str, "  Right alloca redzone:    ", kAsanAllocaRightMagic);
187 }
188
189 void MaybeDumpInstructionBytes(uptr pc) {
190   if (!flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
191     return;
192   InternalScopedString str(1024);
193   str.append("First 16 instruction bytes at pc: ");
194   if (IsAccessibleMemoryRange(pc, 16)) {
195     for (int i = 0; i < 16; ++i) {
196       PrintMemoryByte(&str, "", ((u8 *)pc)[i], /*in_shadow*/false, " ");
197     }
198     str.append("\n");
199   } else {
200     str.append("unaccessible\n");
201   }
202   Report("%s", str.data());
203 }
204
205 static void PrintShadowMemoryForAddress(uptr addr) {
206   if (!AddrIsInMem(addr)) return;
207   uptr shadow_addr = MemToShadow(addr);
208   const uptr n_bytes_per_row = 16;
209   uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1);
210   InternalScopedString str(4096 * 8);
211   str.append("Shadow bytes around the buggy address:\n");
212   for (int i = -5; i <= 5; i++) {
213     const char *prefix = (i == 0) ? "=>" : "  ";
214     PrintShadowBytes(&str, prefix, (u8 *)(aligned_shadow + i * n_bytes_per_row),
215                      (u8 *)shadow_addr, n_bytes_per_row);
216   }
217   if (flags()->print_legend) PrintLegend(&str);
218   Printf("%s", str.data());
219 }
220
221 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
222                                 const char *zone_name) {
223   if (zone_ptr) {
224     if (zone_name) {
225       Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
226                  ptr, zone_ptr, zone_name);
227     } else {
228       Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
229                  ptr, zone_ptr);
230     }
231   } else {
232     Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
233   }
234 }
235
236 static void DescribeThread(AsanThread *t) {
237   if (t)
238     DescribeThread(t->context());
239 }
240
241 // ---------------------- Address Descriptions ------------------- {{{1
242
243 static bool IsASCII(unsigned char c) {
244   return /*0x00 <= c &&*/ c <= 0x7F;
245 }
246
247 static const char *MaybeDemangleGlobalName(const char *name) {
248   // We can spoil names of globals with C linkage, so use an heuristic
249   // approach to check if the name should be demangled.
250   bool should_demangle = false;
251   if (name[0] == '_' && name[1] == 'Z')
252     should_demangle = true;
253   else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?')
254     should_demangle = true;
255
256   return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name;
257 }
258
259 // Check if the global is a zero-terminated ASCII string. If so, print it.
260 static void PrintGlobalNameIfASCII(InternalScopedString *str,
261                                    const __asan_global &g) {
262   for (uptr p = g.beg; p < g.beg + g.size - 1; p++) {
263     unsigned char c = *(unsigned char*)p;
264     if (c == '\0' || !IsASCII(c)) return;
265   }
266   if (*(char*)(g.beg + g.size - 1) != '\0') return;
267   str->append("  '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name),
268               (char *)g.beg);
269 }
270
271 static const char *GlobalFilename(const __asan_global &g) {
272   const char *res = g.module_name;
273   // Prefer the filename from source location, if is available.
274   if (g.location)
275     res = g.location->filename;
276   CHECK(res);
277   return res;
278 }
279
280 static void PrintGlobalLocation(InternalScopedString *str,
281                                 const __asan_global &g) {
282   str->append("%s", GlobalFilename(g));
283   if (!g.location)
284     return;
285   if (g.location->line_no)
286     str->append(":%d", g.location->line_no);
287   if (g.location->column_no)
288     str->append(":%d", g.location->column_no);
289 }
290
291 static void DescribeAddressRelativeToGlobal(uptr addr, uptr size,
292                                             const __asan_global &g) {
293   InternalScopedString str(4096);
294   Decorator d;
295   str.append("%s", d.Location());
296   if (addr < g.beg) {
297     str.append("%p is located %zd bytes to the left", (void *)addr,
298                g.beg - addr);
299   } else if (addr + size > g.beg + g.size) {
300     if (addr < g.beg + g.size)
301       addr = g.beg + g.size;
302     str.append("%p is located %zd bytes to the right", (void *)addr,
303                addr - (g.beg + g.size));
304   } else {
305     // Can it happen?
306     str.append("%p is located %zd bytes inside", (void *)addr, addr - g.beg);
307   }
308   str.append(" of global variable '%s' defined in '",
309              MaybeDemangleGlobalName(g.name));
310   PrintGlobalLocation(&str, g);
311   str.append("' (0x%zx) of size %zu\n", g.beg, g.size);
312   str.append("%s", d.EndLocation());
313   PrintGlobalNameIfASCII(&str, g);
314   Printf("%s", str.data());
315 }
316
317 static bool DescribeAddressIfGlobal(uptr addr, uptr size,
318                                     const char *bug_type) {
319   // Assume address is close to at most four globals.
320   const int kMaxGlobalsInReport = 4;
321   __asan_global globals[kMaxGlobalsInReport];
322   u32 reg_sites[kMaxGlobalsInReport];
323   int globals_num =
324       GetGlobalsForAddress(addr, globals, reg_sites, ARRAY_SIZE(globals));
325   if (globals_num == 0)
326     return false;
327   for (int i = 0; i < globals_num; i++) {
328     DescribeAddressRelativeToGlobal(addr, size, globals[i]);
329     if (0 == internal_strcmp(bug_type, "initialization-order-fiasco") &&
330         reg_sites[i]) {
331       Printf("  registered at:\n");
332       StackDepotGet(reg_sites[i]).Print();
333     }
334   }
335   return true;
336 }
337
338 bool DescribeAddressIfShadow(uptr addr, AddressDescription *descr, bool print) {
339   if (AddrIsInMem(addr))
340     return false;
341   const char *area_type = nullptr;
342   if (AddrIsInShadowGap(addr)) area_type = "shadow gap";
343   else if (AddrIsInHighShadow(addr)) area_type = "high shadow";
344   else if (AddrIsInLowShadow(addr)) area_type = "low shadow";
345   if (area_type != nullptr) {
346     if (print) {
347       Printf("Address %p is located in the %s area.\n", addr, area_type);
348     } else {
349       CHECK(descr);
350       descr->region_kind = area_type;
351     }
352     return true;
353   }
354   CHECK(0 && "Address is not in memory and not in shadow?");
355   return false;
356 }
357
358 // Return " (thread_name) " or an empty string if the name is empty.
359 const char *ThreadNameWithParenthesis(AsanThreadContext *t, char buff[],
360                                       uptr buff_len) {
361   const char *name = t->name;
362   if (name[0] == '\0') return "";
363   buff[0] = 0;
364   internal_strncat(buff, " (", 3);
365   internal_strncat(buff, name, buff_len - 4);
366   internal_strncat(buff, ")", 2);
367   return buff;
368 }
369
370 const char *ThreadNameWithParenthesis(u32 tid, char buff[],
371                                       uptr buff_len) {
372   if (tid == kInvalidTid) return "";
373   asanThreadRegistry().CheckLocked();
374   AsanThreadContext *t = GetThreadContextByTidLocked(tid);
375   return ThreadNameWithParenthesis(t, buff, buff_len);
376 }
377
378 static void PrintAccessAndVarIntersection(const StackVarDescr &var, uptr addr,
379                                           uptr access_size, uptr prev_var_end,
380                                           uptr next_var_beg) {
381   uptr var_end = var.beg + var.size;
382   uptr addr_end = addr + access_size;
383   const char *pos_descr = nullptr;
384   // If the variable [var.beg, var_end) is the nearest variable to the
385   // current memory access, indicate it in the log.
386   if (addr >= var.beg) {
387     if (addr_end <= var_end)
388       pos_descr = "is inside";  // May happen if this is a use-after-return.
389     else if (addr < var_end)
390       pos_descr = "partially overflows";
391     else if (addr_end <= next_var_beg &&
392              next_var_beg - addr_end >= addr - var_end)
393       pos_descr = "overflows";
394   } else {
395     if (addr_end > var.beg)
396       pos_descr = "partially underflows";
397     else if (addr >= prev_var_end &&
398              addr - prev_var_end >= var.beg - addr_end)
399       pos_descr = "underflows";
400   }
401   InternalScopedString str(1024);
402   str.append("    [%zd, %zd)", var.beg, var_end);
403   // Render variable name.
404   str.append(" '");
405   for (uptr i = 0; i < var.name_len; ++i) {
406     str.append("%c", var.name_pos[i]);
407   }
408   str.append("'");
409   if (pos_descr) {
410     Decorator d;
411     // FIXME: we may want to also print the size of the access here,
412     // but in case of accesses generated by memset it may be confusing.
413     str.append("%s <== Memory access at offset %zd %s this variable%s\n",
414                d.Location(), addr, pos_descr, d.EndLocation());
415   } else {
416     str.append("\n");
417   }
418   Printf("%s", str.data());
419 }
420
421 bool ParseFrameDescription(const char *frame_descr,
422                            InternalMmapVector<StackVarDescr> *vars) {
423   CHECK(frame_descr);
424   char *p;
425   // This string is created by the compiler and has the following form:
426   // "n alloc_1 alloc_2 ... alloc_n"
427   // where alloc_i looks like "offset size len ObjectName".
428   uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
429   if (n_objects == 0)
430     return false;
431
432   for (uptr i = 0; i < n_objects; i++) {
433     uptr beg  = (uptr)internal_simple_strtoll(p, &p, 10);
434     uptr size = (uptr)internal_simple_strtoll(p, &p, 10);
435     uptr len  = (uptr)internal_simple_strtoll(p, &p, 10);
436     if (beg == 0 || size == 0 || *p != ' ') {
437       return false;
438     }
439     p++;
440     StackVarDescr var = {beg, size, p, len};
441     vars->push_back(var);
442     p += len;
443   }
444
445   return true;
446 }
447
448 bool DescribeAddressIfStack(uptr addr, uptr access_size) {
449   AsanThread *t = FindThreadByStackAddress(addr);
450   if (!t) return false;
451
452   Decorator d;
453   char tname[128];
454   Printf("%s", d.Location());
455   Printf("Address %p is located in stack of thread T%d%s", addr, t->tid(),
456          ThreadNameWithParenthesis(t->tid(), tname, sizeof(tname)));
457
458   // Try to fetch precise stack frame for this access.
459   AsanThread::StackFrameAccess access;
460   if (!t->GetStackFrameAccessByAddr(addr, &access)) {
461     Printf("%s\n", d.EndLocation());
462     return true;
463   }
464   Printf(" at offset %zu in frame%s\n", access.offset, d.EndLocation());
465
466   // Now we print the frame where the alloca has happened.
467   // We print this frame as a stack trace with one element.
468   // The symbolizer may print more than one frame if inlining was involved.
469   // The frame numbers may be different than those in the stack trace printed
470   // previously. That's unfortunate, but I have no better solution,
471   // especially given that the alloca may be from entirely different place
472   // (e.g. use-after-scope, or different thread's stack).
473 #if defined(__powerpc64__) && defined(__BIG_ENDIAN__)
474   // On PowerPC64 ELFv1, the address of a function actually points to a
475   // three-doubleword data structure with the first field containing
476   // the address of the function's code.
477   access.frame_pc = *reinterpret_cast<uptr *>(access.frame_pc);
478 #endif
479   access.frame_pc += 16;
480   Printf("%s", d.EndLocation());
481   StackTrace alloca_stack(&access.frame_pc, 1);
482   alloca_stack.Print();
483
484   InternalMmapVector<StackVarDescr> vars(16);
485   if (!ParseFrameDescription(access.frame_descr, &vars)) {
486     Printf("AddressSanitizer can't parse the stack frame "
487            "descriptor: |%s|\n", access.frame_descr);
488     // 'addr' is a stack address, so return true even if we can't parse frame
489     return true;
490   }
491   uptr n_objects = vars.size();
492   // Report the number of stack objects.
493   Printf("  This frame has %zu object(s):\n", n_objects);
494
495   // Report all objects in this frame.
496   for (uptr i = 0; i < n_objects; i++) {
497     uptr prev_var_end = i ? vars[i - 1].beg + vars[i - 1].size : 0;
498     uptr next_var_beg = i + 1 < n_objects ? vars[i + 1].beg : ~(0UL);
499     PrintAccessAndVarIntersection(vars[i], access.offset, access_size,
500                                   prev_var_end, next_var_beg);
501   }
502   Printf("HINT: this may be a false positive if your program uses "
503          "some custom stack unwind mechanism or swapcontext\n");
504   if (SANITIZER_WINDOWS)
505     Printf("      (longjmp, SEH and C++ exceptions *are* supported)\n");
506   else
507     Printf("      (longjmp and C++ exceptions *are* supported)\n");
508
509   DescribeThread(t);
510   return true;
511 }
512
513 static void DescribeAccessToHeapChunk(AsanChunkView chunk, uptr addr,
514                                       uptr access_size) {
515   sptr offset;
516   Decorator d;
517   InternalScopedString str(4096);
518   str.append("%s", d.Location());
519   if (chunk.AddrIsAtLeft(addr, access_size, &offset)) {
520     str.append("%p is located %zd bytes to the left of", (void *)addr, offset);
521   } else if (chunk.AddrIsAtRight(addr, access_size, &offset)) {
522     if (offset < 0) {
523       addr -= offset;
524       offset = 0;
525     }
526     str.append("%p is located %zd bytes to the right of", (void *)addr, offset);
527   } else if (chunk.AddrIsInside(addr, access_size, &offset)) {
528     str.append("%p is located %zd bytes inside of", (void*)addr, offset);
529   } else {
530     str.append("%p is located somewhere around (this is AddressSanitizer bug!)",
531                (void *)addr);
532   }
533   str.append(" %zu-byte region [%p,%p)\n", chunk.UsedSize(),
534              (void *)(chunk.Beg()), (void *)(chunk.End()));
535   str.append("%s", d.EndLocation());
536   Printf("%s", str.data());
537 }
538
539 void DescribeHeapAddress(uptr addr, uptr access_size) {
540   AsanChunkView chunk = FindHeapChunkByAddress(addr);
541   if (!chunk.IsValid()) {
542     Printf("AddressSanitizer can not describe address in more detail "
543            "(wild memory access suspected).\n");
544     return;
545   }
546   DescribeAccessToHeapChunk(chunk, addr, access_size);
547   CHECK(chunk.AllocTid() != kInvalidTid);
548   asanThreadRegistry().CheckLocked();
549   AsanThreadContext *alloc_thread =
550       GetThreadContextByTidLocked(chunk.AllocTid());
551   StackTrace alloc_stack = chunk.GetAllocStack();
552   char tname[128];
553   Decorator d;
554   AsanThreadContext *free_thread = nullptr;
555   if (chunk.FreeTid() != kInvalidTid) {
556     free_thread = GetThreadContextByTidLocked(chunk.FreeTid());
557     Printf("%sfreed by thread T%d%s here:%s\n", d.Allocation(),
558            free_thread->tid,
559            ThreadNameWithParenthesis(free_thread, tname, sizeof(tname)),
560            d.EndAllocation());
561     StackTrace free_stack = chunk.GetFreeStack();
562     free_stack.Print();
563     Printf("%spreviously allocated by thread T%d%s here:%s\n",
564            d.Allocation(), alloc_thread->tid,
565            ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
566            d.EndAllocation());
567   } else {
568     Printf("%sallocated by thread T%d%s here:%s\n", d.Allocation(),
569            alloc_thread->tid,
570            ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)),
571            d.EndAllocation());
572   }
573   alloc_stack.Print();
574   DescribeThread(GetCurrentThread());
575   if (free_thread)
576     DescribeThread(free_thread);
577   DescribeThread(alloc_thread);
578 }
579
580 static void DescribeAddress(uptr addr, uptr access_size, const char *bug_type) {
581   // Check if this is shadow or shadow gap.
582   if (DescribeAddressIfShadow(addr))
583     return;
584   CHECK(AddrIsInMem(addr));
585   if (DescribeAddressIfGlobal(addr, access_size, bug_type))
586     return;
587   if (DescribeAddressIfStack(addr, access_size))
588     return;
589   // Assume it is a heap address.
590   DescribeHeapAddress(addr, access_size);
591 }
592
593 // ------------------- Thread description -------------------- {{{1
594
595 void DescribeThread(AsanThreadContext *context) {
596   CHECK(context);
597   asanThreadRegistry().CheckLocked();
598   // No need to announce the main thread.
599   if (context->tid == 0 || context->announced) {
600     return;
601   }
602   context->announced = true;
603   char tname[128];
604   InternalScopedString str(1024);
605   str.append("Thread T%d%s", context->tid,
606              ThreadNameWithParenthesis(context->tid, tname, sizeof(tname)));
607   if (context->parent_tid == kInvalidTid) {
608     str.append(" created by unknown thread\n");
609     Printf("%s", str.data());
610     return;
611   }
612   str.append(
613       " created by T%d%s here:\n", context->parent_tid,
614       ThreadNameWithParenthesis(context->parent_tid, tname, sizeof(tname)));
615   Printf("%s", str.data());
616   StackDepotGet(context->stack_id).Print();
617   // Recursively described parent thread if needed.
618   if (flags()->print_full_thread_history) {
619     AsanThreadContext *parent_context =
620         GetThreadContextByTidLocked(context->parent_tid);
621     DescribeThread(parent_context);
622   }
623 }
624
625 // -------------------- Different kinds of reports ----------------- {{{1
626
627 // Use ScopedInErrorReport to run common actions just before and
628 // immediately after printing error report.
629 class ScopedInErrorReport {
630  public:
631   explicit ScopedInErrorReport(ReportData *report = nullptr,
632                                bool fatal = false) {
633     halt_on_error_ = fatal || flags()->halt_on_error;
634
635     if (lock_.TryLock()) {
636       StartReporting(report);
637       return;
638     }
639
640     // ASan found two bugs in different threads simultaneously.
641
642     u32 current_tid = GetCurrentTidOrInvalid();
643     if (reporting_thread_tid_ == current_tid ||
644         reporting_thread_tid_ == kInvalidTid) {
645       // This is either asynch signal or nested error during error reporting.
646       // Fail simple to avoid deadlocks in Report().
647
648       // Can't use Report() here because of potential deadlocks
649       // in nested signal handlers.
650       const char msg[] = "AddressSanitizer: nested bug in the same thread, "
651                          "aborting.\n";
652       WriteToFile(kStderrFd, msg, sizeof(msg));
653
654       internal__exit(common_flags()->exitcode);
655     }
656
657     if (halt_on_error_) {
658       // Do not print more than one report, otherwise they will mix up.
659       // Error reporting functions shouldn't return at this situation, as
660       // they are effectively no-returns.
661
662       Report("AddressSanitizer: while reporting a bug found another one. "
663              "Ignoring.\n");
664
665       // Sleep long enough to make sure that the thread which started
666       // to print an error report will finish doing it.
667       SleepForSeconds(Max(100, flags()->sleep_before_dying + 1));
668
669       // If we're still not dead for some reason, use raw _exit() instead of
670       // Die() to bypass any additional checks.
671       internal__exit(common_flags()->exitcode);
672     } else {
673       // The other thread will eventually finish reporting
674       // so it's safe to wait
675       lock_.Lock();
676     }
677
678     StartReporting(report);
679   }
680
681   ~ScopedInErrorReport() {
682     // Make sure the current thread is announced.
683     DescribeThread(GetCurrentThread());
684     // We may want to grab this lock again when printing stats.
685     asanThreadRegistry().Unlock();
686     // Print memory stats.
687     if (flags()->print_stats)
688       __asan_print_accumulated_stats();
689
690     // Copy the message buffer so that we could start logging without holding a
691     // lock that gets aquired during printing.
692     InternalScopedBuffer<char> buffer_copy(kErrorMessageBufferSize);
693     {
694       BlockingMutexLock l(&error_message_buf_mutex);
695       internal_memcpy(buffer_copy.data(),
696                       error_message_buffer, kErrorMessageBufferSize);
697     }
698
699     LogFullErrorReport(buffer_copy.data());
700
701     if (error_report_callback) {
702       error_report_callback(buffer_copy.data());
703     }
704     CommonSanitizerReportMutex.Unlock();
705     reporting_thread_tid_ = kInvalidTid;
706     lock_.Unlock();
707     if (halt_on_error_) {
708       Report("ABORTING\n");
709       Die();
710     }
711   }
712
713  private:
714   void StartReporting(ReportData *report) {
715     if (report) report_data = *report;
716     report_happened = true;
717     ASAN_ON_ERROR();
718     // Make sure the registry and sanitizer report mutexes are locked while
719     // we're printing an error report.
720     // We can lock them only here to avoid self-deadlock in case of
721     // recursive reports.
722     asanThreadRegistry().Lock();
723     CommonSanitizerReportMutex.Lock();
724     reporting_thread_tid_ = GetCurrentTidOrInvalid();
725     Printf("===================================================="
726            "=============\n");
727   }
728
729   static StaticSpinMutex lock_;
730   static u32 reporting_thread_tid_;
731   bool halt_on_error_;
732 };
733
734 StaticSpinMutex ScopedInErrorReport::lock_;
735 u32 ScopedInErrorReport::reporting_thread_tid_;
736
737 void ReportStackOverflow(const SignalContext &sig) {
738   ScopedInErrorReport in_report;
739   Decorator d;
740   Printf("%s", d.Warning());
741   Report(
742       "ERROR: AddressSanitizer: stack-overflow on address %p"
743       " (pc %p bp %p sp %p T%d)\n",
744       (void *)sig.addr, (void *)sig.pc, (void *)sig.bp, (void *)sig.sp,
745       GetCurrentTidOrInvalid());
746   Printf("%s", d.EndWarning());
747   GET_STACK_TRACE_SIGNAL(sig);
748   stack.Print();
749   ReportErrorSummary("stack-overflow", &stack);
750 }
751
752 void ReportDeadlySignal(const char *description, const SignalContext &sig) {
753   ScopedInErrorReport in_report(/*report*/nullptr, /*fatal*/true);
754   Decorator d;
755   Printf("%s", d.Warning());
756   Report(
757       "ERROR: AddressSanitizer: %s on unknown address %p"
758       " (pc %p bp %p sp %p T%d)\n",
759       description, (void *)sig.addr, (void *)sig.pc, (void *)sig.bp,
760       (void *)sig.sp, GetCurrentTidOrInvalid());
761   if (sig.pc < GetPageSizeCached()) {
762     Report("Hint: pc points to the zero page.\n");
763   }
764   Printf("%s", d.EndWarning());
765   GET_STACK_TRACE_SIGNAL(sig);
766   stack.Print();
767   MaybeDumpInstructionBytes(sig.pc);
768   Printf("AddressSanitizer can not provide additional info.\n");
769   ReportErrorSummary(description, &stack);
770 }
771
772 void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {
773   ScopedInErrorReport in_report;
774   Decorator d;
775   Printf("%s", d.Warning());
776   char tname[128];
777   u32 curr_tid = GetCurrentTidOrInvalid();
778   Report("ERROR: AddressSanitizer: attempting double-free on %p in "
779          "thread T%d%s:\n",
780          addr, curr_tid,
781          ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
782   Printf("%s", d.EndWarning());
783   CHECK_GT(free_stack->size, 0);
784   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
785   stack.Print();
786   DescribeHeapAddress(addr, 1);
787   ReportErrorSummary("double-free", &stack);
788 }
789
790 void ReportNewDeleteSizeMismatch(uptr addr, uptr delete_size,
791                                  BufferedStackTrace *free_stack) {
792   ScopedInErrorReport in_report;
793   Decorator d;
794   Printf("%s", d.Warning());
795   char tname[128];
796   u32 curr_tid = GetCurrentTidOrInvalid();
797   Report("ERROR: AddressSanitizer: new-delete-type-mismatch on %p in "
798          "thread T%d%s:\n",
799          addr, curr_tid,
800          ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
801   Printf("%s  object passed to delete has wrong type:\n", d.EndWarning());
802   Printf("  size of the allocated type:   %zd bytes;\n"
803          "  size of the deallocated type: %zd bytes.\n",
804          asan_mz_size(reinterpret_cast<void*>(addr)), delete_size);
805   CHECK_GT(free_stack->size, 0);
806   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
807   stack.Print();
808   DescribeHeapAddress(addr, 1);
809   ReportErrorSummary("new-delete-type-mismatch", &stack);
810   Report("HINT: if you don't care about these errors you may set "
811          "ASAN_OPTIONS=new_delete_type_mismatch=0\n");
812 }
813
814 void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {
815   ScopedInErrorReport in_report;
816   Decorator d;
817   Printf("%s", d.Warning());
818   char tname[128];
819   u32 curr_tid = GetCurrentTidOrInvalid();
820   Report("ERROR: AddressSanitizer: attempting free on address "
821              "which was not malloc()-ed: %p in thread T%d%s\n", addr,
822          curr_tid, ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)));
823   Printf("%s", d.EndWarning());
824   CHECK_GT(free_stack->size, 0);
825   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
826   stack.Print();
827   DescribeHeapAddress(addr, 1);
828   ReportErrorSummary("bad-free", &stack);
829 }
830
831 void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,
832                              AllocType alloc_type,
833                              AllocType dealloc_type) {
834   static const char *alloc_names[] =
835     {"INVALID", "malloc", "operator new", "operator new []"};
836   static const char *dealloc_names[] =
837     {"INVALID", "free", "operator delete", "operator delete []"};
838   CHECK_NE(alloc_type, dealloc_type);
839   ScopedInErrorReport in_report;
840   Decorator d;
841   Printf("%s", d.Warning());
842   Report("ERROR: AddressSanitizer: alloc-dealloc-mismatch (%s vs %s) on %p\n",
843         alloc_names[alloc_type], dealloc_names[dealloc_type], addr);
844   Printf("%s", d.EndWarning());
845   CHECK_GT(free_stack->size, 0);
846   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
847   stack.Print();
848   DescribeHeapAddress(addr, 1);
849   ReportErrorSummary("alloc-dealloc-mismatch", &stack);
850   Report("HINT: if you don't care about these errors you may set "
851          "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n");
852 }
853
854 void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {
855   ScopedInErrorReport in_report;
856   Decorator d;
857   Printf("%s", d.Warning());
858   Report("ERROR: AddressSanitizer: attempting to call "
859              "malloc_usable_size() for pointer which is "
860              "not owned: %p\n", addr);
861   Printf("%s", d.EndWarning());
862   stack->Print();
863   DescribeHeapAddress(addr, 1);
864   ReportErrorSummary("bad-malloc_usable_size", stack);
865 }
866
867 void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,
868                                              BufferedStackTrace *stack) {
869   ScopedInErrorReport in_report;
870   Decorator d;
871   Printf("%s", d.Warning());
872   Report("ERROR: AddressSanitizer: attempting to call "
873              "__sanitizer_get_allocated_size() for pointer which is "
874              "not owned: %p\n", addr);
875   Printf("%s", d.EndWarning());
876   stack->Print();
877   DescribeHeapAddress(addr, 1);
878   ReportErrorSummary("bad-__sanitizer_get_allocated_size", stack);
879 }
880
881 void ReportStringFunctionMemoryRangesOverlap(const char *function,
882                                              const char *offset1, uptr length1,
883                                              const char *offset2, uptr length2,
884                                              BufferedStackTrace *stack) {
885   ScopedInErrorReport in_report;
886   Decorator d;
887   char bug_type[100];
888   internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function);
889   Printf("%s", d.Warning());
890   Report("ERROR: AddressSanitizer: %s: "
891              "memory ranges [%p,%p) and [%p, %p) overlap\n", \
892              bug_type, offset1, offset1 + length1, offset2, offset2 + length2);
893   Printf("%s", d.EndWarning());
894   stack->Print();
895   DescribeAddress((uptr)offset1, length1, bug_type);
896   DescribeAddress((uptr)offset2, length2, bug_type);
897   ReportErrorSummary(bug_type, stack);
898 }
899
900 void ReportStringFunctionSizeOverflow(uptr offset, uptr size,
901                                       BufferedStackTrace *stack) {
902   ScopedInErrorReport in_report;
903   Decorator d;
904   const char *bug_type = "negative-size-param";
905   Printf("%s", d.Warning());
906   Report("ERROR: AddressSanitizer: %s: (size=%zd)\n", bug_type, size);
907   Printf("%s", d.EndWarning());
908   stack->Print();
909   DescribeAddress(offset, size, bug_type);
910   ReportErrorSummary(bug_type, stack);
911 }
912
913 void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,
914                                                   uptr old_mid, uptr new_mid,
915                                                   BufferedStackTrace *stack) {
916   ScopedInErrorReport in_report;
917   Report("ERROR: AddressSanitizer: bad parameters to "
918          "__sanitizer_annotate_contiguous_container:\n"
919          "      beg     : %p\n"
920          "      end     : %p\n"
921          "      old_mid : %p\n"
922          "      new_mid : %p\n",
923          beg, end, old_mid, new_mid);
924   uptr granularity = SHADOW_GRANULARITY;
925   if (!IsAligned(beg, granularity))
926     Report("ERROR: beg is not aligned by %d\n", granularity);
927   stack->Print();
928   ReportErrorSummary("bad-__sanitizer_annotate_contiguous_container", stack);
929 }
930
931 void ReportODRViolation(const __asan_global *g1, u32 stack_id1,
932                         const __asan_global *g2, u32 stack_id2) {
933   ScopedInErrorReport in_report;
934   Decorator d;
935   Printf("%s", d.Warning());
936   Report("ERROR: AddressSanitizer: odr-violation (%p):\n", g1->beg);
937   Printf("%s", d.EndWarning());
938   InternalScopedString g1_loc(256), g2_loc(256);
939   PrintGlobalLocation(&g1_loc, *g1);
940   PrintGlobalLocation(&g2_loc, *g2);
941   Printf("  [1] size=%zd '%s' %s\n", g1->size,
942          MaybeDemangleGlobalName(g1->name), g1_loc.data());
943   Printf("  [2] size=%zd '%s' %s\n", g2->size,
944          MaybeDemangleGlobalName(g2->name), g2_loc.data());
945   if (stack_id1 && stack_id2) {
946     Printf("These globals were registered at these points:\n");
947     Printf("  [1]:\n");
948     StackDepotGet(stack_id1).Print();
949     Printf("  [2]:\n");
950     StackDepotGet(stack_id2).Print();
951   }
952   Report("HINT: if you don't care about these errors you may set "
953          "ASAN_OPTIONS=detect_odr_violation=0\n");
954   InternalScopedString error_msg(256);
955   error_msg.append("odr-violation: global '%s' at %s",
956                    MaybeDemangleGlobalName(g1->name), g1_loc.data());
957   ReportErrorSummary(error_msg.data());
958 }
959
960 // ----------------------- CheckForInvalidPointerPair ----------- {{{1
961 static NOINLINE void
962 ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp, uptr a1, uptr a2) {
963   ScopedInErrorReport in_report;
964   const char *bug_type = "invalid-pointer-pair";
965   Decorator d;
966   Printf("%s", d.Warning());
967   Report("ERROR: AddressSanitizer: invalid-pointer-pair: %p %p\n", a1, a2);
968   Printf("%s", d.EndWarning());
969   GET_STACK_TRACE_FATAL(pc, bp);
970   stack.Print();
971   DescribeAddress(a1, 1, bug_type);
972   DescribeAddress(a2, 1, bug_type);
973   ReportErrorSummary(bug_type, &stack);
974 }
975
976 static INLINE void CheckForInvalidPointerPair(void *p1, void *p2) {
977   if (!flags()->detect_invalid_pointer_pairs) return;
978   uptr a1 = reinterpret_cast<uptr>(p1);
979   uptr a2 = reinterpret_cast<uptr>(p2);
980   AsanChunkView chunk1 = FindHeapChunkByAddress(a1);
981   AsanChunkView chunk2 = FindHeapChunkByAddress(a2);
982   bool valid1 = chunk1.IsValid();
983   bool valid2 = chunk2.IsValid();
984   if ((valid1 != valid2) || (valid1 && valid2 && !chunk1.Eq(chunk2))) {
985     GET_CALLER_PC_BP_SP;                                              \
986     return ReportInvalidPointerPair(pc, bp, sp, a1, a2);
987   }
988 }
989 // ----------------------- Mac-specific reports ----------------- {{{1
990
991 void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,
992                                BufferedStackTrace *stack) {
993   ScopedInErrorReport in_report;
994   Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
995              "This is an unrecoverable problem, exiting now.\n",
996              addr);
997   PrintZoneForPointer(addr, zone_ptr, zone_name);
998   stack->Print();
999   DescribeHeapAddress(addr, 1);
1000 }
1001
1002 // -------------- SuppressErrorReport -------------- {{{1
1003 // Avoid error reports duplicating for ASan recover mode.
1004 static bool SuppressErrorReport(uptr pc) {
1005   if (!common_flags()->suppress_equal_pcs) return false;
1006   for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {
1007     uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);
1008     if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,
1009                                                    pc, memory_order_relaxed))
1010       return false;
1011     if (cmp == pc) return true;
1012   }
1013   Die();
1014 }
1015
1016 void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,
1017                         uptr access_size, u32 exp, bool fatal) {
1018   if (!fatal && SuppressErrorReport(pc)) return;
1019   ENABLE_FRAME_POINTER;
1020
1021   // Optimization experiments.
1022   // The experiments can be used to evaluate potential optimizations that remove
1023   // instrumentation (assess false negatives). Instead of completely removing
1024   // some instrumentation, compiler can emit special calls into runtime
1025   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass
1026   // mask of experiments (exp).
1027   // The reaction to a non-zero value of exp is to be defined.
1028   (void)exp;
1029
1030   // Determine the error type.
1031   const char *bug_descr = "unknown-crash";
1032   if (AddrIsInMem(addr)) {
1033     u8 *shadow_addr = (u8*)MemToShadow(addr);
1034     // If we are accessing 16 bytes, look at the second shadow byte.
1035     if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY)
1036       shadow_addr++;
1037     // If we are in the partial right redzone, look at the next shadow byte.
1038     if (*shadow_addr > 0 && *shadow_addr < 128)
1039       shadow_addr++;
1040     switch (*shadow_addr) {
1041       case kAsanHeapLeftRedzoneMagic:
1042       case kAsanHeapRightRedzoneMagic:
1043       case kAsanArrayCookieMagic:
1044         bug_descr = "heap-buffer-overflow";
1045         break;
1046       case kAsanHeapFreeMagic:
1047         bug_descr = "heap-use-after-free";
1048         break;
1049       case kAsanStackLeftRedzoneMagic:
1050         bug_descr = "stack-buffer-underflow";
1051         break;
1052       case kAsanInitializationOrderMagic:
1053         bug_descr = "initialization-order-fiasco";
1054         break;
1055       case kAsanStackMidRedzoneMagic:
1056       case kAsanStackRightRedzoneMagic:
1057       case kAsanStackPartialRedzoneMagic:
1058         bug_descr = "stack-buffer-overflow";
1059         break;
1060       case kAsanStackAfterReturnMagic:
1061         bug_descr = "stack-use-after-return";
1062         break;
1063       case kAsanUserPoisonedMemoryMagic:
1064         bug_descr = "use-after-poison";
1065         break;
1066       case kAsanContiguousContainerOOBMagic:
1067         bug_descr = "container-overflow";
1068         break;
1069       case kAsanStackUseAfterScopeMagic:
1070         bug_descr = "stack-use-after-scope";
1071         break;
1072       case kAsanGlobalRedzoneMagic:
1073         bug_descr = "global-buffer-overflow";
1074         break;
1075       case kAsanIntraObjectRedzone:
1076         bug_descr = "intra-object-overflow";
1077         break;
1078       case kAsanAllocaLeftMagic:
1079       case kAsanAllocaRightMagic:
1080         bug_descr = "dynamic-stack-buffer-overflow";
1081         break;
1082     }
1083   }
1084
1085   ReportData report = { pc, sp, bp, addr, (bool)is_write, access_size,
1086                         bug_descr };
1087   ScopedInErrorReport in_report(&report, fatal);
1088
1089   Decorator d;
1090   Printf("%s", d.Warning());
1091   Report("ERROR: AddressSanitizer: %s on address "
1092              "%p at pc %p bp %p sp %p\n",
1093              bug_descr, (void*)addr, pc, bp, sp);
1094   Printf("%s", d.EndWarning());
1095
1096   u32 curr_tid = GetCurrentTidOrInvalid();
1097   char tname[128];
1098   Printf("%s%s of size %zu at %p thread T%d%s%s\n",
1099          d.Access(),
1100          access_size ? (is_write ? "WRITE" : "READ") : "ACCESS",
1101          access_size, (void*)addr, curr_tid,
1102          ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)),
1103          d.EndAccess());
1104
1105   GET_STACK_TRACE_FATAL(pc, bp);
1106   stack.Print();
1107
1108   DescribeAddress(addr, access_size, bug_descr);
1109   ReportErrorSummary(bug_descr, &stack);
1110   PrintShadowMemoryForAddress(addr);
1111 }
1112
1113 }  // namespace __asan
1114
1115 // --------------------------- Interface --------------------- {{{1
1116 using namespace __asan;  // NOLINT
1117
1118 void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
1119                          uptr access_size, u32 exp) {
1120   ENABLE_FRAME_POINTER;
1121   bool fatal = flags()->halt_on_error;
1122   ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);
1123 }
1124
1125 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
1126   BlockingMutexLock l(&error_message_buf_mutex);
1127   error_report_callback = callback;
1128 }
1129
1130 void __asan_describe_address(uptr addr) {
1131   // Thread registry must be locked while we're describing an address.
1132   asanThreadRegistry().Lock();
1133   DescribeAddress(addr, 1, "");
1134   asanThreadRegistry().Unlock();
1135 }
1136
1137 int __asan_report_present() {
1138   return report_happened ? 1 : 0;
1139 }
1140
1141 uptr __asan_get_report_pc() {
1142   return report_data.pc;
1143 }
1144
1145 uptr __asan_get_report_bp() {
1146   return report_data.bp;
1147 }
1148
1149 uptr __asan_get_report_sp() {
1150   return report_data.sp;
1151 }
1152
1153 uptr __asan_get_report_address() {
1154   return report_data.addr;
1155 }
1156
1157 int __asan_get_report_access_type() {
1158   return report_data.is_write ? 1 : 0;
1159 }
1160
1161 uptr __asan_get_report_access_size() {
1162   return report_data.access_size;
1163 }
1164
1165 const char *__asan_get_report_description() {
1166   return report_data.description;
1167 }
1168
1169 extern "C" {
1170 SANITIZER_INTERFACE_ATTRIBUTE
1171 void __sanitizer_ptr_sub(void *a, void *b) {
1172   CheckForInvalidPointerPair(a, b);
1173 }
1174 SANITIZER_INTERFACE_ATTRIBUTE
1175 void __sanitizer_ptr_cmp(void *a, void *b) {
1176   CheckForInvalidPointerPair(a, b);
1177 }
1178 } // extern "C"
1179
1180 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
1181 // Provide default implementation of __asan_on_error that does nothing
1182 // and may be overriden by user.
1183 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE
1184 void __asan_on_error() {}
1185 #endif