1 //===-- asan_errors.cc ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of AddressSanitizer, an address sanity checker.
12 // ASan implementation for error structures.
13 //===----------------------------------------------------------------------===//
15 #include "asan_errors.h"
16 #include "asan_descriptions.h"
17 #include "asan_mapping.h"
18 #include "asan_report.h"
19 #include "asan_stack.h"
20 #include "sanitizer_common/sanitizer_stackdepot.h"
24 static void OnStackUnwind(const SignalContext &sig,
25 const void *callback_context,
26 BufferedStackTrace *stack) {
27 bool fast = common_flags()->fast_unwind_on_fatal;
28 #if SANITIZER_FREEBSD || SANITIZER_NETBSD
29 // On FreeBSD the slow unwinding that leverages _Unwind_Backtrace()
30 // yields the call stack of the signal's handler and not of the code
31 // that raised the signal (as it does on Linux).
34 // Tests and maybe some users expect that scariness is going to be printed
35 // just before the stack. As only asan has scariness score we have no
36 // corresponding code in the sanitizer_common and we use this callback to
38 static_cast<const ScarinessScoreBase *>(callback_context)->Print();
39 GetStackTrace(stack, kStackTraceMax, sig.pc, sig.bp, sig.context, fast);
42 void ErrorDeadlySignal::Print() {
43 ReportDeadlySignal(signal, tid, &OnStackUnwind, &scariness);
46 void ErrorDoubleFree::Print() {
48 Printf("%s", d.Warning());
51 "ERROR: AddressSanitizer: attempting %s on %p in "
53 scariness.GetDescription(), addr_description.addr, tid,
54 ThreadNameWithParenthesis(tid, tname, sizeof(tname)));
55 Printf("%s", d.Default());
57 GET_STACK_TRACE_FATAL(second_free_stack->trace[0],
58 second_free_stack->top_frame_bp);
60 addr_description.Print();
61 ReportErrorSummary(scariness.GetDescription(), &stack);
64 void ErrorNewDeleteTypeMismatch::Print() {
66 Printf("%s", d.Warning());
69 "ERROR: AddressSanitizer: %s on %p in thread "
71 scariness.GetDescription(), addr_description.addr, tid,
72 ThreadNameWithParenthesis(tid, tname, sizeof(tname)));
73 Printf("%s object passed to delete has wrong type:\n", d.Default());
74 if (delete_size != 0) {
76 " size of the allocated type: %zd bytes;\n"
77 " size of the deallocated type: %zd bytes.\n",
78 addr_description.chunk_access.chunk_size, delete_size);
80 const uptr user_alignment =
81 addr_description.chunk_access.user_requested_alignment;
82 if (delete_alignment != user_alignment) {
83 char user_alignment_str[32];
84 char delete_alignment_str[32];
85 internal_snprintf(user_alignment_str, sizeof(user_alignment_str),
86 "%zd bytes", user_alignment);
87 internal_snprintf(delete_alignment_str, sizeof(delete_alignment_str),
88 "%zd bytes", delete_alignment);
89 static const char *kDefaultAlignment = "default-aligned";
91 " alignment of the allocated type: %s;\n"
92 " alignment of the deallocated type: %s.\n",
93 user_alignment > 0 ? user_alignment_str : kDefaultAlignment,
94 delete_alignment > 0 ? delete_alignment_str : kDefaultAlignment);
96 CHECK_GT(free_stack->size, 0);
98 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
100 addr_description.Print();
101 ReportErrorSummary(scariness.GetDescription(), &stack);
103 "HINT: if you don't care about these errors you may set "
104 "ASAN_OPTIONS=new_delete_type_mismatch=0\n");
107 void ErrorFreeNotMalloced::Print() {
109 Printf("%s", d.Warning());
112 "ERROR: AddressSanitizer: attempting free on address "
113 "which was not malloc()-ed: %p in thread T%d%s\n",
114 addr_description.Address(), tid,
115 ThreadNameWithParenthesis(tid, tname, sizeof(tname)));
116 Printf("%s", d.Default());
117 CHECK_GT(free_stack->size, 0);
119 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
121 addr_description.Print();
122 ReportErrorSummary(scariness.GetDescription(), &stack);
125 void ErrorAllocTypeMismatch::Print() {
126 static const char *alloc_names[] = {"INVALID", "malloc", "operator new",
128 static const char *dealloc_names[] = {"INVALID", "free", "operator delete",
129 "operator delete []"};
130 CHECK_NE(alloc_type, dealloc_type);
132 Printf("%s", d.Warning());
133 Report("ERROR: AddressSanitizer: %s (%s vs %s) on %p\n",
134 scariness.GetDescription(),
135 alloc_names[alloc_type], dealloc_names[dealloc_type],
136 addr_description.addr);
137 Printf("%s", d.Default());
138 CHECK_GT(dealloc_stack->size, 0);
140 GET_STACK_TRACE_FATAL(dealloc_stack->trace[0], dealloc_stack->top_frame_bp);
142 addr_description.Print();
143 ReportErrorSummary(scariness.GetDescription(), &stack);
145 "HINT: if you don't care about these errors you may set "
146 "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n");
149 void ErrorMallocUsableSizeNotOwned::Print() {
151 Printf("%s", d.Warning());
153 "ERROR: AddressSanitizer: attempting to call malloc_usable_size() for "
154 "pointer which is not owned: %p\n",
155 addr_description.Address());
156 Printf("%s", d.Default());
158 addr_description.Print();
159 ReportErrorSummary(scariness.GetDescription(), stack);
162 void ErrorSanitizerGetAllocatedSizeNotOwned::Print() {
164 Printf("%s", d.Warning());
166 "ERROR: AddressSanitizer: attempting to call "
167 "__sanitizer_get_allocated_size() for pointer which is not owned: %p\n",
168 addr_description.Address());
169 Printf("%s", d.Default());
171 addr_description.Print();
172 ReportErrorSummary(scariness.GetDescription(), stack);
175 void ErrorStringFunctionMemoryRangesOverlap::Print() {
178 internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function);
179 Printf("%s", d.Warning());
181 "ERROR: AddressSanitizer: %s: memory ranges [%p,%p) and [%p, %p) "
183 bug_type, addr1_description.Address(),
184 addr1_description.Address() + length1, addr2_description.Address(),
185 addr2_description.Address() + length2);
186 Printf("%s", d.Default());
189 addr1_description.Print();
190 addr2_description.Print();
191 ReportErrorSummary(bug_type, stack);
194 void ErrorStringFunctionSizeOverflow::Print() {
196 Printf("%s", d.Warning());
197 Report("ERROR: AddressSanitizer: %s: (size=%zd)\n",
198 scariness.GetDescription(), size);
199 Printf("%s", d.Default());
202 addr_description.Print();
203 ReportErrorSummary(scariness.GetDescription(), stack);
206 void ErrorBadParamsToAnnotateContiguousContainer::Print() {
208 "ERROR: AddressSanitizer: bad parameters to "
209 "__sanitizer_annotate_contiguous_container:\n"
214 beg, end, old_mid, new_mid);
215 uptr granularity = SHADOW_GRANULARITY;
216 if (!IsAligned(beg, granularity))
217 Report("ERROR: beg is not aligned by %d\n", granularity);
219 ReportErrorSummary(scariness.GetDescription(), stack);
222 void ErrorODRViolation::Print() {
224 Printf("%s", d.Warning());
225 Report("ERROR: AddressSanitizer: %s (%p):\n", scariness.GetDescription(),
227 Printf("%s", d.Default());
228 InternalScopedString g1_loc(256), g2_loc(256);
229 PrintGlobalLocation(&g1_loc, global1);
230 PrintGlobalLocation(&g2_loc, global2);
231 Printf(" [1] size=%zd '%s' %s\n", global1.size,
232 MaybeDemangleGlobalName(global1.name), g1_loc.data());
233 Printf(" [2] size=%zd '%s' %s\n", global2.size,
234 MaybeDemangleGlobalName(global2.name), g2_loc.data());
235 if (stack_id1 && stack_id2) {
236 Printf("These globals were registered at these points:\n");
238 StackDepotGet(stack_id1).Print();
240 StackDepotGet(stack_id2).Print();
243 "HINT: if you don't care about these errors you may set "
244 "ASAN_OPTIONS=detect_odr_violation=0\n");
245 InternalScopedString error_msg(256);
246 error_msg.append("%s: global '%s' at %s", scariness.GetDescription(),
247 MaybeDemangleGlobalName(global1.name), g1_loc.data());
248 ReportErrorSummary(error_msg.data());
251 void ErrorInvalidPointerPair::Print() {
253 Printf("%s", d.Warning());
254 Report("ERROR: AddressSanitizer: %s: %p %p\n", scariness.GetDescription(),
255 addr1_description.Address(), addr2_description.Address());
256 Printf("%s", d.Default());
257 GET_STACK_TRACE_FATAL(pc, bp);
259 addr1_description.Print();
260 addr2_description.Print();
261 ReportErrorSummary(scariness.GetDescription(), &stack);
264 static bool AdjacentShadowValuesAreFullyPoisoned(u8 *s) {
265 return s[-1] > 127 && s[1] > 127;
268 ErrorGeneric::ErrorGeneric(u32 tid, uptr pc_, uptr bp_, uptr sp_, uptr addr,
269 bool is_write_, uptr access_size_)
271 addr_description(addr, access_size_, /*shouldLockThreadRegistry=*/false),
275 access_size(access_size_),
280 if (access_size <= 9) {
281 char desr[] = "?-byte";
282 desr[0] = '0' + access_size;
283 scariness.Scare(access_size + access_size / 2, desr);
284 } else if (access_size >= 10) {
285 scariness.Scare(15, "multi-byte");
287 is_write ? scariness.Scare(20, "write") : scariness.Scare(1, "read");
289 // Determine the error type.
290 bug_descr = "unknown-crash";
291 if (AddrIsInMem(addr)) {
292 u8 *shadow_addr = (u8 *)MemToShadow(addr);
293 // If we are accessing 16 bytes, look at the second shadow byte.
294 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY) shadow_addr++;
295 // If we are in the partial right redzone, look at the next shadow byte.
296 if (*shadow_addr > 0 && *shadow_addr < 128) shadow_addr++;
297 bool far_from_bounds = false;
298 shadow_val = *shadow_addr;
299 int bug_type_score = 0;
300 // For use-after-frees reads are almost as bad as writes.
301 int read_after_free_bonus = 0;
302 switch (shadow_val) {
303 case kAsanHeapLeftRedzoneMagic:
304 case kAsanArrayCookieMagic:
305 bug_descr = "heap-buffer-overflow";
307 far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
309 case kAsanHeapFreeMagic:
310 bug_descr = "heap-use-after-free";
312 if (!is_write) read_after_free_bonus = 18;
314 case kAsanStackLeftRedzoneMagic:
315 bug_descr = "stack-buffer-underflow";
317 far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
319 case kAsanInitializationOrderMagic:
320 bug_descr = "initialization-order-fiasco";
323 case kAsanStackMidRedzoneMagic:
324 case kAsanStackRightRedzoneMagic:
325 bug_descr = "stack-buffer-overflow";
327 far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
329 case kAsanStackAfterReturnMagic:
330 bug_descr = "stack-use-after-return";
332 if (!is_write) read_after_free_bonus = 18;
334 case kAsanUserPoisonedMemoryMagic:
335 bug_descr = "use-after-poison";
338 case kAsanContiguousContainerOOBMagic:
339 bug_descr = "container-overflow";
342 case kAsanStackUseAfterScopeMagic:
343 bug_descr = "stack-use-after-scope";
346 case kAsanGlobalRedzoneMagic:
347 bug_descr = "global-buffer-overflow";
349 far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
351 case kAsanIntraObjectRedzone:
352 bug_descr = "intra-object-overflow";
355 case kAsanAllocaLeftMagic:
356 case kAsanAllocaRightMagic:
357 bug_descr = "dynamic-stack-buffer-overflow";
359 far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
362 scariness.Scare(bug_type_score + read_after_free_bonus, bug_descr);
363 if (far_from_bounds) scariness.Scare(10, "far-from-bounds");
368 static void PrintContainerOverflowHint() {
369 Printf("HINT: if you don't care about these errors you may set "
370 "ASAN_OPTIONS=detect_container_overflow=0.\n"
371 "If you suspect a false positive see also: "
372 "https://github.com/google/sanitizers/wiki/"
373 "AddressSanitizerContainerOverflow.\n");
376 static void PrintShadowByte(InternalScopedString *str, const char *before,
377 u8 byte, const char *after = "\n") {
378 PrintMemoryByte(str, before, byte, /*in_shadow*/true, after);
381 static void PrintLegend(InternalScopedString *str) {
383 "Shadow byte legend (one shadow byte represents %d "
384 "application bytes):\n",
385 (int)SHADOW_GRANULARITY);
386 PrintShadowByte(str, " Addressable: ", 0);
387 str->append(" Partially addressable: ");
388 for (u8 i = 1; i < SHADOW_GRANULARITY; i++) PrintShadowByte(str, "", i, " ");
390 PrintShadowByte(str, " Heap left redzone: ",
391 kAsanHeapLeftRedzoneMagic);
392 PrintShadowByte(str, " Freed heap region: ", kAsanHeapFreeMagic);
393 PrintShadowByte(str, " Stack left redzone: ",
394 kAsanStackLeftRedzoneMagic);
395 PrintShadowByte(str, " Stack mid redzone: ",
396 kAsanStackMidRedzoneMagic);
397 PrintShadowByte(str, " Stack right redzone: ",
398 kAsanStackRightRedzoneMagic);
399 PrintShadowByte(str, " Stack after return: ",
400 kAsanStackAfterReturnMagic);
401 PrintShadowByte(str, " Stack use after scope: ",
402 kAsanStackUseAfterScopeMagic);
403 PrintShadowByte(str, " Global redzone: ", kAsanGlobalRedzoneMagic);
404 PrintShadowByte(str, " Global init order: ",
405 kAsanInitializationOrderMagic);
406 PrintShadowByte(str, " Poisoned by user: ",
407 kAsanUserPoisonedMemoryMagic);
408 PrintShadowByte(str, " Container overflow: ",
409 kAsanContiguousContainerOOBMagic);
410 PrintShadowByte(str, " Array cookie: ",
411 kAsanArrayCookieMagic);
412 PrintShadowByte(str, " Intra object redzone: ",
413 kAsanIntraObjectRedzone);
414 PrintShadowByte(str, " ASan internal: ", kAsanInternalHeapMagic);
415 PrintShadowByte(str, " Left alloca redzone: ", kAsanAllocaLeftMagic);
416 PrintShadowByte(str, " Right alloca redzone: ", kAsanAllocaRightMagic);
419 static void PrintShadowBytes(InternalScopedString *str, const char *before,
420 u8 *bytes, u8 *guilty, uptr n) {
422 if (before) str->append("%s%p:", before, bytes);
423 for (uptr i = 0; i < n; i++) {
426 p == guilty ? "[" : (p - 1 == guilty && i != 0) ? "" : " ";
427 const char *after = p == guilty ? "]" : "";
428 PrintShadowByte(str, before, *p, after);
433 static void PrintShadowMemoryForAddress(uptr addr) {
434 if (!AddrIsInMem(addr)) return;
435 uptr shadow_addr = MemToShadow(addr);
436 const uptr n_bytes_per_row = 16;
437 uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1);
438 InternalScopedString str(4096 * 8);
439 str.append("Shadow bytes around the buggy address:\n");
440 for (int i = -5; i <= 5; i++) {
441 uptr row_shadow_addr = aligned_shadow + i * n_bytes_per_row;
442 // Skip rows that would be outside the shadow range. This can happen when
443 // the user address is near the bottom, top, or shadow gap of the address
445 if (!AddrIsInShadow(row_shadow_addr)) continue;
446 const char *prefix = (i == 0) ? "=>" : " ";
447 PrintShadowBytes(&str, prefix, (u8 *)row_shadow_addr, (u8 *)shadow_addr,
450 if (flags()->print_legend) PrintLegend(&str);
451 Printf("%s", str.data());
454 void ErrorGeneric::Print() {
456 Printf("%s", d.Warning());
457 uptr addr = addr_description.Address();
458 Report("ERROR: AddressSanitizer: %s on address %p at pc %p bp %p sp %p\n",
459 bug_descr, (void *)addr, pc, bp, sp);
460 Printf("%s", d.Default());
463 Printf("%s%s of size %zu at %p thread T%d%s%s\n", d.Access(),
464 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS", access_size,
466 ThreadNameWithParenthesis(tid, tname, sizeof(tname)), d.Default());
469 GET_STACK_TRACE_FATAL(pc, bp);
472 // Pass bug_descr because we have a special case for
473 // initialization-order-fiasco
474 addr_description.Print(bug_descr);
475 if (shadow_val == kAsanContiguousContainerOOBMagic)
476 PrintContainerOverflowHint();
477 ReportErrorSummary(bug_descr, &stack);
478 PrintShadowMemoryForAddress(addr);
481 } // namespace __asan