]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/asan/asan_report.cc
Merge compiler-rt trunk r291476.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / asan / asan_report.cc
1 //===-- asan_report.cc ----------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 //
12 // This file contains error reporting code.
13 //===----------------------------------------------------------------------===//
14
15 #include "asan_errors.h"
16 #include "asan_flags.h"
17 #include "asan_descriptions.h"
18 #include "asan_internal.h"
19 #include "asan_mapping.h"
20 #include "asan_report.h"
21 #include "asan_scariness_score.h"
22 #include "asan_stack.h"
23 #include "asan_thread.h"
24 #include "sanitizer_common/sanitizer_common.h"
25 #include "sanitizer_common/sanitizer_flags.h"
26 #include "sanitizer_common/sanitizer_report_decorator.h"
27 #include "sanitizer_common/sanitizer_stackdepot.h"
28 #include "sanitizer_common/sanitizer_symbolizer.h"
29
30 namespace __asan {
31
32 // -------------------- User-specified callbacks ----------------- {{{1
33 static void (*error_report_callback)(const char*);
34 static char *error_message_buffer = nullptr;
35 static uptr error_message_buffer_pos = 0;
36 static BlockingMutex error_message_buf_mutex(LINKER_INITIALIZED);
37 static const unsigned kAsanBuggyPcPoolSize = 25;
38 static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];
39
40 void AppendToErrorMessageBuffer(const char *buffer) {
41   BlockingMutexLock l(&error_message_buf_mutex);
42   if (!error_message_buffer) {
43     error_message_buffer =
44       (char*)MmapOrDieQuietly(kErrorMessageBufferSize, __func__);
45     error_message_buffer_pos = 0;
46   }
47   uptr length = internal_strlen(buffer);
48   RAW_CHECK(kErrorMessageBufferSize >= error_message_buffer_pos);
49   uptr remaining = kErrorMessageBufferSize - error_message_buffer_pos;
50   internal_strncpy(error_message_buffer + error_message_buffer_pos,
51                    buffer, remaining);
52   error_message_buffer[kErrorMessageBufferSize - 1] = '\0';
53   // FIXME: reallocate the buffer instead of truncating the message.
54   error_message_buffer_pos += Min(remaining, length);
55 }
56
57 // ---------------------- Helper functions ----------------------- {{{1
58
59 void PrintMemoryByte(InternalScopedString *str, const char *before, u8 byte,
60                      bool in_shadow, const char *after) {
61   Decorator d;
62   str->append("%s%s%x%x%s%s", before,
63               in_shadow ? d.ShadowByte(byte) : d.MemoryByte(),
64               byte >> 4, byte & 15,
65               in_shadow ? d.EndShadowByte() : d.EndMemoryByte(), after);
66 }
67
68 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
69                                 const char *zone_name) {
70   if (zone_ptr) {
71     if (zone_name) {
72       Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
73                  ptr, zone_ptr, zone_name);
74     } else {
75       Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
76                  ptr, zone_ptr);
77     }
78   } else {
79     Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
80   }
81 }
82
83 // ---------------------- Address Descriptions ------------------- {{{1
84
85 bool ParseFrameDescription(const char *frame_descr,
86                            InternalMmapVector<StackVarDescr> *vars) {
87   CHECK(frame_descr);
88   char *p;
89   // This string is created by the compiler and has the following form:
90   // "n alloc_1 alloc_2 ... alloc_n"
91   // where alloc_i looks like "offset size len ObjectName".
92   uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
93   if (n_objects == 0)
94     return false;
95
96   for (uptr i = 0; i < n_objects; i++) {
97     uptr beg  = (uptr)internal_simple_strtoll(p, &p, 10);
98     uptr size = (uptr)internal_simple_strtoll(p, &p, 10);
99     uptr len  = (uptr)internal_simple_strtoll(p, &p, 10);
100     if (beg == 0 || size == 0 || *p != ' ') {
101       return false;
102     }
103     p++;
104     StackVarDescr var = {beg, size, p, len};
105     vars->push_back(var);
106     p += len;
107   }
108
109   return true;
110 }
111
112 // -------------------- Different kinds of reports ----------------- {{{1
113
114 // Use ScopedInErrorReport to run common actions just before and
115 // immediately after printing error report.
116 class ScopedInErrorReport {
117  public:
118   explicit ScopedInErrorReport(bool fatal = false) {
119     halt_on_error_ = fatal || flags()->halt_on_error;
120
121     if (lock_.TryLock()) {
122       StartReporting();
123       return;
124     }
125
126     // ASan found two bugs in different threads simultaneously.
127
128     u32 current_tid = GetCurrentTidOrInvalid();
129     if (reporting_thread_tid_ == current_tid ||
130         reporting_thread_tid_ == kInvalidTid) {
131       // This is either asynch signal or nested error during error reporting.
132       // Fail simple to avoid deadlocks in Report().
133
134       // Can't use Report() here because of potential deadlocks
135       // in nested signal handlers.
136       const char msg[] = "AddressSanitizer: nested bug in the same thread, "
137                          "aborting.\n";
138       WriteToFile(kStderrFd, msg, sizeof(msg));
139
140       internal__exit(common_flags()->exitcode);
141     }
142
143     if (halt_on_error_) {
144       // Do not print more than one report, otherwise they will mix up.
145       // Error reporting functions shouldn't return at this situation, as
146       // they are effectively no-returns.
147
148       Report("AddressSanitizer: while reporting a bug found another one. "
149              "Ignoring.\n");
150
151       // Sleep long enough to make sure that the thread which started
152       // to print an error report will finish doing it.
153       SleepForSeconds(Max(100, flags()->sleep_before_dying + 1));
154
155       // If we're still not dead for some reason, use raw _exit() instead of
156       // Die() to bypass any additional checks.
157       internal__exit(common_flags()->exitcode);
158     } else {
159       // The other thread will eventually finish reporting
160       // so it's safe to wait
161       lock_.Lock();
162     }
163
164     StartReporting();
165   }
166
167   ~ScopedInErrorReport() {
168     ASAN_ON_ERROR();
169     if (current_error_.IsValid()) current_error_.Print();
170
171     // Make sure the current thread is announced.
172     DescribeThread(GetCurrentThread());
173     // We may want to grab this lock again when printing stats.
174     asanThreadRegistry().Unlock();
175     // Print memory stats.
176     if (flags()->print_stats)
177       __asan_print_accumulated_stats();
178
179     if (common_flags()->print_cmdline)
180       PrintCmdline();
181
182     if (common_flags()->print_module_map == 2) PrintModuleMap();
183
184     // Copy the message buffer so that we could start logging without holding a
185     // lock that gets aquired during printing.
186     InternalScopedBuffer<char> buffer_copy(kErrorMessageBufferSize);
187     {
188       BlockingMutexLock l(&error_message_buf_mutex);
189       internal_memcpy(buffer_copy.data(),
190                       error_message_buffer, kErrorMessageBufferSize);
191     }
192
193     LogFullErrorReport(buffer_copy.data());
194
195     if (error_report_callback) {
196       error_report_callback(buffer_copy.data());
197     }
198
199     // In halt_on_error = false mode, reset the current error object (before
200     // unlocking).
201     if (!halt_on_error_)
202       internal_memset(&current_error_, 0, sizeof(current_error_));
203
204     CommonSanitizerReportMutex.Unlock();
205     reporting_thread_tid_ = kInvalidTid;
206     lock_.Unlock();
207     if (halt_on_error_) {
208       Report("ABORTING\n");
209       Die();
210     }
211   }
212
213   void ReportError(const ErrorDescription &description) {
214     // Can only report one error per ScopedInErrorReport.
215     CHECK_EQ(current_error_.kind, kErrorKindInvalid);
216     current_error_ = description;
217   }
218
219   static ErrorDescription &CurrentError() {
220     return current_error_;
221   }
222
223  private:
224   void StartReporting() {
225     // Make sure the registry and sanitizer report mutexes are locked while
226     // we're printing an error report.
227     // We can lock them only here to avoid self-deadlock in case of
228     // recursive reports.
229     asanThreadRegistry().Lock();
230     CommonSanitizerReportMutex.Lock();
231     reporting_thread_tid_ = GetCurrentTidOrInvalid();
232     Printf("===================================================="
233            "=============\n");
234   }
235
236   static StaticSpinMutex lock_;
237   static u32 reporting_thread_tid_;
238   // Error currently being reported. This enables the destructor to interact
239   // with the debugger and point it to an error description.
240   static ErrorDescription current_error_;
241   bool halt_on_error_;
242 };
243
244 StaticSpinMutex ScopedInErrorReport::lock_;
245 u32 ScopedInErrorReport::reporting_thread_tid_ = kInvalidTid;
246 ErrorDescription ScopedInErrorReport::current_error_;
247
248 void ReportStackOverflow(const SignalContext &sig) {
249   ScopedInErrorReport in_report(/*fatal*/ true);
250   ErrorStackOverflow error(GetCurrentTidOrInvalid(), sig);
251   in_report.ReportError(error);
252 }
253
254 void ReportDeadlySignal(int signo, const SignalContext &sig) {
255   ScopedInErrorReport in_report(/*fatal*/ true);
256   ErrorDeadlySignal error(GetCurrentTidOrInvalid(), sig, signo);
257   in_report.ReportError(error);
258 }
259
260 void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {
261   ScopedInErrorReport in_report;
262   ErrorDoubleFree error(GetCurrentTidOrInvalid(), free_stack, addr);
263   in_report.ReportError(error);
264 }
265
266 void ReportNewDeleteSizeMismatch(uptr addr, uptr delete_size,
267                                  BufferedStackTrace *free_stack) {
268   ScopedInErrorReport in_report;
269   ErrorNewDeleteSizeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
270                                    delete_size);
271   in_report.ReportError(error);
272 }
273
274 void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {
275   ScopedInErrorReport in_report;
276   ErrorFreeNotMalloced error(GetCurrentTidOrInvalid(), free_stack, addr);
277   in_report.ReportError(error);
278 }
279
280 void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,
281                              AllocType alloc_type,
282                              AllocType dealloc_type) {
283   ScopedInErrorReport in_report;
284   ErrorAllocTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
285                                alloc_type, dealloc_type);
286   in_report.ReportError(error);
287 }
288
289 void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {
290   ScopedInErrorReport in_report;
291   ErrorMallocUsableSizeNotOwned error(GetCurrentTidOrInvalid(), stack, addr);
292   in_report.ReportError(error);
293 }
294
295 void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,
296                                              BufferedStackTrace *stack) {
297   ScopedInErrorReport in_report;
298   ErrorSanitizerGetAllocatedSizeNotOwned error(GetCurrentTidOrInvalid(), stack,
299                                                addr);
300   in_report.ReportError(error);
301 }
302
303 void ReportStringFunctionMemoryRangesOverlap(const char *function,
304                                              const char *offset1, uptr length1,
305                                              const char *offset2, uptr length2,
306                                              BufferedStackTrace *stack) {
307   ScopedInErrorReport in_report;
308   ErrorStringFunctionMemoryRangesOverlap error(
309       GetCurrentTidOrInvalid(), stack, (uptr)offset1, length1, (uptr)offset2,
310       length2, function);
311   in_report.ReportError(error);
312 }
313
314 void ReportStringFunctionSizeOverflow(uptr offset, uptr size,
315                                       BufferedStackTrace *stack) {
316   ScopedInErrorReport in_report;
317   ErrorStringFunctionSizeOverflow error(GetCurrentTidOrInvalid(), stack, offset,
318                                         size);
319   in_report.ReportError(error);
320 }
321
322 void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,
323                                                   uptr old_mid, uptr new_mid,
324                                                   BufferedStackTrace *stack) {
325   ScopedInErrorReport in_report;
326   ErrorBadParamsToAnnotateContiguousContainer error(
327       GetCurrentTidOrInvalid(), stack, beg, end, old_mid, new_mid);
328   in_report.ReportError(error);
329 }
330
331 void ReportODRViolation(const __asan_global *g1, u32 stack_id1,
332                         const __asan_global *g2, u32 stack_id2) {
333   ScopedInErrorReport in_report;
334   ErrorODRViolation error(GetCurrentTidOrInvalid(), g1, stack_id1, g2,
335                           stack_id2);
336   in_report.ReportError(error);
337 }
338
339 // ----------------------- CheckForInvalidPointerPair ----------- {{{1
340 static NOINLINE void ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp,
341                                               uptr a1, uptr a2) {
342   ScopedInErrorReport in_report;
343   ErrorInvalidPointerPair error(GetCurrentTidOrInvalid(), pc, bp, sp, a1, a2);
344   in_report.ReportError(error);
345 }
346
347 static INLINE void CheckForInvalidPointerPair(void *p1, void *p2) {
348   if (!flags()->detect_invalid_pointer_pairs) return;
349   uptr a1 = reinterpret_cast<uptr>(p1);
350   uptr a2 = reinterpret_cast<uptr>(p2);
351   AsanChunkView chunk1 = FindHeapChunkByAddress(a1);
352   AsanChunkView chunk2 = FindHeapChunkByAddress(a2);
353   bool valid1 = chunk1.IsAllocated();
354   bool valid2 = chunk2.IsAllocated();
355   if (!valid1 || !valid2 || !chunk1.Eq(chunk2)) {
356     GET_CALLER_PC_BP_SP;
357     return ReportInvalidPointerPair(pc, bp, sp, a1, a2);
358   }
359 }
360 // ----------------------- Mac-specific reports ----------------- {{{1
361
362 void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,
363                                BufferedStackTrace *stack) {
364   ScopedInErrorReport in_report;
365   Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
366              "This is an unrecoverable problem, exiting now.\n",
367              addr);
368   PrintZoneForPointer(addr, zone_ptr, zone_name);
369   stack->Print();
370   DescribeAddressIfHeap(addr);
371 }
372
373 // -------------- SuppressErrorReport -------------- {{{1
374 // Avoid error reports duplicating for ASan recover mode.
375 static bool SuppressErrorReport(uptr pc) {
376   if (!common_flags()->suppress_equal_pcs) return false;
377   for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {
378     uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);
379     if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,
380                                                    pc, memory_order_relaxed))
381       return false;
382     if (cmp == pc) return true;
383   }
384   Die();
385 }
386
387 void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,
388                         uptr access_size, u32 exp, bool fatal) {
389   if (!fatal && SuppressErrorReport(pc)) return;
390   ENABLE_FRAME_POINTER;
391
392   // Optimization experiments.
393   // The experiments can be used to evaluate potential optimizations that remove
394   // instrumentation (assess false negatives). Instead of completely removing
395   // some instrumentation, compiler can emit special calls into runtime
396   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass
397   // mask of experiments (exp).
398   // The reaction to a non-zero value of exp is to be defined.
399   (void)exp;
400
401   ScopedInErrorReport in_report(fatal);
402   ErrorGeneric error(GetCurrentTidOrInvalid(), pc, bp, sp, addr, is_write,
403                      access_size);
404   in_report.ReportError(error);
405 }
406
407 }  // namespace __asan
408
409 // --------------------------- Interface --------------------- {{{1
410 using namespace __asan;  // NOLINT
411
412 void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
413                          uptr access_size, u32 exp) {
414   ENABLE_FRAME_POINTER;
415   bool fatal = flags()->halt_on_error;
416   ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);
417 }
418
419 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
420   BlockingMutexLock l(&error_message_buf_mutex);
421   error_report_callback = callback;
422 }
423
424 void __asan_describe_address(uptr addr) {
425   // Thread registry must be locked while we're describing an address.
426   asanThreadRegistry().Lock();
427   PrintAddressDescription(addr, 1, "");
428   asanThreadRegistry().Unlock();
429 }
430
431 int __asan_report_present() {
432   return ScopedInErrorReport::CurrentError().kind != kErrorKindInvalid;
433 }
434
435 uptr __asan_get_report_pc() {
436   if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
437     return ScopedInErrorReport::CurrentError().Generic.pc;
438   return 0;
439 }
440
441 uptr __asan_get_report_bp() {
442   if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
443     return ScopedInErrorReport::CurrentError().Generic.bp;
444   return 0;
445 }
446
447 uptr __asan_get_report_sp() {
448   if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
449     return ScopedInErrorReport::CurrentError().Generic.sp;
450   return 0;
451 }
452
453 uptr __asan_get_report_address() {
454   ErrorDescription &err = ScopedInErrorReport::CurrentError();
455   if (err.kind == kErrorKindGeneric)
456     return err.Generic.addr_description.Address();
457   else if (err.kind == kErrorKindDoubleFree)
458     return err.DoubleFree.addr_description.addr;
459   return 0;
460 }
461
462 int __asan_get_report_access_type() {
463   if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
464     return ScopedInErrorReport::CurrentError().Generic.is_write;
465   return 0;
466 }
467
468 uptr __asan_get_report_access_size() {
469   if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
470     return ScopedInErrorReport::CurrentError().Generic.access_size;
471   return 0;
472 }
473
474 const char *__asan_get_report_description() {
475   if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
476     return ScopedInErrorReport::CurrentError().Generic.bug_descr;
477   return ScopedInErrorReport::CurrentError().Base.scariness.GetDescription();
478 }
479
480 extern "C" {
481 SANITIZER_INTERFACE_ATTRIBUTE
482 void __sanitizer_ptr_sub(void *a, void *b) {
483   CheckForInvalidPointerPair(a, b);
484 }
485 SANITIZER_INTERFACE_ATTRIBUTE
486 void __sanitizer_ptr_cmp(void *a, void *b) {
487   CheckForInvalidPointerPair(a, b);
488 }
489 } // extern "C"
490
491 #if !SANITIZER_SUPPORTS_WEAK_HOOKS
492 // Provide default implementation of __asan_on_error that does nothing
493 // and may be overriden by user.
494 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE
495 void __asan_on_error() {}
496 #endif