1217222abSNico Weber //===-- asan_errors.cpp -----------------------------------------*- C++ -*-===//
2217222abSNico Weber //
3217222abSNico Weber // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4217222abSNico Weber // See https://llvm.org/LICENSE.txt for license information.
5217222abSNico Weber // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6217222abSNico Weber //
7217222abSNico Weber //===----------------------------------------------------------------------===//
8217222abSNico Weber //
9217222abSNico Weber // This file is a part of AddressSanitizer, an address sanity checker.
10217222abSNico Weber //
11217222abSNico Weber // ASan implementation for error structures.
12217222abSNico Weber //===----------------------------------------------------------------------===//
13217222abSNico Weber 
14217222abSNico Weber #include "asan_errors.h"
15217222abSNico Weber #include "asan_descriptions.h"
16217222abSNico Weber #include "asan_mapping.h"
17217222abSNico Weber #include "asan_report.h"
18217222abSNico Weber #include "asan_stack.h"
19217222abSNico Weber #include "sanitizer_common/sanitizer_stackdepot.h"
20217222abSNico Weber 
21217222abSNico Weber namespace __asan {
22217222abSNico Weber 
23217222abSNico Weber static void OnStackUnwind(const SignalContext &sig,
24217222abSNico Weber                           const void *callback_context,
25217222abSNico Weber                           BufferedStackTrace *stack) {
26217222abSNico Weber   bool fast = common_flags()->fast_unwind_on_fatal;
27217222abSNico Weber #if SANITIZER_FREEBSD || SANITIZER_NETBSD
28217222abSNico Weber   // On FreeBSD the slow unwinding that leverages _Unwind_Backtrace()
29217222abSNico Weber   // yields the call stack of the signal's handler and not of the code
30217222abSNico Weber   // that raised the signal (as it does on Linux).
31217222abSNico Weber   fast = true;
32217222abSNico Weber #endif
33217222abSNico Weber   // Tests and maybe some users expect that scariness is going to be printed
34217222abSNico Weber   // just before the stack. As only asan has scariness score we have no
35217222abSNico Weber   // corresponding code in the sanitizer_common and we use this callback to
36217222abSNico Weber   // print it.
37217222abSNico Weber   static_cast<const ScarinessScoreBase *>(callback_context)->Print();
38*d39e7e2cSVitaly Buka   stack->Unwind(StackTrace::GetNextInstructionPc(sig.pc), sig.bp, sig.context,
39*d39e7e2cSVitaly Buka                 fast);
40217222abSNico Weber }
41217222abSNico Weber 
42217222abSNico Weber void ErrorDeadlySignal::Print() {
43217222abSNico Weber   ReportDeadlySignal(signal, tid, &OnStackUnwind, &scariness);
44217222abSNico Weber }
45217222abSNico Weber 
46217222abSNico Weber void ErrorDoubleFree::Print() {
47217222abSNico Weber   Decorator d;
48217222abSNico Weber   Printf("%s", d.Error());
49217222abSNico Weber   Report(
50217222abSNico Weber       "ERROR: AddressSanitizer: attempting %s on %p in thread %s:\n",
51217222abSNico Weber       scariness.GetDescription(), addr_description.addr,
52217222abSNico Weber       AsanThreadIdAndName(tid).c_str());
53217222abSNico Weber   Printf("%s", d.Default());
54217222abSNico Weber   scariness.Print();
55217222abSNico Weber   GET_STACK_TRACE_FATAL(second_free_stack->trace[0],
56217222abSNico Weber                         second_free_stack->top_frame_bp);
57217222abSNico Weber   stack.Print();
58217222abSNico Weber   addr_description.Print();
59217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), &stack);
60217222abSNico Weber }
61217222abSNico Weber 
62217222abSNico Weber void ErrorNewDeleteTypeMismatch::Print() {
63217222abSNico Weber   Decorator d;
64217222abSNico Weber   Printf("%s", d.Error());
65217222abSNico Weber   Report(
66217222abSNico Weber       "ERROR: AddressSanitizer: %s on %p in thread %s:\n",
67217222abSNico Weber       scariness.GetDescription(), addr_description.addr,
68217222abSNico Weber       AsanThreadIdAndName(tid).c_str());
69217222abSNico Weber   Printf("%s  object passed to delete has wrong type:\n", d.Default());
70217222abSNico Weber   if (delete_size != 0) {
71217222abSNico Weber     Printf(
72217222abSNico Weber         "  size of the allocated type:   %zd bytes;\n"
73217222abSNico Weber         "  size of the deallocated type: %zd bytes.\n",
74217222abSNico Weber         addr_description.chunk_access.chunk_size, delete_size);
75217222abSNico Weber   }
76217222abSNico Weber   const uptr user_alignment =
77217222abSNico Weber       addr_description.chunk_access.user_requested_alignment;
78217222abSNico Weber   if (delete_alignment != user_alignment) {
79217222abSNico Weber     char user_alignment_str[32];
80217222abSNico Weber     char delete_alignment_str[32];
81217222abSNico Weber     internal_snprintf(user_alignment_str, sizeof(user_alignment_str),
82217222abSNico Weber                       "%zd bytes", user_alignment);
83217222abSNico Weber     internal_snprintf(delete_alignment_str, sizeof(delete_alignment_str),
84217222abSNico Weber                       "%zd bytes", delete_alignment);
85217222abSNico Weber     static const char *kDefaultAlignment = "default-aligned";
86217222abSNico Weber     Printf(
87217222abSNico Weber         "  alignment of the allocated type:   %s;\n"
88217222abSNico Weber         "  alignment of the deallocated type: %s.\n",
89217222abSNico Weber         user_alignment > 0 ? user_alignment_str : kDefaultAlignment,
90217222abSNico Weber         delete_alignment > 0 ? delete_alignment_str : kDefaultAlignment);
91217222abSNico Weber   }
92217222abSNico Weber   CHECK_GT(free_stack->size, 0);
93217222abSNico Weber   scariness.Print();
94217222abSNico Weber   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
95217222abSNico Weber   stack.Print();
96217222abSNico Weber   addr_description.Print();
97217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), &stack);
98217222abSNico Weber   Report(
99217222abSNico Weber       "HINT: if you don't care about these errors you may set "
100217222abSNico Weber       "ASAN_OPTIONS=new_delete_type_mismatch=0\n");
101217222abSNico Weber }
102217222abSNico Weber 
103217222abSNico Weber void ErrorFreeNotMalloced::Print() {
104217222abSNico Weber   Decorator d;
105217222abSNico Weber   Printf("%s", d.Error());
106217222abSNico Weber   Report(
107217222abSNico Weber       "ERROR: AddressSanitizer: attempting free on address "
108217222abSNico Weber       "which was not malloc()-ed: %p in thread %s\n",
109217222abSNico Weber       addr_description.Address(), AsanThreadIdAndName(tid).c_str());
110217222abSNico Weber   Printf("%s", d.Default());
111217222abSNico Weber   CHECK_GT(free_stack->size, 0);
112217222abSNico Weber   scariness.Print();
113217222abSNico Weber   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
114217222abSNico Weber   stack.Print();
115217222abSNico Weber   addr_description.Print();
116217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), &stack);
117217222abSNico Weber }
118217222abSNico Weber 
119217222abSNico Weber void ErrorAllocTypeMismatch::Print() {
120217222abSNico Weber   static const char *alloc_names[] = {"INVALID", "malloc", "operator new",
121217222abSNico Weber                                       "operator new []"};
122217222abSNico Weber   static const char *dealloc_names[] = {"INVALID", "free", "operator delete",
123217222abSNico Weber                                         "operator delete []"};
124217222abSNico Weber   CHECK_NE(alloc_type, dealloc_type);
125217222abSNico Weber   Decorator d;
126217222abSNico Weber   Printf("%s", d.Error());
127217222abSNico Weber   Report("ERROR: AddressSanitizer: %s (%s vs %s) on %p\n",
128217222abSNico Weber          scariness.GetDescription(), alloc_names[alloc_type],
129217222abSNico Weber          dealloc_names[dealloc_type], addr_description.Address());
130217222abSNico Weber   Printf("%s", d.Default());
131217222abSNico Weber   CHECK_GT(dealloc_stack->size, 0);
132217222abSNico Weber   scariness.Print();
133217222abSNico Weber   GET_STACK_TRACE_FATAL(dealloc_stack->trace[0], dealloc_stack->top_frame_bp);
134217222abSNico Weber   stack.Print();
135217222abSNico Weber   addr_description.Print();
136217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), &stack);
137217222abSNico Weber   Report(
138217222abSNico Weber       "HINT: if you don't care about these errors you may set "
139217222abSNico Weber       "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n");
140217222abSNico Weber }
141217222abSNico Weber 
142217222abSNico Weber void ErrorMallocUsableSizeNotOwned::Print() {
143217222abSNico Weber   Decorator d;
144217222abSNico Weber   Printf("%s", d.Error());
145217222abSNico Weber   Report(
146217222abSNico Weber       "ERROR: AddressSanitizer: attempting to call malloc_usable_size() for "
147217222abSNico Weber       "pointer which is not owned: %p\n",
148217222abSNico Weber       addr_description.Address());
149217222abSNico Weber   Printf("%s", d.Default());
150217222abSNico Weber   stack->Print();
151217222abSNico Weber   addr_description.Print();
152217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
153217222abSNico Weber }
154217222abSNico Weber 
155217222abSNico Weber void ErrorSanitizerGetAllocatedSizeNotOwned::Print() {
156217222abSNico Weber   Decorator d;
157217222abSNico Weber   Printf("%s", d.Error());
158217222abSNico Weber   Report(
159217222abSNico Weber       "ERROR: AddressSanitizer: attempting to call "
160217222abSNico Weber       "__sanitizer_get_allocated_size() for pointer which is not owned: %p\n",
161217222abSNico Weber       addr_description.Address());
162217222abSNico Weber   Printf("%s", d.Default());
163217222abSNico Weber   stack->Print();
164217222abSNico Weber   addr_description.Print();
165217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
166217222abSNico Weber }
167217222abSNico Weber 
168217222abSNico Weber void ErrorCallocOverflow::Print() {
169217222abSNico Weber   Decorator d;
170217222abSNico Weber   Printf("%s", d.Error());
171217222abSNico Weber   Report(
172217222abSNico Weber       "ERROR: AddressSanitizer: calloc parameters overflow: count * size "
173217222abSNico Weber       "(%zd * %zd) cannot be represented in type size_t (thread %s)\n",
174217222abSNico Weber       count, size, AsanThreadIdAndName(tid).c_str());
175217222abSNico Weber   Printf("%s", d.Default());
176217222abSNico Weber   stack->Print();
177217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
178217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
179217222abSNico Weber }
180217222abSNico Weber 
181217222abSNico Weber void ErrorReallocArrayOverflow::Print() {
182217222abSNico Weber   Decorator d;
183217222abSNico Weber   Printf("%s", d.Error());
184217222abSNico Weber   Report(
185217222abSNico Weber       "ERROR: AddressSanitizer: reallocarray parameters overflow: count * size "
186217222abSNico Weber       "(%zd * %zd) cannot be represented in type size_t (thread %s)\n",
187217222abSNico Weber       count, size, AsanThreadIdAndName(tid).c_str());
188217222abSNico Weber   Printf("%s", d.Default());
189217222abSNico Weber   stack->Print();
190217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
191217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
192217222abSNico Weber }
193217222abSNico Weber 
194217222abSNico Weber void ErrorPvallocOverflow::Print() {
195217222abSNico Weber   Decorator d;
196217222abSNico Weber   Printf("%s", d.Error());
197217222abSNico Weber   Report(
198217222abSNico Weber       "ERROR: AddressSanitizer: pvalloc parameters overflow: size 0x%zx "
199217222abSNico Weber       "rounded up to system page size 0x%zx cannot be represented in type "
200217222abSNico Weber       "size_t (thread %s)\n",
201217222abSNico Weber       size, GetPageSizeCached(), AsanThreadIdAndName(tid).c_str());
202217222abSNico Weber   Printf("%s", d.Default());
203217222abSNico Weber   stack->Print();
204217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
205217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
206217222abSNico Weber }
207217222abSNico Weber 
208217222abSNico Weber void ErrorInvalidAllocationAlignment::Print() {
209217222abSNico Weber   Decorator d;
210217222abSNico Weber   Printf("%s", d.Error());
211217222abSNico Weber   Report(
212217222abSNico Weber       "ERROR: AddressSanitizer: invalid allocation alignment: %zd, "
213217222abSNico Weber       "alignment must be a power of two (thread %s)\n",
214217222abSNico Weber       alignment, AsanThreadIdAndName(tid).c_str());
215217222abSNico Weber   Printf("%s", d.Default());
216217222abSNico Weber   stack->Print();
217217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
218217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
219217222abSNico Weber }
220217222abSNico Weber 
221217222abSNico Weber void ErrorInvalidAlignedAllocAlignment::Print() {
222217222abSNico Weber   Decorator d;
223217222abSNico Weber   Printf("%s", d.Error());
224217222abSNico Weber #if SANITIZER_POSIX
225217222abSNico Weber   Report("ERROR: AddressSanitizer: invalid alignment requested in "
226217222abSNico Weber          "aligned_alloc: %zd, alignment must be a power of two and the "
227217222abSNico Weber          "requested size 0x%zx must be a multiple of alignment "
228217222abSNico Weber          "(thread %s)\n", alignment, size, AsanThreadIdAndName(tid).c_str());
229217222abSNico Weber #else
230217222abSNico Weber   Report("ERROR: AddressSanitizer: invalid alignment requested in "
231217222abSNico Weber          "aligned_alloc: %zd, the requested size 0x%zx must be a multiple of "
232217222abSNico Weber          "alignment (thread %s)\n", alignment, size,
233217222abSNico Weber          AsanThreadIdAndName(tid).c_str());
234217222abSNico Weber #endif
235217222abSNico Weber   Printf("%s", d.Default());
236217222abSNico Weber   stack->Print();
237217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
238217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
239217222abSNico Weber }
240217222abSNico Weber 
241217222abSNico Weber void ErrorInvalidPosixMemalignAlignment::Print() {
242217222abSNico Weber   Decorator d;
243217222abSNico Weber   Printf("%s", d.Error());
244217222abSNico Weber   Report(
245217222abSNico Weber       "ERROR: AddressSanitizer: invalid alignment requested in posix_memalign: "
246217222abSNico Weber       "%zd, alignment must be a power of two and a multiple of sizeof(void*) "
247217222abSNico Weber       "== %zd (thread %s)\n",
248c0fa6322SVitaly Buka       alignment, sizeof(void *), AsanThreadIdAndName(tid).c_str());
249217222abSNico Weber   Printf("%s", d.Default());
250217222abSNico Weber   stack->Print();
251217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
252217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
253217222abSNico Weber }
254217222abSNico Weber 
255217222abSNico Weber void ErrorAllocationSizeTooBig::Print() {
256217222abSNico Weber   Decorator d;
257217222abSNico Weber   Printf("%s", d.Error());
258217222abSNico Weber   Report(
259217222abSNico Weber       "ERROR: AddressSanitizer: requested allocation size 0x%zx (0x%zx after "
260217222abSNico Weber       "adjustments for alignment, red zones etc.) exceeds maximum supported "
261217222abSNico Weber       "size of 0x%zx (thread %s)\n",
262217222abSNico Weber       user_size, total_size, max_size, AsanThreadIdAndName(tid).c_str());
263217222abSNico Weber   Printf("%s", d.Default());
264217222abSNico Weber   stack->Print();
265217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
266217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
267217222abSNico Weber }
268217222abSNico Weber 
269217222abSNico Weber void ErrorRssLimitExceeded::Print() {
270217222abSNico Weber   Decorator d;
271217222abSNico Weber   Printf("%s", d.Error());
272217222abSNico Weber   Report(
273217222abSNico Weber       "ERROR: AddressSanitizer: specified RSS limit exceeded, currently set to "
274217222abSNico Weber       "soft_rss_limit_mb=%zd\n", common_flags()->soft_rss_limit_mb);
275217222abSNico Weber   Printf("%s", d.Default());
276217222abSNico Weber   stack->Print();
277217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
278217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
279217222abSNico Weber }
280217222abSNico Weber 
281217222abSNico Weber void ErrorOutOfMemory::Print() {
282217222abSNico Weber   Decorator d;
283217222abSNico Weber   Printf("%s", d.Error());
284217222abSNico Weber   Report(
285217222abSNico Weber       "ERROR: AddressSanitizer: allocator is out of memory trying to allocate "
286217222abSNico Weber       "0x%zx bytes\n", requested_size);
287217222abSNico Weber   Printf("%s", d.Default());
288217222abSNico Weber   stack->Print();
289217222abSNico Weber   PrintHintAllocatorCannotReturnNull();
290217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
291217222abSNico Weber }
292217222abSNico Weber 
293217222abSNico Weber void ErrorStringFunctionMemoryRangesOverlap::Print() {
294217222abSNico Weber   Decorator d;
295217222abSNico Weber   char bug_type[100];
296217222abSNico Weber   internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function);
297217222abSNico Weber   Printf("%s", d.Error());
298217222abSNico Weber   Report(
299217222abSNico Weber       "ERROR: AddressSanitizer: %s: memory ranges [%p,%p) and [%p, %p) "
300217222abSNico Weber       "overlap\n",
301217222abSNico Weber       bug_type, addr1_description.Address(),
302217222abSNico Weber       addr1_description.Address() + length1, addr2_description.Address(),
303217222abSNico Weber       addr2_description.Address() + length2);
304217222abSNico Weber   Printf("%s", d.Default());
305217222abSNico Weber   scariness.Print();
306217222abSNico Weber   stack->Print();
307217222abSNico Weber   addr1_description.Print();
308217222abSNico Weber   addr2_description.Print();
309217222abSNico Weber   ReportErrorSummary(bug_type, stack);
310217222abSNico Weber }
311217222abSNico Weber 
312217222abSNico Weber void ErrorStringFunctionSizeOverflow::Print() {
313217222abSNico Weber   Decorator d;
314217222abSNico Weber   Printf("%s", d.Error());
315217222abSNico Weber   Report("ERROR: AddressSanitizer: %s: (size=%zd)\n",
316217222abSNico Weber          scariness.GetDescription(), size);
317217222abSNico Weber   Printf("%s", d.Default());
318217222abSNico Weber   scariness.Print();
319217222abSNico Weber   stack->Print();
320217222abSNico Weber   addr_description.Print();
321217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
322217222abSNico Weber }
323217222abSNico Weber 
324217222abSNico Weber void ErrorBadParamsToAnnotateContiguousContainer::Print() {
325217222abSNico Weber   Report(
326217222abSNico Weber       "ERROR: AddressSanitizer: bad parameters to "
327217222abSNico Weber       "__sanitizer_annotate_contiguous_container:\n"
328217222abSNico Weber       "      beg     : %p\n"
329217222abSNico Weber       "      end     : %p\n"
330217222abSNico Weber       "      old_mid : %p\n"
331217222abSNico Weber       "      new_mid : %p\n",
332217222abSNico Weber       beg, end, old_mid, new_mid);
333217222abSNico Weber   uptr granularity = SHADOW_GRANULARITY;
334217222abSNico Weber   if (!IsAligned(beg, granularity))
335217222abSNico Weber     Report("ERROR: beg is not aligned by %d\n", granularity);
336217222abSNico Weber   stack->Print();
337217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), stack);
338217222abSNico Weber }
339217222abSNico Weber 
340217222abSNico Weber void ErrorODRViolation::Print() {
341217222abSNico Weber   Decorator d;
342217222abSNico Weber   Printf("%s", d.Error());
343217222abSNico Weber   Report("ERROR: AddressSanitizer: %s (%p):\n", scariness.GetDescription(),
344217222abSNico Weber          global1.beg);
345217222abSNico Weber   Printf("%s", d.Default());
346217222abSNico Weber   InternalScopedString g1_loc(256), g2_loc(256);
347217222abSNico Weber   PrintGlobalLocation(&g1_loc, global1);
348217222abSNico Weber   PrintGlobalLocation(&g2_loc, global2);
349217222abSNico Weber   Printf("  [1] size=%zd '%s' %s\n", global1.size,
350217222abSNico Weber          MaybeDemangleGlobalName(global1.name), g1_loc.data());
351217222abSNico Weber   Printf("  [2] size=%zd '%s' %s\n", global2.size,
352217222abSNico Weber          MaybeDemangleGlobalName(global2.name), g2_loc.data());
353217222abSNico Weber   if (stack_id1 && stack_id2) {
354217222abSNico Weber     Printf("These globals were registered at these points:\n");
355217222abSNico Weber     Printf("  [1]:\n");
356217222abSNico Weber     StackDepotGet(stack_id1).Print();
357217222abSNico Weber     Printf("  [2]:\n");
358217222abSNico Weber     StackDepotGet(stack_id2).Print();
359217222abSNico Weber   }
360217222abSNico Weber   Report(
361217222abSNico Weber       "HINT: if you don't care about these errors you may set "
362217222abSNico Weber       "ASAN_OPTIONS=detect_odr_violation=0\n");
363217222abSNico Weber   InternalScopedString error_msg(256);
364217222abSNico Weber   error_msg.append("%s: global '%s' at %s", scariness.GetDescription(),
365217222abSNico Weber                    MaybeDemangleGlobalName(global1.name), g1_loc.data());
366217222abSNico Weber   ReportErrorSummary(error_msg.data());
367217222abSNico Weber }
368217222abSNico Weber 
369217222abSNico Weber void ErrorInvalidPointerPair::Print() {
370217222abSNico Weber   Decorator d;
371217222abSNico Weber   Printf("%s", d.Error());
372217222abSNico Weber   Report("ERROR: AddressSanitizer: %s: %p %p\n", scariness.GetDescription(),
373217222abSNico Weber          addr1_description.Address(), addr2_description.Address());
374217222abSNico Weber   Printf("%s", d.Default());
375217222abSNico Weber   GET_STACK_TRACE_FATAL(pc, bp);
376217222abSNico Weber   stack.Print();
377217222abSNico Weber   addr1_description.Print();
378217222abSNico Weber   addr2_description.Print();
379217222abSNico Weber   ReportErrorSummary(scariness.GetDescription(), &stack);
380217222abSNico Weber }
381217222abSNico Weber 
382217222abSNico Weber static bool AdjacentShadowValuesAreFullyPoisoned(u8 *s) {
383217222abSNico Weber   return s[-1] > 127 && s[1] > 127;
384217222abSNico Weber }
385217222abSNico Weber 
386217222abSNico Weber ErrorGeneric::ErrorGeneric(u32 tid, uptr pc_, uptr bp_, uptr sp_, uptr addr,
387217222abSNico Weber                            bool is_write_, uptr access_size_)
388217222abSNico Weber     : ErrorBase(tid),
389217222abSNico Weber       addr_description(addr, access_size_, /*shouldLockThreadRegistry=*/false),
390217222abSNico Weber       pc(pc_),
391217222abSNico Weber       bp(bp_),
392217222abSNico Weber       sp(sp_),
393217222abSNico Weber       access_size(access_size_),
394217222abSNico Weber       is_write(is_write_),
395217222abSNico Weber       shadow_val(0) {
396217222abSNico Weber   scariness.Clear();
397217222abSNico Weber   if (access_size) {
398217222abSNico Weber     if (access_size <= 9) {
399217222abSNico Weber       char desr[] = "?-byte";
400217222abSNico Weber       desr[0] = '0' + access_size;
401217222abSNico Weber       scariness.Scare(access_size + access_size / 2, desr);
402217222abSNico Weber     } else if (access_size >= 10) {
403217222abSNico Weber       scariness.Scare(15, "multi-byte");
404217222abSNico Weber     }
405217222abSNico Weber     is_write ? scariness.Scare(20, "write") : scariness.Scare(1, "read");
406217222abSNico Weber 
407217222abSNico Weber     // Determine the error type.
408217222abSNico Weber     bug_descr = "unknown-crash";
409217222abSNico Weber     if (AddrIsInMem(addr)) {
410217222abSNico Weber       u8 *shadow_addr = (u8 *)MemToShadow(addr);
411217222abSNico Weber       // If we are accessing 16 bytes, look at the second shadow byte.
412217222abSNico Weber       if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY) shadow_addr++;
413217222abSNico Weber       // If we are in the partial right redzone, look at the next shadow byte.
414217222abSNico Weber       if (*shadow_addr > 0 && *shadow_addr < 128) shadow_addr++;
415217222abSNico Weber       bool far_from_bounds = false;
416217222abSNico Weber       shadow_val = *shadow_addr;
417217222abSNico Weber       int bug_type_score = 0;
418217222abSNico Weber       // For use-after-frees reads are almost as bad as writes.
419217222abSNico Weber       int read_after_free_bonus = 0;
420217222abSNico Weber       switch (shadow_val) {
421217222abSNico Weber         case kAsanHeapLeftRedzoneMagic:
422217222abSNico Weber         case kAsanArrayCookieMagic:
423217222abSNico Weber           bug_descr = "heap-buffer-overflow";
424217222abSNico Weber           bug_type_score = 10;
425217222abSNico Weber           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
426217222abSNico Weber           break;
427217222abSNico Weber         case kAsanHeapFreeMagic:
428217222abSNico Weber           bug_descr = "heap-use-after-free";
429217222abSNico Weber           bug_type_score = 20;
430217222abSNico Weber           if (!is_write) read_after_free_bonus = 18;
431217222abSNico Weber           break;
432217222abSNico Weber         case kAsanStackLeftRedzoneMagic:
433217222abSNico Weber           bug_descr = "stack-buffer-underflow";
434217222abSNico Weber           bug_type_score = 25;
435217222abSNico Weber           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
436217222abSNico Weber           break;
437217222abSNico Weber         case kAsanInitializationOrderMagic:
438217222abSNico Weber           bug_descr = "initialization-order-fiasco";
439217222abSNico Weber           bug_type_score = 1;
440217222abSNico Weber           break;
441217222abSNico Weber         case kAsanStackMidRedzoneMagic:
442217222abSNico Weber         case kAsanStackRightRedzoneMagic:
443217222abSNico Weber           bug_descr = "stack-buffer-overflow";
444217222abSNico Weber           bug_type_score = 25;
445217222abSNico Weber           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
446217222abSNico Weber           break;
447217222abSNico Weber         case kAsanStackAfterReturnMagic:
448217222abSNico Weber           bug_descr = "stack-use-after-return";
449217222abSNico Weber           bug_type_score = 30;
450217222abSNico Weber           if (!is_write) read_after_free_bonus = 18;
451217222abSNico Weber           break;
452217222abSNico Weber         case kAsanUserPoisonedMemoryMagic:
453217222abSNico Weber           bug_descr = "use-after-poison";
454217222abSNico Weber           bug_type_score = 20;
455217222abSNico Weber           break;
456217222abSNico Weber         case kAsanContiguousContainerOOBMagic:
457217222abSNico Weber           bug_descr = "container-overflow";
458217222abSNico Weber           bug_type_score = 10;
459217222abSNico Weber           break;
460217222abSNico Weber         case kAsanStackUseAfterScopeMagic:
461217222abSNico Weber           bug_descr = "stack-use-after-scope";
462217222abSNico Weber           bug_type_score = 10;
463217222abSNico Weber           break;
464217222abSNico Weber         case kAsanGlobalRedzoneMagic:
465217222abSNico Weber           bug_descr = "global-buffer-overflow";
466217222abSNico Weber           bug_type_score = 10;
467217222abSNico Weber           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
468217222abSNico Weber           break;
469217222abSNico Weber         case kAsanIntraObjectRedzone:
470217222abSNico Weber           bug_descr = "intra-object-overflow";
471217222abSNico Weber           bug_type_score = 10;
472217222abSNico Weber           break;
473217222abSNico Weber         case kAsanAllocaLeftMagic:
474217222abSNico Weber         case kAsanAllocaRightMagic:
475217222abSNico Weber           bug_descr = "dynamic-stack-buffer-overflow";
476217222abSNico Weber           bug_type_score = 25;
477217222abSNico Weber           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
478217222abSNico Weber           break;
479217222abSNico Weber       }
480217222abSNico Weber       scariness.Scare(bug_type_score + read_after_free_bonus, bug_descr);
481217222abSNico Weber       if (far_from_bounds) scariness.Scare(10, "far-from-bounds");
482217222abSNico Weber     }
483217222abSNico Weber   }
484217222abSNico Weber }
485217222abSNico Weber 
486217222abSNico Weber static void PrintContainerOverflowHint() {
487217222abSNico Weber   Printf("HINT: if you don't care about these errors you may set "
488217222abSNico Weber          "ASAN_OPTIONS=detect_container_overflow=0.\n"
489217222abSNico Weber          "If you suspect a false positive see also: "
490217222abSNico Weber          "https://github.com/google/sanitizers/wiki/"
491217222abSNico Weber          "AddressSanitizerContainerOverflow.\n");
492217222abSNico Weber }
493217222abSNico Weber 
494217222abSNico Weber static void PrintShadowByte(InternalScopedString *str, const char *before,
495217222abSNico Weber     u8 byte, const char *after = "\n") {
496217222abSNico Weber   PrintMemoryByte(str, before, byte, /*in_shadow*/true, after);
497217222abSNico Weber }
498217222abSNico Weber 
499217222abSNico Weber static void PrintLegend(InternalScopedString *str) {
500217222abSNico Weber   str->append(
501217222abSNico Weber       "Shadow byte legend (one shadow byte represents %d "
502217222abSNico Weber       "application bytes):\n",
503217222abSNico Weber       (int)SHADOW_GRANULARITY);
504217222abSNico Weber   PrintShadowByte(str, "  Addressable:           ", 0);
505217222abSNico Weber   str->append("  Partially addressable: ");
506217222abSNico Weber   for (u8 i = 1; i < SHADOW_GRANULARITY; i++) PrintShadowByte(str, "", i, " ");
507217222abSNico Weber   str->append("\n");
508217222abSNico Weber   PrintShadowByte(str, "  Heap left redzone:       ",
509217222abSNico Weber                   kAsanHeapLeftRedzoneMagic);
510217222abSNico Weber   PrintShadowByte(str, "  Freed heap region:       ", kAsanHeapFreeMagic);
511217222abSNico Weber   PrintShadowByte(str, "  Stack left redzone:      ",
512217222abSNico Weber                   kAsanStackLeftRedzoneMagic);
513217222abSNico Weber   PrintShadowByte(str, "  Stack mid redzone:       ",
514217222abSNico Weber                   kAsanStackMidRedzoneMagic);
515217222abSNico Weber   PrintShadowByte(str, "  Stack right redzone:     ",
516217222abSNico Weber                   kAsanStackRightRedzoneMagic);
517217222abSNico Weber   PrintShadowByte(str, "  Stack after return:      ",
518217222abSNico Weber                   kAsanStackAfterReturnMagic);
519217222abSNico Weber   PrintShadowByte(str, "  Stack use after scope:   ",
520217222abSNico Weber                   kAsanStackUseAfterScopeMagic);
521217222abSNico Weber   PrintShadowByte(str, "  Global redzone:          ", kAsanGlobalRedzoneMagic);
522217222abSNico Weber   PrintShadowByte(str, "  Global init order:       ",
523217222abSNico Weber                   kAsanInitializationOrderMagic);
524217222abSNico Weber   PrintShadowByte(str, "  Poisoned by user:        ",
525217222abSNico Weber                   kAsanUserPoisonedMemoryMagic);
526217222abSNico Weber   PrintShadowByte(str, "  Container overflow:      ",
527217222abSNico Weber                   kAsanContiguousContainerOOBMagic);
528217222abSNico Weber   PrintShadowByte(str, "  Array cookie:            ",
529217222abSNico Weber                   kAsanArrayCookieMagic);
530217222abSNico Weber   PrintShadowByte(str, "  Intra object redzone:    ",
531217222abSNico Weber                   kAsanIntraObjectRedzone);
532217222abSNico Weber   PrintShadowByte(str, "  ASan internal:           ", kAsanInternalHeapMagic);
533217222abSNico Weber   PrintShadowByte(str, "  Left alloca redzone:     ", kAsanAllocaLeftMagic);
534217222abSNico Weber   PrintShadowByte(str, "  Right alloca redzone:    ", kAsanAllocaRightMagic);
535217222abSNico Weber   PrintShadowByte(str, "  Shadow gap:              ", kAsanShadowGap);
536217222abSNico Weber }
537217222abSNico Weber 
538217222abSNico Weber static void PrintShadowBytes(InternalScopedString *str, const char *before,
539217222abSNico Weber                              u8 *bytes, u8 *guilty, uptr n) {
540217222abSNico Weber   Decorator d;
541217222abSNico Weber   if (before) str->append("%s%p:", before, bytes);
542217222abSNico Weber   for (uptr i = 0; i < n; i++) {
543217222abSNico Weber     u8 *p = bytes + i;
544217222abSNico Weber     const char *before =
545217222abSNico Weber         p == guilty ? "[" : (p - 1 == guilty && i != 0) ? "" : " ";
546217222abSNico Weber     const char *after = p == guilty ? "]" : "";
547217222abSNico Weber     PrintShadowByte(str, before, *p, after);
548217222abSNico Weber   }
549217222abSNico Weber   str->append("\n");
550217222abSNico Weber }
551217222abSNico Weber 
552217222abSNico Weber static void PrintShadowMemoryForAddress(uptr addr) {
553217222abSNico Weber   if (!AddrIsInMem(addr)) return;
554217222abSNico Weber   uptr shadow_addr = MemToShadow(addr);
555217222abSNico Weber   const uptr n_bytes_per_row = 16;
556217222abSNico Weber   uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1);
557217222abSNico Weber   InternalScopedString str(4096 * 8);
558217222abSNico Weber   str.append("Shadow bytes around the buggy address:\n");
559217222abSNico Weber   for (int i = -5; i <= 5; i++) {
560217222abSNico Weber     uptr row_shadow_addr = aligned_shadow + i * n_bytes_per_row;
561217222abSNico Weber     // Skip rows that would be outside the shadow range. This can happen when
562217222abSNico Weber     // the user address is near the bottom, top, or shadow gap of the address
563217222abSNico Weber     // space.
564217222abSNico Weber     if (!AddrIsInShadow(row_shadow_addr)) continue;
565217222abSNico Weber     const char *prefix = (i == 0) ? "=>" : "  ";
566217222abSNico Weber     PrintShadowBytes(&str, prefix, (u8 *)row_shadow_addr, (u8 *)shadow_addr,
567217222abSNico Weber                      n_bytes_per_row);
568217222abSNico Weber   }
569217222abSNico Weber   if (flags()->print_legend) PrintLegend(&str);
570217222abSNico Weber   Printf("%s", str.data());
571217222abSNico Weber }
572217222abSNico Weber 
573217222abSNico Weber void ErrorGeneric::Print() {
574217222abSNico Weber   Decorator d;
575217222abSNico Weber   Printf("%s", d.Error());
576217222abSNico Weber   uptr addr = addr_description.Address();
577217222abSNico Weber   Report("ERROR: AddressSanitizer: %s on address %p at pc %p bp %p sp %p\n",
578217222abSNico Weber          bug_descr, (void *)addr, pc, bp, sp);
579217222abSNico Weber   Printf("%s", d.Default());
580217222abSNico Weber 
581217222abSNico Weber   Printf("%s%s of size %zu at %p thread %s%s\n", d.Access(),
582217222abSNico Weber          access_size ? (is_write ? "WRITE" : "READ") : "ACCESS", access_size,
583217222abSNico Weber          (void *)addr, AsanThreadIdAndName(tid).c_str(), d.Default());
584217222abSNico Weber 
585217222abSNico Weber   scariness.Print();
586217222abSNico Weber   GET_STACK_TRACE_FATAL(pc, bp);
587217222abSNico Weber   stack.Print();
588217222abSNico Weber 
589217222abSNico Weber   // Pass bug_descr because we have a special case for
590217222abSNico Weber   // initialization-order-fiasco
591217222abSNico Weber   addr_description.Print(bug_descr);
592217222abSNico Weber   if (shadow_val == kAsanContiguousContainerOOBMagic)
593217222abSNico Weber     PrintContainerOverflowHint();
594217222abSNico Weber   ReportErrorSummary(bug_descr, &stack);
595217222abSNico Weber   PrintShadowMemoryForAddress(addr);
596217222abSNico Weber }
597217222abSNico Weber 
598217222abSNico Weber }  // namespace __asan
599