xfail experimental/memory_resource/resource_adaptor.cc on 32-bit Solaris/x86 (PR...
[official-gcc.git] / libsanitizer / asan / asan_report.cc
blob434aa734c8fec7169b6e6156a66f1f12af979f88
1 //===-- asan_report.cc ----------------------------------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // This file contains error reporting code.
11 //===----------------------------------------------------------------------===//
13 #include "asan_errors.h"
14 #include "asan_flags.h"
15 #include "asan_descriptions.h"
16 #include "asan_internal.h"
17 #include "asan_mapping.h"
18 #include "asan_report.h"
19 #include "asan_scariness_score.h"
20 #include "asan_stack.h"
21 #include "asan_thread.h"
22 #include "sanitizer_common/sanitizer_common.h"
23 #include "sanitizer_common/sanitizer_flags.h"
24 #include "sanitizer_common/sanitizer_report_decorator.h"
25 #include "sanitizer_common/sanitizer_stackdepot.h"
26 #include "sanitizer_common/sanitizer_symbolizer.h"
28 namespace __asan {
30 // -------------------- User-specified callbacks ----------------- {{{1
31 static void (*error_report_callback)(const char*);
32 static char *error_message_buffer = nullptr;
33 static uptr error_message_buffer_pos = 0;
34 static BlockingMutex error_message_buf_mutex(LINKER_INITIALIZED);
35 static const unsigned kAsanBuggyPcPoolSize = 25;
36 static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];
38 void AppendToErrorMessageBuffer(const char *buffer) {
39 BlockingMutexLock l(&error_message_buf_mutex);
40 if (!error_message_buffer) {
41 error_message_buffer =
42 (char*)MmapOrDieQuietly(kErrorMessageBufferSize, __func__);
43 error_message_buffer_pos = 0;
45 uptr length = internal_strlen(buffer);
46 RAW_CHECK(kErrorMessageBufferSize >= error_message_buffer_pos);
47 uptr remaining = kErrorMessageBufferSize - error_message_buffer_pos;
48 internal_strncpy(error_message_buffer + error_message_buffer_pos,
49 buffer, remaining);
50 error_message_buffer[kErrorMessageBufferSize - 1] = '\0';
51 // FIXME: reallocate the buffer instead of truncating the message.
52 error_message_buffer_pos += Min(remaining, length);
55 // ---------------------- Helper functions ----------------------- {{{1
57 void PrintMemoryByte(InternalScopedString *str, const char *before, u8 byte,
58 bool in_shadow, const char *after) {
59 Decorator d;
60 str->append("%s%s%x%x%s%s", before,
61 in_shadow ? d.ShadowByte(byte) : d.MemoryByte(), byte >> 4,
62 byte & 15, d.Default(), after);
65 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
66 const char *zone_name) {
67 if (zone_ptr) {
68 if (zone_name) {
69 Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n",
70 ptr, zone_ptr, zone_name);
71 } else {
72 Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
73 ptr, zone_ptr);
75 } else {
76 Printf("malloc_zone_from_ptr(%p) = 0\n", ptr);
80 // ---------------------- Address Descriptions ------------------- {{{1
82 bool ParseFrameDescription(const char *frame_descr,
83 InternalMmapVector<StackVarDescr> *vars) {
84 CHECK(frame_descr);
85 char *p;
86 // This string is created by the compiler and has the following form:
87 // "n alloc_1 alloc_2 ... alloc_n"
88 // where alloc_i looks like "offset size len ObjectName"
89 // or "offset size len ObjectName:line".
90 uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
91 if (n_objects == 0)
92 return false;
94 for (uptr i = 0; i < n_objects; i++) {
95 uptr beg = (uptr)internal_simple_strtoll(p, &p, 10);
96 uptr size = (uptr)internal_simple_strtoll(p, &p, 10);
97 uptr len = (uptr)internal_simple_strtoll(p, &p, 10);
98 if (beg == 0 || size == 0 || *p != ' ') {
99 return false;
101 p++;
102 char *colon_pos = internal_strchr(p, ':');
103 uptr line = 0;
104 uptr name_len = len;
105 if (colon_pos != nullptr && colon_pos < p + len) {
106 name_len = colon_pos - p;
107 line = (uptr)internal_simple_strtoll(colon_pos + 1, nullptr, 10);
109 StackVarDescr var = {beg, size, p, name_len, line};
110 vars->push_back(var);
111 p += len;
114 return true;
117 // -------------------- Different kinds of reports ----------------- {{{1
119 // Use ScopedInErrorReport to run common actions just before and
120 // immediately after printing error report.
121 class ScopedInErrorReport {
122 public:
123 explicit ScopedInErrorReport(bool fatal = false)
124 : halt_on_error_(fatal || flags()->halt_on_error) {
125 // Make sure the registry and sanitizer report mutexes are locked while
126 // we're printing an error report.
127 // We can lock them only here to avoid self-deadlock in case of
128 // recursive reports.
129 asanThreadRegistry().Lock();
130 Printf(
131 "=================================================================\n");
134 ~ScopedInErrorReport() {
135 ASAN_ON_ERROR();
136 if (current_error_.IsValid()) current_error_.Print();
138 // Make sure the current thread is announced.
139 DescribeThread(GetCurrentThread());
140 // We may want to grab this lock again when printing stats.
141 asanThreadRegistry().Unlock();
142 // Print memory stats.
143 if (flags()->print_stats)
144 __asan_print_accumulated_stats();
146 if (common_flags()->print_cmdline)
147 PrintCmdline();
149 if (common_flags()->print_module_map == 2) PrintModuleMap();
151 // Copy the message buffer so that we could start logging without holding a
152 // lock that gets aquired during printing.
153 InternalScopedBuffer<char> buffer_copy(kErrorMessageBufferSize);
155 BlockingMutexLock l(&error_message_buf_mutex);
156 internal_memcpy(buffer_copy.data(),
157 error_message_buffer, kErrorMessageBufferSize);
160 LogFullErrorReport(buffer_copy.data());
162 if (error_report_callback) {
163 error_report_callback(buffer_copy.data());
166 if (halt_on_error_ && common_flags()->abort_on_error) {
167 // On Android the message is truncated to 512 characters.
168 // FIXME: implement "compact" error format, possibly without, or with
169 // highly compressed stack traces?
170 // FIXME: or just use the summary line as abort message?
171 SetAbortMessage(buffer_copy.data());
174 // In halt_on_error = false mode, reset the current error object (before
175 // unlocking).
176 if (!halt_on_error_)
177 internal_memset(&current_error_, 0, sizeof(current_error_));
179 if (halt_on_error_) {
180 Report("ABORTING\n");
181 Die();
185 void ReportError(const ErrorDescription &description) {
186 // Can only report one error per ScopedInErrorReport.
187 CHECK_EQ(current_error_.kind, kErrorKindInvalid);
188 current_error_ = description;
191 static ErrorDescription &CurrentError() {
192 return current_error_;
195 private:
196 ScopedErrorReportLock error_report_lock_;
197 // Error currently being reported. This enables the destructor to interact
198 // with the debugger and point it to an error description.
199 static ErrorDescription current_error_;
200 bool halt_on_error_;
203 ErrorDescription ScopedInErrorReport::current_error_;
205 void ReportDeadlySignal(const SignalContext &sig) {
206 ScopedInErrorReport in_report(/*fatal*/ true);
207 ErrorDeadlySignal error(GetCurrentTidOrInvalid(), sig);
208 in_report.ReportError(error);
211 void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {
212 ScopedInErrorReport in_report;
213 ErrorDoubleFree error(GetCurrentTidOrInvalid(), free_stack, addr);
214 in_report.ReportError(error);
217 void ReportNewDeleteSizeMismatch(uptr addr, uptr delete_size,
218 BufferedStackTrace *free_stack) {
219 ScopedInErrorReport in_report;
220 ErrorNewDeleteSizeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
221 delete_size);
222 in_report.ReportError(error);
225 void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {
226 ScopedInErrorReport in_report;
227 ErrorFreeNotMalloced error(GetCurrentTidOrInvalid(), free_stack, addr);
228 in_report.ReportError(error);
231 void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,
232 AllocType alloc_type,
233 AllocType dealloc_type) {
234 ScopedInErrorReport in_report;
235 ErrorAllocTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
236 alloc_type, dealloc_type);
237 in_report.ReportError(error);
240 void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {
241 ScopedInErrorReport in_report;
242 ErrorMallocUsableSizeNotOwned error(GetCurrentTidOrInvalid(), stack, addr);
243 in_report.ReportError(error);
246 void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,
247 BufferedStackTrace *stack) {
248 ScopedInErrorReport in_report;
249 ErrorSanitizerGetAllocatedSizeNotOwned error(GetCurrentTidOrInvalid(), stack,
250 addr);
251 in_report.ReportError(error);
254 void ReportStringFunctionMemoryRangesOverlap(const char *function,
255 const char *offset1, uptr length1,
256 const char *offset2, uptr length2,
257 BufferedStackTrace *stack) {
258 ScopedInErrorReport in_report;
259 ErrorStringFunctionMemoryRangesOverlap error(
260 GetCurrentTidOrInvalid(), stack, (uptr)offset1, length1, (uptr)offset2,
261 length2, function);
262 in_report.ReportError(error);
265 void ReportStringFunctionSizeOverflow(uptr offset, uptr size,
266 BufferedStackTrace *stack) {
267 ScopedInErrorReport in_report;
268 ErrorStringFunctionSizeOverflow error(GetCurrentTidOrInvalid(), stack, offset,
269 size);
270 in_report.ReportError(error);
273 void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,
274 uptr old_mid, uptr new_mid,
275 BufferedStackTrace *stack) {
276 ScopedInErrorReport in_report;
277 ErrorBadParamsToAnnotateContiguousContainer error(
278 GetCurrentTidOrInvalid(), stack, beg, end, old_mid, new_mid);
279 in_report.ReportError(error);
282 void ReportODRViolation(const __asan_global *g1, u32 stack_id1,
283 const __asan_global *g2, u32 stack_id2) {
284 ScopedInErrorReport in_report;
285 ErrorODRViolation error(GetCurrentTidOrInvalid(), g1, stack_id1, g2,
286 stack_id2);
287 in_report.ReportError(error);
290 // ----------------------- CheckForInvalidPointerPair ----------- {{{1
291 static NOINLINE void ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp,
292 uptr a1, uptr a2) {
293 ScopedInErrorReport in_report;
294 ErrorInvalidPointerPair error(GetCurrentTidOrInvalid(), pc, bp, sp, a1, a2);
295 in_report.ReportError(error);
298 static bool IsInvalidPointerPair(uptr a1, uptr a2) {
299 if (a1 == a2)
300 return false;
302 // 256B in shadow memory can be iterated quite fast
303 static const uptr kMaxOffset = 2048;
305 uptr left = a1 < a2 ? a1 : a2;
306 uptr right = a1 < a2 ? a2 : a1;
307 uptr offset = right - left;
308 if (offset <= kMaxOffset)
309 return __asan_region_is_poisoned(left, offset);
311 AsanThread *t = GetCurrentThread();
313 // check whether left is a stack memory pointer
314 if (uptr shadow_offset1 = t->GetStackVariableShadowStart(left)) {
315 uptr shadow_offset2 = t->GetStackVariableShadowStart(right);
316 return shadow_offset2 == 0 || shadow_offset1 != shadow_offset2;
319 // check whether left is a heap memory address
320 HeapAddressDescription hdesc1, hdesc2;
321 if (GetHeapAddressInformation(left, 0, &hdesc1) &&
322 hdesc1.chunk_access.access_type == kAccessTypeInside)
323 return !GetHeapAddressInformation(right, 0, &hdesc2) ||
324 hdesc2.chunk_access.access_type != kAccessTypeInside ||
325 hdesc1.chunk_access.chunk_begin != hdesc2.chunk_access.chunk_begin;
327 // check whether left is an address of a global variable
328 GlobalAddressDescription gdesc1, gdesc2;
329 if (GetGlobalAddressInformation(left, 0, &gdesc1))
330 return !GetGlobalAddressInformation(right - 1, 0, &gdesc2) ||
331 !gdesc1.PointsInsideTheSameVariable(gdesc2);
333 if (t->GetStackVariableShadowStart(right) ||
334 GetHeapAddressInformation(right, 0, &hdesc2) ||
335 GetGlobalAddressInformation(right - 1, 0, &gdesc2))
336 return true;
338 // At this point we know nothing about both a1 and a2 addresses.
339 return false;
342 static INLINE void CheckForInvalidPointerPair(void *p1, void *p2) {
343 switch (flags()->detect_invalid_pointer_pairs) {
344 case 0 : return;
345 case 1 : if (p1 == nullptr || p2 == nullptr) return; break;
348 uptr a1 = reinterpret_cast<uptr>(p1);
349 uptr a2 = reinterpret_cast<uptr>(p2);
351 if (IsInvalidPointerPair(a1, a2)) {
352 GET_CALLER_PC_BP_SP;
353 ReportInvalidPointerPair(pc, bp, sp, a1, a2);
356 // ----------------------- Mac-specific reports ----------------- {{{1
358 void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,
359 BufferedStackTrace *stack) {
360 ScopedInErrorReport in_report;
361 Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
362 "This is an unrecoverable problem, exiting now.\n",
363 addr);
364 PrintZoneForPointer(addr, zone_ptr, zone_name);
365 stack->Print();
366 DescribeAddressIfHeap(addr);
369 // -------------- SuppressErrorReport -------------- {{{1
370 // Avoid error reports duplicating for ASan recover mode.
371 static bool SuppressErrorReport(uptr pc) {
372 if (!common_flags()->suppress_equal_pcs) return false;
373 for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {
374 uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);
375 if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,
376 pc, memory_order_relaxed))
377 return false;
378 if (cmp == pc) return true;
380 Die();
383 void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,
384 uptr access_size, u32 exp, bool fatal) {
385 if (!fatal && SuppressErrorReport(pc)) return;
386 ENABLE_FRAME_POINTER;
388 // Optimization experiments.
389 // The experiments can be used to evaluate potential optimizations that remove
390 // instrumentation (assess false negatives). Instead of completely removing
391 // some instrumentation, compiler can emit special calls into runtime
392 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass
393 // mask of experiments (exp).
394 // The reaction to a non-zero value of exp is to be defined.
395 (void)exp;
397 ScopedInErrorReport in_report(fatal);
398 ErrorGeneric error(GetCurrentTidOrInvalid(), pc, bp, sp, addr, is_write,
399 access_size);
400 in_report.ReportError(error);
403 } // namespace __asan
405 // --------------------------- Interface --------------------- {{{1
406 using namespace __asan; // NOLINT
408 void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
409 uptr access_size, u32 exp) {
410 ENABLE_FRAME_POINTER;
411 bool fatal = flags()->halt_on_error;
412 ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);
415 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
416 BlockingMutexLock l(&error_message_buf_mutex);
417 error_report_callback = callback;
420 void __asan_describe_address(uptr addr) {
421 // Thread registry must be locked while we're describing an address.
422 asanThreadRegistry().Lock();
423 PrintAddressDescription(addr, 1, "");
424 asanThreadRegistry().Unlock();
427 int __asan_report_present() {
428 return ScopedInErrorReport::CurrentError().kind != kErrorKindInvalid;
431 uptr __asan_get_report_pc() {
432 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
433 return ScopedInErrorReport::CurrentError().Generic.pc;
434 return 0;
437 uptr __asan_get_report_bp() {
438 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
439 return ScopedInErrorReport::CurrentError().Generic.bp;
440 return 0;
443 uptr __asan_get_report_sp() {
444 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
445 return ScopedInErrorReport::CurrentError().Generic.sp;
446 return 0;
449 uptr __asan_get_report_address() {
450 ErrorDescription &err = ScopedInErrorReport::CurrentError();
451 if (err.kind == kErrorKindGeneric)
452 return err.Generic.addr_description.Address();
453 else if (err.kind == kErrorKindDoubleFree)
454 return err.DoubleFree.addr_description.addr;
455 return 0;
458 int __asan_get_report_access_type() {
459 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
460 return ScopedInErrorReport::CurrentError().Generic.is_write;
461 return 0;
464 uptr __asan_get_report_access_size() {
465 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
466 return ScopedInErrorReport::CurrentError().Generic.access_size;
467 return 0;
470 const char *__asan_get_report_description() {
471 if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
472 return ScopedInErrorReport::CurrentError().Generic.bug_descr;
473 return ScopedInErrorReport::CurrentError().Base.scariness.GetDescription();
476 extern "C" {
477 SANITIZER_INTERFACE_ATTRIBUTE
478 void __sanitizer_ptr_sub(void *a, void *b) {
479 CheckForInvalidPointerPair(a, b);
481 SANITIZER_INTERFACE_ATTRIBUTE
482 void __sanitizer_ptr_cmp(void *a, void *b) {
483 CheckForInvalidPointerPair(a, b);
485 } // extern "C"
487 // Provide default implementation of __asan_on_error that does nothing
488 // and may be overriden by user.
489 SANITIZER_INTERFACE_WEAK_DEF(void, __asan_on_error, void) {}