]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_errors.cc
Merge compiler-rt trunk r321017 to contrib/compiler-rt.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_errors.cc
1 //===-- asan_errors.cc ------------------------------------------*- C++ -*-===//
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 // ASan implementation for error structures.
13 //===----------------------------------------------------------------------===//
14
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"
21
22 namespace __asan {
23
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).
32   fast = true;
33 #endif
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
37   // print it.
38   static_cast<const ScarinessScoreBase *>(callback_context)->Print();
39   GetStackTrace(stack, kStackTraceMax, sig.pc, sig.bp, sig.context, fast);
40 }
41
42 void ErrorDeadlySignal::Print() {
43   ReportDeadlySignal(signal, tid, &OnStackUnwind, &scariness);
44 }
45
46 void ErrorDoubleFree::Print() {
47   Decorator d;
48   Printf("%s", d.Warning());
49   char tname[128];
50   Report(
51       "ERROR: AddressSanitizer: attempting %s on %p in "
52       "thread T%d%s:\n",
53       scariness.GetDescription(), addr_description.addr, tid,
54       ThreadNameWithParenthesis(tid, tname, sizeof(tname)));
55   Printf("%s", d.Default());
56   scariness.Print();
57   GET_STACK_TRACE_FATAL(second_free_stack->trace[0],
58                         second_free_stack->top_frame_bp);
59   stack.Print();
60   addr_description.Print();
61   ReportErrorSummary(scariness.GetDescription(), &stack);
62 }
63
64 void ErrorNewDeleteTypeMismatch::Print() {
65   Decorator d;
66   Printf("%s", d.Warning());
67   char tname[128];
68   Report(
69       "ERROR: AddressSanitizer: %s on %p in thread "
70       "T%d%s:\n",
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) {
75     Printf(
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);
79   }
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";
90     Printf(
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);
95   }
96   CHECK_GT(free_stack->size, 0);
97   scariness.Print();
98   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
99   stack.Print();
100   addr_description.Print();
101   ReportErrorSummary(scariness.GetDescription(), &stack);
102   Report(
103       "HINT: if you don't care about these errors you may set "
104       "ASAN_OPTIONS=new_delete_type_mismatch=0\n");
105 }
106
107 void ErrorFreeNotMalloced::Print() {
108   Decorator d;
109   Printf("%s", d.Warning());
110   char tname[128];
111   Report(
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);
118   scariness.Print();
119   GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp);
120   stack.Print();
121   addr_description.Print();
122   ReportErrorSummary(scariness.GetDescription(), &stack);
123 }
124
125 void ErrorAllocTypeMismatch::Print() {
126   static const char *alloc_names[] = {"INVALID", "malloc", "operator new",
127                                       "operator new []"};
128   static const char *dealloc_names[] = {"INVALID", "free", "operator delete",
129                                         "operator delete []"};
130   CHECK_NE(alloc_type, dealloc_type);
131   Decorator d;
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);
139   scariness.Print();
140   GET_STACK_TRACE_FATAL(dealloc_stack->trace[0], dealloc_stack->top_frame_bp);
141   stack.Print();
142   addr_description.Print();
143   ReportErrorSummary(scariness.GetDescription(), &stack);
144   Report(
145       "HINT: if you don't care about these errors you may set "
146       "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n");
147 }
148
149 void ErrorMallocUsableSizeNotOwned::Print() {
150   Decorator d;
151   Printf("%s", d.Warning());
152   Report(
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());
157   stack->Print();
158   addr_description.Print();
159   ReportErrorSummary(scariness.GetDescription(), stack);
160 }
161
162 void ErrorSanitizerGetAllocatedSizeNotOwned::Print() {
163   Decorator d;
164   Printf("%s", d.Warning());
165   Report(
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());
170   stack->Print();
171   addr_description.Print();
172   ReportErrorSummary(scariness.GetDescription(), stack);
173 }
174
175 void ErrorStringFunctionMemoryRangesOverlap::Print() {
176   Decorator d;
177   char bug_type[100];
178   internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function);
179   Printf("%s", d.Warning());
180   Report(
181       "ERROR: AddressSanitizer: %s: memory ranges [%p,%p) and [%p, %p) "
182       "overlap\n",
183       bug_type, addr1_description.Address(),
184       addr1_description.Address() + length1, addr2_description.Address(),
185       addr2_description.Address() + length2);
186   Printf("%s", d.Default());
187   scariness.Print();
188   stack->Print();
189   addr1_description.Print();
190   addr2_description.Print();
191   ReportErrorSummary(bug_type, stack);
192 }
193
194 void ErrorStringFunctionSizeOverflow::Print() {
195   Decorator d;
196   Printf("%s", d.Warning());
197   Report("ERROR: AddressSanitizer: %s: (size=%zd)\n",
198          scariness.GetDescription(), size);
199   Printf("%s", d.Default());
200   scariness.Print();
201   stack->Print();
202   addr_description.Print();
203   ReportErrorSummary(scariness.GetDescription(), stack);
204 }
205
206 void ErrorBadParamsToAnnotateContiguousContainer::Print() {
207   Report(
208       "ERROR: AddressSanitizer: bad parameters to "
209       "__sanitizer_annotate_contiguous_container:\n"
210       "      beg     : %p\n"
211       "      end     : %p\n"
212       "      old_mid : %p\n"
213       "      new_mid : %p\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);
218   stack->Print();
219   ReportErrorSummary(scariness.GetDescription(), stack);
220 }
221
222 void ErrorODRViolation::Print() {
223   Decorator d;
224   Printf("%s", d.Warning());
225   Report("ERROR: AddressSanitizer: %s (%p):\n", scariness.GetDescription(),
226          global1.beg);
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");
237     Printf("  [1]:\n");
238     StackDepotGet(stack_id1).Print();
239     Printf("  [2]:\n");
240     StackDepotGet(stack_id2).Print();
241   }
242   Report(
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());
249 }
250
251 void ErrorInvalidPointerPair::Print() {
252   Decorator d;
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);
258   stack.Print();
259   addr1_description.Print();
260   addr2_description.Print();
261   ReportErrorSummary(scariness.GetDescription(), &stack);
262 }
263
264 static bool AdjacentShadowValuesAreFullyPoisoned(u8 *s) {
265   return s[-1] > 127 && s[1] > 127;
266 }
267
268 ErrorGeneric::ErrorGeneric(u32 tid, uptr pc_, uptr bp_, uptr sp_, uptr addr,
269                            bool is_write_, uptr access_size_)
270     : ErrorBase(tid),
271       addr_description(addr, access_size_, /*shouldLockThreadRegistry=*/false),
272       pc(pc_),
273       bp(bp_),
274       sp(sp_),
275       access_size(access_size_),
276       is_write(is_write_),
277       shadow_val(0) {
278   scariness.Clear();
279   if (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");
286     }
287     is_write ? scariness.Scare(20, "write") : scariness.Scare(1, "read");
288
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";
306           bug_type_score = 10;
307           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
308           break;
309         case kAsanHeapFreeMagic:
310           bug_descr = "heap-use-after-free";
311           bug_type_score = 20;
312           if (!is_write) read_after_free_bonus = 18;
313           break;
314         case kAsanStackLeftRedzoneMagic:
315           bug_descr = "stack-buffer-underflow";
316           bug_type_score = 25;
317           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
318           break;
319         case kAsanInitializationOrderMagic:
320           bug_descr = "initialization-order-fiasco";
321           bug_type_score = 1;
322           break;
323         case kAsanStackMidRedzoneMagic:
324         case kAsanStackRightRedzoneMagic:
325           bug_descr = "stack-buffer-overflow";
326           bug_type_score = 25;
327           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
328           break;
329         case kAsanStackAfterReturnMagic:
330           bug_descr = "stack-use-after-return";
331           bug_type_score = 30;
332           if (!is_write) read_after_free_bonus = 18;
333           break;
334         case kAsanUserPoisonedMemoryMagic:
335           bug_descr = "use-after-poison";
336           bug_type_score = 20;
337           break;
338         case kAsanContiguousContainerOOBMagic:
339           bug_descr = "container-overflow";
340           bug_type_score = 10;
341           break;
342         case kAsanStackUseAfterScopeMagic:
343           bug_descr = "stack-use-after-scope";
344           bug_type_score = 10;
345           break;
346         case kAsanGlobalRedzoneMagic:
347           bug_descr = "global-buffer-overflow";
348           bug_type_score = 10;
349           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
350           break;
351         case kAsanIntraObjectRedzone:
352           bug_descr = "intra-object-overflow";
353           bug_type_score = 10;
354           break;
355         case kAsanAllocaLeftMagic:
356         case kAsanAllocaRightMagic:
357           bug_descr = "dynamic-stack-buffer-overflow";
358           bug_type_score = 25;
359           far_from_bounds = AdjacentShadowValuesAreFullyPoisoned(shadow_addr);
360           break;
361       }
362       scariness.Scare(bug_type_score + read_after_free_bonus, bug_descr);
363       if (far_from_bounds) scariness.Scare(10, "far-from-bounds");
364     }
365   }
366 }
367
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");
374 }
375
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);
379 }
380
381 static void PrintLegend(InternalScopedString *str) {
382   str->append(
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, " ");
389   str->append("\n");
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);
417 }
418
419 static void PrintShadowBytes(InternalScopedString *str, const char *before,
420                              u8 *bytes, u8 *guilty, uptr n) {
421   Decorator d;
422   if (before) str->append("%s%p:", before, bytes);
423   for (uptr i = 0; i < n; i++) {
424     u8 *p = bytes + i;
425     const char *before =
426         p == guilty ? "[" : (p - 1 == guilty && i != 0) ? "" : " ";
427     const char *after = p == guilty ? "]" : "";
428     PrintShadowByte(str, before, *p, after);
429   }
430   str->append("\n");
431 }
432
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
444     // space.
445     if (!AddrIsInShadow(row_shadow_addr)) continue;
446     const char *prefix = (i == 0) ? "=>" : "  ";
447     PrintShadowBytes(&str, prefix, (u8 *)row_shadow_addr, (u8 *)shadow_addr,
448                      n_bytes_per_row);
449   }
450   if (flags()->print_legend) PrintLegend(&str);
451   Printf("%s", str.data());
452 }
453
454 void ErrorGeneric::Print() {
455   Decorator d;
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());
461
462   char tname[128];
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,
465          (void *)addr, tid,
466          ThreadNameWithParenthesis(tid, tname, sizeof(tname)), d.Default());
467
468   scariness.Print();
469   GET_STACK_TRACE_FATAL(pc, bp);
470   stack.Print();
471
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);
479 }
480
481 }  // namespace __asan