1 //===-- asan_errors.cpp -----------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of AddressSanitizer, an address sanity checker.
10 //
11 // ASan implementation for error structures.
12 //===----------------------------------------------------------------------===//
13 
14 #include "asan_errors.h"
15 #include "asan_descriptions.h"
16 #include "asan_mapping.h"
17 #include "asan_report.h"
18 #include "asan_stack.h"
19 #include "sanitizer_common/sanitizer_stackdepot.h"
20 
21 namespace __asan {
22 
OnStackUnwind(const SignalContext & sig,const void * callback_context,BufferedStackTrace * stack)23 static void OnStackUnwind(const SignalContext &sig,
24                           const void *callback_context,
25                           BufferedStackTrace *stack) {
26   bool fast = common_flags()->fast_unwind_on_fatal;
27 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
28   // On FreeBSD the slow unwinding that leverages _Unwind_Backtrace()
29   // yields the call stack of the signal's handler and not of the code
30   // that raised the signal (as it does on Linux).
31   fast = true;
32 #endif
33   // Tests and maybe some users expect that scariness is going to be printed
34   // just before the stack. As only asan has scariness score we have no
35   // corresponding code in the sanitizer_common and we use this callback to
36   // print it.
37   static_cast<const ScarinessScoreBase *>(callback_context)->Print();
38   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
39                 fast);
40 }
41 
Print()42 void ErrorDeadlySignal::Print() {
43   ReportDeadlySignal(signal, tid, &OnStackUnwind, &scariness);
44 }
45 
Print()46 void ErrorDoubleFree::Print() {
47   Decorator d;
48   Printf("%s", d.Error());
49   Report(
50       "ERROR: AddressSanitizer: attempting %s on %p in thread %s:\n",
51       scariness.GetDescription(), addr_description.addr,
52       AsanThreadIdAndName(tid).c_str());
53   Printf("%s", d.Default());
54   scariness.Print();
55   GET_STACK_TRACE_FATAL(second_free_stack->trace[0],
56                         second_free_stack->top_frame_bp);
57   stack.Print();
58   addr_description.Print();
59   ReportErrorSummary(scariness.GetDescription(), &stack);
60 }
61 
Print()62 void ErrorNewDeleteTypeMismatch::Print() {
63   Decorator d;
64   Printf("%s", d.Error());
65   Report(
66       "ERROR: AddressSanitizer: %s on %p in thread %s:\n",
67       scariness.GetDescription(), addr_description.addr,
68       AsanThreadIdAndName(tid).c_str());
69   Printf("%s  object passed to delete has wrong type:\n", d.Default());
70   if (delete_size != 0) {
71     Printf(
72         "  size of the allocated type:   %zd bytes;\n"
73         "  size of the deallocated type: %zd bytes.\n",
74         addr_description.chunk_access.chunk_size, delete_size);
75   }
76   const uptr user_alignment =
77       addr_description.chunk_access.user_requested_alignment;
78   if (delete_alignment != user_alignment) {
79     char user_alignment_str[32];
80     char delete_alignment_str[32];
81     internal_snprintf(user_alignment_str, sizeof(user_alignment_str),
82                       "%zd bytes", user_alignment);
83     internal_snprintf(delete_alignment_str, sizeof(delete_alignment_str),
84                       "%zd bytes", delete_alignment);
85     static const char *kDefaultAlignment = "default-aligned";
86     Printf(
87         "  alignment of the allocated type:   %s;\n"
88         "  alignment of the deallocated type: %s.\n",
89         user_alignment > 0 ? user_alignment_str : kDefaultAlignment,
90         delete_alignment > 0 ? delete_alignment_str : kDefaultAlignment);
91   }
92   CHECK_GT(free_stack->size, 0);
93   scariness.Print();
94   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
95   stack.Print();
96   addr_description.Print();
97   ReportErrorSummary(scariness.GetDescription(), &stack);
98   Report(
99       "HINT: if you don't care about these errors you may set "
100       "ASAN_OPTIONS=new_delete_type_mismatch=0\n");
101 }
102 
Print()103 void ErrorFreeNotMalloced::Print() {
104   Decorator d;
105   Printf("%s", d.Error());
106   Report(
107       "ERROR: AddressSanitizer: attempting free on address "
108       "which was not malloc()-ed: %p in thread %s\n",
109       addr_description.Address(), AsanThreadIdAndName(tid).c_str());
110   Printf("%s", d.Default());
111   CHECK_GT(free_stack->size, 0);
112   scariness.Print();
113   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
114   stack.Print();
115   addr_description.Print();
116   ReportErrorSummary(scariness.GetDescription(), &stack);
117 }
118 
Print()119 void ErrorAllocTypeMismatch::Print() {
120   static const char *alloc_names[] = {"INVALID", "malloc", "operator new",
121                                       "operator new []"};
122   static const char *dealloc_names[] = {"INVALID", "free", "operator delete",
123                                         "operator delete []"};
124   CHECK_NE(alloc_type, dealloc_type);
125   Decorator d;
126   Printf("%s", d.Error());
127   Report("ERROR: AddressSanitizer: %s (%s vs %s) on %p\n",
128          scariness.GetDescription(), alloc_names[alloc_type],
129          dealloc_names[dealloc_type], addr_description.Address());
130   Printf("%s", d.Default());
131   CHECK_GT(dealloc_stack->size, 0);
132   scariness.Print();
133   GET_STACK_TRACE_FATAL(dealloc_stack->trace[0], dealloc_stack->top_frame_bp);
134   stack.Print();
135   addr_description.Print();
136   ReportErrorSummary(scariness.GetDescription(), &stack);
137   Report(
138       "HINT: if you don't care about these errors you may set "
139       "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n");
140 }
141 
Print()142 void ErrorMallocUsableSizeNotOwned::Print() {
143   Decorator d;
144   Printf("%s", d.Error());
145   Report(
146       "ERROR: AddressSanitizer: attempting to call malloc_usable_size() for "
147       "pointer which is not owned: %p\n",
148       addr_description.Address());
149   Printf("%s", d.Default());
150   stack->Print();
151   addr_description.Print();
152   ReportErrorSummary(scariness.GetDescription(), stack);
153 }
154 
Print()155 void ErrorSanitizerGetAllocatedSizeNotOwned::Print() {
156   Decorator d;
157   Printf("%s", d.Error());
158   Report(
159       "ERROR: AddressSanitizer: attempting to call "
160       "__sanitizer_get_allocated_size() for pointer which is not owned: %p\n",
161       addr_description.Address());
162   Printf("%s", d.Default());
163   stack->Print();
164   addr_description.Print();
165   ReportErrorSummary(scariness.GetDescription(), stack);
166 }
167 
Print()168 void ErrorCallocOverflow::Print() {
169   Decorator d;
170   Printf("%s", d.Error());
171   Report(
172       "ERROR: AddressSanitizer: calloc parameters overflow: count * size "
173       "(%zd * %zd) cannot be represented in type size_t (thread %s)\n",
174       count, size, AsanThreadIdAndName(tid).c_str());
175   Printf("%s", d.Default());
176   stack->Print();
177   PrintHintAllocatorCannotReturnNull();
178   ReportErrorSummary(scariness.GetDescription(), stack);
179 }
180 
Print()181 void ErrorReallocArrayOverflow::Print() {
182   Decorator d;
183   Printf("%s", d.Error());
184   Report(
185       "ERROR: AddressSanitizer: reallocarray parameters overflow: count * size "
186       "(%zd * %zd) cannot be represented in type size_t (thread %s)\n",
187       count, size, AsanThreadIdAndName(tid).c_str());
188   Printf("%s", d.Default());
189   stack->Print();
190   PrintHintAllocatorCannotReturnNull();
191   ReportErrorSummary(scariness.GetDescription(), stack);
192 }
193 
Print()194 void ErrorPvallocOverflow::Print() {
195   Decorator d;
196   Printf("%s", d.Error());
197   Report(
198       "ERROR: AddressSanitizer: pvalloc parameters overflow: size 0x%zx "
199       "rounded up to system page size 0x%zx cannot be represented in type "
200       "size_t (thread %s)\n",
201       size, GetPageSizeCached(), AsanThreadIdAndName(tid).c_str());
202   Printf("%s", d.Default());
203   stack->Print();
204   PrintHintAllocatorCannotReturnNull();
205   ReportErrorSummary(scariness.GetDescription(), stack);
206 }
207 
Print()208 void ErrorInvalidAllocationAlignment::Print() {
209   Decorator d;
210   Printf("%s", d.Error());
211   Report(
212       "ERROR: AddressSanitizer: invalid allocation alignment: %zd, "
213       "alignment must be a power of two (thread %s)\n",
214       alignment, AsanThreadIdAndName(tid).c_str());
215   Printf("%s", d.Default());
216   stack->Print();
217   PrintHintAllocatorCannotReturnNull();
218   ReportErrorSummary(scariness.GetDescription(), stack);
219 }
220 
Print()221 void ErrorInvalidAlignedAllocAlignment::Print() {
222   Decorator d;
223   Printf("%s", d.Error());
224 #if SANITIZER_POSIX
225   Report("ERROR: AddressSanitizer: invalid alignment requested in "
226          "aligned_alloc: %zd, alignment must be a power of two and the "
227          "requested size 0x%zx must be a multiple of alignment "
228          "(thread %s)\n", alignment, size, AsanThreadIdAndName(tid).c_str());
229 #else
230   Report("ERROR: AddressSanitizer: invalid alignment requested in "
231          "aligned_alloc: %zd, the requested size 0x%zx must be a multiple of "
232          "alignment (thread %s)\n", alignment, size,
233          AsanThreadIdAndName(tid).c_str());
234 #endif
235   Printf("%s", d.Default());
236   stack->Print();
237   PrintHintAllocatorCannotReturnNull();
238   ReportErrorSummary(scariness.GetDescription(), stack);
239 }
240 
Print()241 void ErrorInvalidPosixMemalignAlignment::Print() {
242   Decorator d;
243   Printf("%s", d.Error());
244   Report(
245       "ERROR: AddressSanitizer: invalid alignment requested in posix_memalign: "
246       "%zd, alignment must be a power of two and a multiple of sizeof(void*) "
247       "== %zd (thread %s)\n",
248       alignment, sizeof(void *), AsanThreadIdAndName(tid).c_str());
249   Printf("%s", d.Default());
250   stack->Print();
251   PrintHintAllocatorCannotReturnNull();
252   ReportErrorSummary(scariness.GetDescription(), stack);
253 }
254 
Print()255 void ErrorAllocationSizeTooBig::Print() {
256   Decorator d;
257   Printf("%s", d.Error());
258   Report(
259       "ERROR: AddressSanitizer: requested allocation size 0x%zx (0x%zx after "
260       "adjustments for alignment, red zones etc.) exceeds maximum supported "
261       "size of 0x%zx (thread %s)\n",
262       user_size, total_size, max_size, AsanThreadIdAndName(tid).c_str());
263   Printf("%s", d.Default());
264   stack->Print();
265   PrintHintAllocatorCannotReturnNull();
266   ReportErrorSummary(scariness.GetDescription(), stack);
267 }
268 
Print()269 void ErrorRssLimitExceeded::Print() {
270   Decorator d;
271   Printf("%s", d.Error());
272   Report(
273       "ERROR: AddressSanitizer: specified RSS limit exceeded, currently set to "
274       "soft_rss_limit_mb=%zd\n", common_flags()->soft_rss_limit_mb);
275   Printf("%s", d.Default());
276   stack->Print();
277   PrintHintAllocatorCannotReturnNull();
278   ReportErrorSummary(scariness.GetDescription(), stack);
279 }
280 
Print()281 void ErrorOutOfMemory::Print() {
282   Decorator d;
283   Printf("%s", d.Error());
284   Report(
285       "ERROR: AddressSanitizer: allocator is out of memory trying to allocate "
286       "0x%zx bytes\n", requested_size);
287   Printf("%s", d.Default());
288   stack->Print();
289   PrintHintAllocatorCannotReturnNull();
290   ReportErrorSummary(scariness.GetDescription(), stack);
291 }
292 
Print()293 void ErrorStringFunctionMemoryRangesOverlap::Print() {
294   Decorator d;
295   char bug_type[100];
296   internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function);
297   Printf("%s", d.Error());
298   Report(
299       "ERROR: AddressSanitizer: %s: memory ranges [%p,%p) and [%p, %p) "
300       "overlap\n",
301       bug_type, addr1_description.Address(),
302       addr1_description.Address() + length1, addr2_description.Address(),
303       addr2_description.Address() + length2);
304   Printf("%s", d.Default());
305   scariness.Print();
306   stack->Print();
307   addr1_description.Print();
308   addr2_description.Print();
309   ReportErrorSummary(bug_type, stack);
310 }
311 
Print()312 void ErrorStringFunctionSizeOverflow::Print() {
313   Decorator d;
314   Printf("%s", d.Error());
315   Report("ERROR: AddressSanitizer: %s: (size=%zd)\n",
316          scariness.GetDescription(), size);
317   Printf("%s", d.Default());
318   scariness.Print();
319   stack->Print();
320   addr_description.Print();
321   ReportErrorSummary(scariness.GetDescription(), stack);
322 }
323 
Print()324 void ErrorBadParamsToAnnotateContiguousContainer::Print() {
325   Report(
326       "ERROR: AddressSanitizer: bad parameters to "
327       "__sanitizer_annotate_contiguous_container:\n"
328       "      beg     : %p\n"
329       "      end     : %p\n"
330       "      old_mid : %p\n"
331       "      new_mid : %p\n",
332       beg, end, old_mid, new_mid);
333   uptr granularity = SHADOW_GRANULARITY;
334   if (!IsAligned(beg, granularity))
335     Report("ERROR: beg is not aligned by %d\n", granularity);
336   stack->Print();
337   ReportErrorSummary(scariness.GetDescription(), stack);
338 }
339 
Print()340 void ErrorODRViolation::Print() {
341   Decorator d;
342   Printf("%s", d.Error());
343   Report("ERROR: AddressSanitizer: %s (%p):\n", scariness.GetDescription(),
344          global1.beg);
345   Printf("%s", d.Default());
346   InternalScopedString g1_loc(256), g2_loc(256);
347   PrintGlobalLocation(&g1_loc, global1);
348   PrintGlobalLocation(&g2_loc, global2);
349   Printf("  [1] size=%zd '%s' %s\n", global1.size,
350          MaybeDemangleGlobalName(global1.name), g1_loc.data());
351   Printf("  [2] size=%zd '%s' %s\n", global2.size,
352          MaybeDemangleGlobalName(global2.name), g2_loc.data());
353   if (stack_id1 && stack_id2) {
354     Printf("These globals were registered at these points:\n");
355     Printf("  [1]:\n");
356     StackDepotGet(stack_id1).Print();
357     Printf("  [2]:\n");
358     StackDepotGet(stack_id2).Print();
359   }
360   Report(
361       "HINT: if you don't care about these errors you may set "
362       "ASAN_OPTIONS=detect_odr_violation=0\n");
363   InternalScopedString error_msg(256);
364   error_msg.append("%s: global '%s' at %s", scariness.GetDescription(),
365                    MaybeDemangleGlobalName(global1.name), g1_loc.data());
366   ReportErrorSummary(error_msg.data());
367 }
368 
Print()369 void ErrorInvalidPointerPair::Print() {
370   Decorator d;
371   Printf("%s", d.Error());
372   Report("ERROR: AddressSanitizer: %s: %p %p\n", scariness.GetDescription(),
373          addr1_description.Address(), addr2_description.Address());
374   Printf("%s", d.Default());
375   GET_STACK_TRACE_FATAL(pc, bp);
376   stack.Print();
377   addr1_description.Print();
378   addr2_description.Print();
379   ReportErrorSummary(scariness.GetDescription(), &stack);
380 }
381 
AdjacentShadowValuesAreFullyPoisoned(u8 * s)382 static bool AdjacentShadowValuesAreFullyPoisoned(u8 *s) {
383   return s[-1] > 127 && s[1] > 127;
384 }
385 
ErrorGeneric(u32 tid,uptr pc_,uptr bp_,uptr sp_,uptr addr,bool is_write_,uptr access_size_)386 ErrorGeneric::ErrorGeneric(u32 tid, uptr pc_, uptr bp_, uptr sp_, uptr addr,
387                            bool is_write_, uptr access_size_)
388     : ErrorBase(tid),
389       addr_description(addr, access_size_, /*shouldLockThreadRegistry=*/false),
390       pc(pc_),
391       bp(bp_),
392       sp(sp_),
393       access_size(access_size_),
394       is_write(is_write_),
395       shadow_val(0) {
396   scariness.Clear();
397   if (access_size) {
398     if (access_size <= 9) {
399       char desr[] = "?-byte";
400       desr[0] = '0' + access_size;
401       scariness.Scare(access_size + access_size / 2, desr);
402     } else if (access_size >= 10) {
403       scariness.Scare(15, "multi-byte");
404     }
405     is_write ? scariness.Scare(20, "write") : scariness.Scare(1, "read");
406 
407     // Determine the error type.
408     bug_descr = "unknown-crash";
409     if (AddrIsInMem(addr)) {
410       u8 *shadow_addr = (u8 *)MemToShadow(addr);
411       // If we are accessing 16 bytes, look at the second shadow byte.
412       if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY) shadow_addr++;
413       // If we are in the partial right redzone, look at the next shadow byte.
414       if (*shadow_addr > 0 && *shadow_addr < 128) shadow_addr++;
415       bool far_from_bounds = false;
416       shadow_val = *shadow_addr;
417       int bug_type_score = 0;
418       // For use-after-frees reads are almost as bad as writes.
419       int read_after_free_bonus = 0;
420       switch (shadow_val) {
421         case kAsanHeapLeftRedzoneMagic:
422         case kAsanArrayCookieMagic:
423           bug_descr = "heap-buffer-overflow";
424           bug_type_score = 10;
425           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
426           break;
427         case kAsanHeapFreeMagic:
428           bug_descr = "heap-use-after-free";
429           bug_type_score = 20;
430           if (!is_write) read_after_free_bonus = 18;
431           break;
432         case kAsanStackLeftRedzoneMagic:
433           bug_descr = "stack-buffer-underflow";
434           bug_type_score = 25;
435           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
436           break;
437         case kAsanInitializationOrderMagic:
438           bug_descr = "initialization-order-fiasco";
439           bug_type_score = 1;
440           break;
441         case kAsanStackMidRedzoneMagic:
442         case kAsanStackRightRedzoneMagic:
443           bug_descr = "stack-buffer-overflow";
444           bug_type_score = 25;
445           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
446           break;
447         case kAsanStackAfterReturnMagic:
448           bug_descr = "stack-use-after-return";
449           bug_type_score = 30;
450           if (!is_write) read_after_free_bonus = 18;
451           break;
452         case kAsanUserPoisonedMemoryMagic:
453           bug_descr = "use-after-poison";
454           bug_type_score = 20;
455           break;
456         case kAsanContiguousContainerOOBMagic:
457           bug_descr = "container-overflow";
458           bug_type_score = 10;
459           break;
460         case kAsanStackUseAfterScopeMagic:
461           bug_descr = "stack-use-after-scope";
462           bug_type_score = 10;
463           break;
464         case kAsanGlobalRedzoneMagic:
465           bug_descr = "global-buffer-overflow";
466           bug_type_score = 10;
467           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
468           break;
469         case kAsanIntraObjectRedzone:
470           bug_descr = "intra-object-overflow";
471           bug_type_score = 10;
472           break;
473         case kAsanAllocaLeftMagic:
474         case kAsanAllocaRightMagic:
475           bug_descr = "dynamic-stack-buffer-overflow";
476           bug_type_score = 25;
477           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
478           break;
479       }
480       scariness.Scare(bug_type_score + read_after_free_bonus, bug_descr);
481       if (far_from_bounds) scariness.Scare(10, "far-from-bounds");
482     }
483   }
484 }
485 
PrintContainerOverflowHint()486 static void PrintContainerOverflowHint() {
487   Printf("HINT: if you don't care about these errors you may set "
488          "ASAN_OPTIONS=detect_container_overflow=0.\n"
489          "If you suspect a false positive see also: "
490          "https://github.com/google/sanitizers/wiki/"
491          "AddressSanitizerContainerOverflow.\n");
492 }
493 
PrintShadowByte(InternalScopedString * str,const char * before,u8 byte,const char * after="\\n")494 static void PrintShadowByte(InternalScopedString *str, const char *before,
495     u8 byte, const char *after = "\n") {
496   PrintMemoryByte(str, before, byte, /*in_shadow*/true, after);
497 }
498 
PrintLegend(InternalScopedString * str)499 static void PrintLegend(InternalScopedString *str) {
500   str->append(
501       "Shadow byte legend (one shadow byte represents %d "
502       "application bytes):\n",
503       (int)SHADOW_GRANULARITY);
504   PrintShadowByte(str, "  Addressable:           ", 0);
505   str->append("  Partially addressable: ");
506   for (u8 i = 1; i < SHADOW_GRANULARITY; i++) PrintShadowByte(str, "", i, " ");
507   str->append("\n");
508   PrintShadowByte(str, "  Heap left redzone:       ",
509                   kAsanHeapLeftRedzoneMagic);
510   PrintShadowByte(str, "  Freed heap region:       ", kAsanHeapFreeMagic);
511   PrintShadowByte(str, "  Stack left redzone:      ",
512                   kAsanStackLeftRedzoneMagic);
513   PrintShadowByte(str, "  Stack mid redzone:       ",
514                   kAsanStackMidRedzoneMagic);
515   PrintShadowByte(str, "  Stack right redzone:     ",
516                   kAsanStackRightRedzoneMagic);
517   PrintShadowByte(str, "  Stack after return:      ",
518                   kAsanStackAfterReturnMagic);
519   PrintShadowByte(str, "  Stack use after scope:   ",
520                   kAsanStackUseAfterScopeMagic);
521   PrintShadowByte(str, "  Global redzone:          ", kAsanGlobalRedzoneMagic);
522   PrintShadowByte(str, "  Global init order:       ",
523                   kAsanInitializationOrderMagic);
524   PrintShadowByte(str, "  Poisoned by user:        ",
525                   kAsanUserPoisonedMemoryMagic);
526   PrintShadowByte(str, "  Container overflow:      ",
527                   kAsanContiguousContainerOOBMagic);
528   PrintShadowByte(str, "  Array cookie:            ",
529                   kAsanArrayCookieMagic);
530   PrintShadowByte(str, "  Intra object redzone:    ",
531                   kAsanIntraObjectRedzone);
532   PrintShadowByte(str, "  ASan internal:           ", kAsanInternalHeapMagic);
533   PrintShadowByte(str, "  Left alloca redzone:     ", kAsanAllocaLeftMagic);
534   PrintShadowByte(str, "  Right alloca redzone:    ", kAsanAllocaRightMagic);
535   PrintShadowByte(str, "  Shadow gap:              ", kAsanShadowGap);
536 }
537 
PrintShadowBytes(InternalScopedString * str,const char * before,u8 * bytes,u8 * guilty,uptr n)538 static void PrintShadowBytes(InternalScopedString *str, const char *before,
539                              u8 *bytes, u8 *guilty, uptr n) {
540   Decorator d;
541   if (before) str->append("%s%p:", before, bytes);
542   for (uptr i = 0; i < n; i++) {
543     u8 *p = bytes + i;
544     const char *before =
545         p == guilty ? "[" : (p - 1 == guilty && i != 0) ? "" : " ";
546     const char *after = p == guilty ? "]" : "";
547     PrintShadowByte(str, before, *p, after);
548   }
549   str->append("\n");
550 }
551 
PrintShadowMemoryForAddress(uptr addr)552 static void PrintShadowMemoryForAddress(uptr addr) {
553   if (!AddrIsInMem(addr)) return;
554   uptr shadow_addr = MemToShadow(addr);
555   const uptr n_bytes_per_row = 16;
556   uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1);
557   InternalScopedString str(4096 * 8);
558   str.append("Shadow bytes around the buggy address:\n");
559   for (int i = -5; i <= 5; i++) {
560     uptr row_shadow_addr = aligned_shadow + i * n_bytes_per_row;
561     // Skip rows that would be outside the shadow range. This can happen when
562     // the user address is near the bottom, top, or shadow gap of the address
563     // space.
564     if (!AddrIsInShadow(row_shadow_addr)) continue;
565     const char *prefix = (i == 0) ? "=>" : "  ";
566     PrintShadowBytes(&str, prefix, (u8 *)row_shadow_addr, (u8 *)shadow_addr,
567                      n_bytes_per_row);
568   }
569   if (flags()->print_legend) PrintLegend(&str);
570   Printf("%s", str.data());
571 }
572 
Print()573 void ErrorGeneric::Print() {
574   Decorator d;
575   Printf("%s", d.Error());
576   uptr addr = addr_description.Address();
577   Report("ERROR: AddressSanitizer: %s on address %p at pc %p bp %p sp %p\n",
578          bug_descr, (void *)addr, pc, bp, sp);
579   Printf("%s", d.Default());
580 
581   Printf("%s%s of size %zu at %p thread %s%s\n", d.Access(),
582          access_size ? (is_write ? "WRITE" : "READ") : "ACCESS", access_size,
583          (void *)addr, AsanThreadIdAndName(tid).c_str(), d.Default());
584 
585   scariness.Print();
586   GET_STACK_TRACE_FATAL(pc, bp);
587   stack.Print();
588 
589   // Pass bug_descr because we have a special case for
590   // initialization-order-fiasco
591   addr_description.Print(bug_descr);
592   if (shadow_val == kAsanContiguousContainerOOBMagic)
593     PrintContainerOverflowHint();
594   ReportErrorSummary(bug_descr, &stack);
595   PrintShadowMemoryForAddress(addr);
596 }
597 
598 }  // namespace __asan
599