llvm-project
586 строк · 20.9 Кб
1//===-- asan_report.cpp ---------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file is a part of AddressSanitizer, an address sanity checker.
10//
11// This file contains error reporting code.
12//===----------------------------------------------------------------------===//
13
14#include "asan_report.h"
15
16#include "asan_descriptions.h"
17#include "asan_errors.h"
18#include "asan_flags.h"
19#include "asan_internal.h"
20#include "asan_mapping.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_interface_internal.h"
27#include "sanitizer_common/sanitizer_placement_new.h"
28#include "sanitizer_common/sanitizer_report_decorator.h"
29#include "sanitizer_common/sanitizer_stackdepot.h"
30#include "sanitizer_common/sanitizer_symbolizer.h"
31
32namespace __asan {
33
34// -------------------- User-specified callbacks ----------------- {{{1
35static void (*error_report_callback)(const char*);
36using ErrorMessageBuffer = InternalMmapVectorNoCtor<char, true>;
37static ALIGNED(
38alignof(ErrorMessageBuffer)) char error_message_buffer_placeholder
39[sizeof(ErrorMessageBuffer)];
40static ErrorMessageBuffer *error_message_buffer = nullptr;
41static Mutex error_message_buf_mutex;
42static const unsigned kAsanBuggyPcPoolSize = 25;
43static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];
44
45void AppendToErrorMessageBuffer(const char *buffer) {
46Lock l(&error_message_buf_mutex);
47if (!error_message_buffer) {
48error_message_buffer =
49new (error_message_buffer_placeholder) ErrorMessageBuffer();
50error_message_buffer->Initialize(kErrorMessageBufferSize);
51}
52uptr error_message_buffer_len = error_message_buffer->size();
53uptr buffer_len = internal_strlen(buffer);
54error_message_buffer->resize(error_message_buffer_len + buffer_len);
55internal_memcpy(error_message_buffer->data() + error_message_buffer_len,
56buffer, buffer_len);
57}
58
59// ---------------------- Helper functions ----------------------- {{{1
60
61void PrintMemoryByte(InternalScopedString *str, const char *before, u8 byte,
62bool in_shadow, const char *after) {
63Decorator d;
64str->AppendF("%s%s%x%x%s%s", before,
65in_shadow ? d.ShadowByte(byte) : d.MemoryByte(), byte >> 4,
66byte & 15, d.Default(), after);
67}
68
69static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,
70const char *zone_name) {
71if (zone_ptr) {
72if (zone_name) {
73Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n", (void *)ptr,
74(void *)zone_ptr, zone_name);
75} else {
76Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",
77(void *)ptr, (void *)zone_ptr);
78}
79} else {
80Printf("malloc_zone_from_ptr(%p) = 0\n", (void *)ptr);
81}
82}
83
84// ---------------------- Address Descriptions ------------------- {{{1
85
86bool ParseFrameDescription(const char *frame_descr,
87InternalMmapVector<StackVarDescr> *vars) {
88CHECK(frame_descr);
89const char *p;
90// This string is created by the compiler and has the following form:
91// "n alloc_1 alloc_2 ... alloc_n"
92// where alloc_i looks like "offset size len ObjectName"
93// or "offset size len ObjectName:line".
94uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);
95if (n_objects == 0)
96return false;
97
98for (uptr i = 0; i < n_objects; i++) {
99uptr beg = (uptr)internal_simple_strtoll(p, &p, 10);
100uptr size = (uptr)internal_simple_strtoll(p, &p, 10);
101uptr len = (uptr)internal_simple_strtoll(p, &p, 10);
102if (beg == 0 || size == 0 || *p != ' ') {
103return false;
104}
105p++;
106char *colon_pos = internal_strchr(p, ':');
107uptr line = 0;
108uptr name_len = len;
109if (colon_pos != nullptr && colon_pos < p + len) {
110name_len = colon_pos - p;
111line = (uptr)internal_simple_strtoll(colon_pos + 1, nullptr, 10);
112}
113StackVarDescr var = {beg, size, p, name_len, line};
114vars->push_back(var);
115p += len;
116}
117
118return true;
119}
120
121// -------------------- Different kinds of reports ----------------- {{{1
122
123// Use ScopedInErrorReport to run common actions just before and
124// immediately after printing error report.
125class ScopedInErrorReport {
126public:
127explicit ScopedInErrorReport(bool fatal = false)
128: halt_on_error_(fatal || flags()->halt_on_error) {
129// Make sure the registry and sanitizer report mutexes are locked while
130// we're printing an error report.
131// We can lock them only here to avoid self-deadlock in case of
132// recursive reports.
133asanThreadRegistry().Lock();
134Printf(
135"=================================================================\n");
136}
137
138~ScopedInErrorReport() {
139if (halt_on_error_ && !__sanitizer_acquire_crash_state()) {
140asanThreadRegistry().Unlock();
141return;
142}
143ASAN_ON_ERROR();
144if (current_error_.IsValid()) current_error_.Print();
145
146// Make sure the current thread is announced.
147DescribeThread(GetCurrentThread());
148// We may want to grab this lock again when printing stats.
149asanThreadRegistry().Unlock();
150// Print memory stats.
151if (flags()->print_stats)
152__asan_print_accumulated_stats();
153
154if (common_flags()->print_cmdline)
155PrintCmdline();
156
157if (common_flags()->print_module_map == 2)
158DumpProcessMap();
159
160// Copy the message buffer so that we could start logging without holding a
161// lock that gets acquired during printing.
162InternalScopedString buffer_copy;
163{
164Lock l(&error_message_buf_mutex);
165error_message_buffer->push_back('\0');
166buffer_copy.Append(error_message_buffer->data());
167// Clear error_message_buffer so that if we find other errors
168// we don't re-log this error.
169error_message_buffer->clear();
170}
171
172LogFullErrorReport(buffer_copy.data());
173
174if (error_report_callback) {
175error_report_callback(buffer_copy.data());
176}
177
178if (halt_on_error_ && common_flags()->abort_on_error) {
179// On Android the message is truncated to 512 characters.
180// FIXME: implement "compact" error format, possibly without, or with
181// highly compressed stack traces?
182// FIXME: or just use the summary line as abort message?
183SetAbortMessage(buffer_copy.data());
184}
185
186// In halt_on_error = false mode, reset the current error object (before
187// unlocking).
188if (!halt_on_error_)
189internal_memset(¤t_error_, 0, sizeof(current_error_));
190
191if (halt_on_error_) {
192Report("ABORTING\n");
193Die();
194}
195}
196
197void ReportError(const ErrorDescription &description) {
198// Can only report one error per ScopedInErrorReport.
199CHECK_EQ(current_error_.kind, kErrorKindInvalid);
200internal_memcpy(¤t_error_, &description, sizeof(current_error_));
201}
202
203static ErrorDescription &CurrentError() {
204return current_error_;
205}
206
207private:
208ScopedErrorReportLock error_report_lock_;
209// Error currently being reported. This enables the destructor to interact
210// with the debugger and point it to an error description.
211static ErrorDescription current_error_;
212bool halt_on_error_;
213};
214
215ErrorDescription ScopedInErrorReport::current_error_(LINKER_INITIALIZED);
216
217void ReportDeadlySignal(const SignalContext &sig) {
218ScopedInErrorReport in_report(/*fatal*/ true);
219ErrorDeadlySignal error(GetCurrentTidOrInvalid(), sig);
220in_report.ReportError(error);
221}
222
223void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {
224ScopedInErrorReport in_report;
225ErrorDoubleFree error(GetCurrentTidOrInvalid(), free_stack, addr);
226in_report.ReportError(error);
227}
228
229void ReportNewDeleteTypeMismatch(uptr addr, uptr delete_size,
230uptr delete_alignment,
231BufferedStackTrace *free_stack) {
232ScopedInErrorReport in_report;
233ErrorNewDeleteTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
234delete_size, delete_alignment);
235in_report.ReportError(error);
236}
237
238void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {
239ScopedInErrorReport in_report;
240ErrorFreeNotMalloced error(GetCurrentTidOrInvalid(), free_stack, addr);
241in_report.ReportError(error);
242}
243
244void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,
245AllocType alloc_type,
246AllocType dealloc_type) {
247ScopedInErrorReport in_report;
248ErrorAllocTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,
249alloc_type, dealloc_type);
250in_report.ReportError(error);
251}
252
253void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {
254ScopedInErrorReport in_report;
255ErrorMallocUsableSizeNotOwned error(GetCurrentTidOrInvalid(), stack, addr);
256in_report.ReportError(error);
257}
258
259void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,
260BufferedStackTrace *stack) {
261ScopedInErrorReport in_report;
262ErrorSanitizerGetAllocatedSizeNotOwned error(GetCurrentTidOrInvalid(), stack,
263addr);
264in_report.ReportError(error);
265}
266
267void ReportCallocOverflow(uptr count, uptr size, BufferedStackTrace *stack) {
268ScopedInErrorReport in_report(/*fatal*/ true);
269ErrorCallocOverflow error(GetCurrentTidOrInvalid(), stack, count, size);
270in_report.ReportError(error);
271}
272
273void ReportReallocArrayOverflow(uptr count, uptr size,
274BufferedStackTrace *stack) {
275ScopedInErrorReport in_report(/*fatal*/ true);
276ErrorReallocArrayOverflow error(GetCurrentTidOrInvalid(), stack, count, size);
277in_report.ReportError(error);
278}
279
280void ReportPvallocOverflow(uptr size, BufferedStackTrace *stack) {
281ScopedInErrorReport in_report(/*fatal*/ true);
282ErrorPvallocOverflow error(GetCurrentTidOrInvalid(), stack, size);
283in_report.ReportError(error);
284}
285
286void ReportInvalidAllocationAlignment(uptr alignment,
287BufferedStackTrace *stack) {
288ScopedInErrorReport in_report(/*fatal*/ true);
289ErrorInvalidAllocationAlignment error(GetCurrentTidOrInvalid(), stack,
290alignment);
291in_report.ReportError(error);
292}
293
294void ReportInvalidAlignedAllocAlignment(uptr size, uptr alignment,
295BufferedStackTrace *stack) {
296ScopedInErrorReport in_report(/*fatal*/ true);
297ErrorInvalidAlignedAllocAlignment error(GetCurrentTidOrInvalid(), stack,
298size, alignment);
299in_report.ReportError(error);
300}
301
302void ReportInvalidPosixMemalignAlignment(uptr alignment,
303BufferedStackTrace *stack) {
304ScopedInErrorReport in_report(/*fatal*/ true);
305ErrorInvalidPosixMemalignAlignment error(GetCurrentTidOrInvalid(), stack,
306alignment);
307in_report.ReportError(error);
308}
309
310void ReportAllocationSizeTooBig(uptr user_size, uptr total_size, uptr max_size,
311BufferedStackTrace *stack) {
312ScopedInErrorReport in_report(/*fatal*/ true);
313ErrorAllocationSizeTooBig error(GetCurrentTidOrInvalid(), stack, user_size,
314total_size, max_size);
315in_report.ReportError(error);
316}
317
318void ReportRssLimitExceeded(BufferedStackTrace *stack) {
319ScopedInErrorReport in_report(/*fatal*/ true);
320ErrorRssLimitExceeded error(GetCurrentTidOrInvalid(), stack);
321in_report.ReportError(error);
322}
323
324void ReportOutOfMemory(uptr requested_size, BufferedStackTrace *stack) {
325ScopedInErrorReport in_report(/*fatal*/ true);
326ErrorOutOfMemory error(GetCurrentTidOrInvalid(), stack, requested_size);
327in_report.ReportError(error);
328}
329
330void ReportStringFunctionMemoryRangesOverlap(const char *function,
331const char *offset1, uptr length1,
332const char *offset2, uptr length2,
333BufferedStackTrace *stack) {
334ScopedInErrorReport in_report;
335ErrorStringFunctionMemoryRangesOverlap error(
336GetCurrentTidOrInvalid(), stack, (uptr)offset1, length1, (uptr)offset2,
337length2, function);
338in_report.ReportError(error);
339}
340
341void ReportStringFunctionSizeOverflow(uptr offset, uptr size,
342BufferedStackTrace *stack) {
343ScopedInErrorReport in_report;
344ErrorStringFunctionSizeOverflow error(GetCurrentTidOrInvalid(), stack, offset,
345size);
346in_report.ReportError(error);
347}
348
349void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,
350uptr old_mid, uptr new_mid,
351BufferedStackTrace *stack) {
352ScopedInErrorReport in_report;
353ErrorBadParamsToAnnotateContiguousContainer error(
354GetCurrentTidOrInvalid(), stack, beg, end, old_mid, new_mid);
355in_report.ReportError(error);
356}
357
358void ReportBadParamsToAnnotateDoubleEndedContiguousContainer(
359uptr storage_beg, uptr storage_end, uptr old_container_beg,
360uptr old_container_end, uptr new_container_beg, uptr new_container_end,
361BufferedStackTrace *stack) {
362ScopedInErrorReport in_report;
363ErrorBadParamsToAnnotateDoubleEndedContiguousContainer error(
364GetCurrentTidOrInvalid(), stack, storage_beg, storage_end,
365old_container_beg, old_container_end, new_container_beg,
366new_container_end);
367in_report.ReportError(error);
368}
369
370void ReportODRViolation(const __asan_global *g1, u32 stack_id1,
371const __asan_global *g2, u32 stack_id2) {
372ScopedInErrorReport in_report;
373ErrorODRViolation error(GetCurrentTidOrInvalid(), g1, stack_id1, g2,
374stack_id2);
375in_report.ReportError(error);
376}
377
378// ----------------------- CheckForInvalidPointerPair ----------- {{{1
379static NOINLINE void ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp,
380uptr a1, uptr a2) {
381ScopedInErrorReport in_report;
382ErrorInvalidPointerPair error(GetCurrentTidOrInvalid(), pc, bp, sp, a1, a2);
383in_report.ReportError(error);
384}
385
386static bool IsInvalidPointerPair(uptr a1, uptr a2) {
387if (a1 == a2)
388return false;
389
390// 256B in shadow memory can be iterated quite fast
391static const uptr kMaxOffset = 2048;
392
393uptr left = a1 < a2 ? a1 : a2;
394uptr right = a1 < a2 ? a2 : a1;
395uptr offset = right - left;
396if (offset <= kMaxOffset)
397return __asan_region_is_poisoned(left, offset);
398
399AsanThread *t = GetCurrentThread();
400
401// check whether left is a stack memory pointer
402if (uptr shadow_offset1 = t->GetStackVariableShadowStart(left)) {
403uptr shadow_offset2 = t->GetStackVariableShadowStart(right);
404return shadow_offset2 == 0 || shadow_offset1 != shadow_offset2;
405}
406
407// check whether left is a heap memory address
408HeapAddressDescription hdesc1, hdesc2;
409if (GetHeapAddressInformation(left, 0, &hdesc1) &&
410hdesc1.chunk_access.access_type == kAccessTypeInside)
411return !GetHeapAddressInformation(right, 0, &hdesc2) ||
412hdesc2.chunk_access.access_type != kAccessTypeInside ||
413hdesc1.chunk_access.chunk_begin != hdesc2.chunk_access.chunk_begin;
414
415// check whether left is an address of a global variable
416GlobalAddressDescription gdesc1, gdesc2;
417if (GetGlobalAddressInformation(left, 0, &gdesc1))
418return !GetGlobalAddressInformation(right - 1, 0, &gdesc2) ||
419!gdesc1.PointsInsideTheSameVariable(gdesc2);
420
421if (t->GetStackVariableShadowStart(right) ||
422GetHeapAddressInformation(right, 0, &hdesc2) ||
423GetGlobalAddressInformation(right - 1, 0, &gdesc2))
424return true;
425
426// At this point we know nothing about both a1 and a2 addresses.
427return false;
428}
429
430static inline void CheckForInvalidPointerPair(void *p1, void *p2) {
431switch (flags()->detect_invalid_pointer_pairs) {
432case 0:
433return;
434case 1:
435if (p1 == nullptr || p2 == nullptr)
436return;
437break;
438}
439
440uptr a1 = reinterpret_cast<uptr>(p1);
441uptr a2 = reinterpret_cast<uptr>(p2);
442
443if (IsInvalidPointerPair(a1, a2)) {
444GET_CALLER_PC_BP_SP;
445ReportInvalidPointerPair(pc, bp, sp, a1, a2);
446}
447}
448// ----------------------- Mac-specific reports ----------------- {{{1
449
450void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,
451BufferedStackTrace *stack) {
452ScopedInErrorReport in_report;
453Printf(
454"mz_realloc(%p) -- attempting to realloc unallocated memory.\n"
455"This is an unrecoverable problem, exiting now.\n",
456(void *)addr);
457PrintZoneForPointer(addr, zone_ptr, zone_name);
458stack->Print();
459DescribeAddressIfHeap(addr);
460}
461
462// -------------- SuppressErrorReport -------------- {{{1
463// Avoid error reports duplicating for ASan recover mode.
464static bool SuppressErrorReport(uptr pc) {
465if (!common_flags()->suppress_equal_pcs) return false;
466for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {
467uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);
468if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,
469pc, memory_order_relaxed))
470return false;
471if (cmp == pc) return true;
472}
473Die();
474}
475
476void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,
477uptr access_size, u32 exp, bool fatal) {
478if (__asan_test_only_reported_buggy_pointer) {
479*__asan_test_only_reported_buggy_pointer = addr;
480return;
481}
482if (!fatal && SuppressErrorReport(pc)) return;
483ENABLE_FRAME_POINTER;
484
485// Optimization experiments.
486// The experiments can be used to evaluate potential optimizations that remove
487// instrumentation (assess false negatives). Instead of completely removing
488// some instrumentation, compiler can emit special calls into runtime
489// (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass
490// mask of experiments (exp).
491// The reaction to a non-zero value of exp is to be defined.
492(void)exp;
493
494ScopedInErrorReport in_report(fatal);
495ErrorGeneric error(GetCurrentTidOrInvalid(), pc, bp, sp, addr, is_write,
496access_size);
497in_report.ReportError(error);
498}
499
500} // namespace __asan
501
502// --------------------------- Interface --------------------- {{{1
503using namespace __asan;
504
505void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,
506uptr access_size, u32 exp) {
507ENABLE_FRAME_POINTER;
508bool fatal = flags()->halt_on_error;
509ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);
510}
511
512void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {
513Lock l(&error_message_buf_mutex);
514error_report_callback = callback;
515}
516
517void __asan_describe_address(uptr addr) {
518// Thread registry must be locked while we're describing an address.
519asanThreadRegistry().Lock();
520PrintAddressDescription(addr, 1, "");
521asanThreadRegistry().Unlock();
522}
523
524int __asan_report_present() {
525return ScopedInErrorReport::CurrentError().kind != kErrorKindInvalid;
526}
527
528uptr __asan_get_report_pc() {
529if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
530return ScopedInErrorReport::CurrentError().Generic.pc;
531return 0;
532}
533
534uptr __asan_get_report_bp() {
535if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
536return ScopedInErrorReport::CurrentError().Generic.bp;
537return 0;
538}
539
540uptr __asan_get_report_sp() {
541if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
542return ScopedInErrorReport::CurrentError().Generic.sp;
543return 0;
544}
545
546uptr __asan_get_report_address() {
547ErrorDescription &err = ScopedInErrorReport::CurrentError();
548if (err.kind == kErrorKindGeneric)
549return err.Generic.addr_description.Address();
550else if (err.kind == kErrorKindDoubleFree)
551return err.DoubleFree.addr_description.addr;
552return 0;
553}
554
555int __asan_get_report_access_type() {
556if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
557return ScopedInErrorReport::CurrentError().Generic.is_write;
558return 0;
559}
560
561uptr __asan_get_report_access_size() {
562if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
563return ScopedInErrorReport::CurrentError().Generic.access_size;
564return 0;
565}
566
567const char *__asan_get_report_description() {
568if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)
569return ScopedInErrorReport::CurrentError().Generic.bug_descr;
570return ScopedInErrorReport::CurrentError().Base.scariness.GetDescription();
571}
572
573extern "C" {
574SANITIZER_INTERFACE_ATTRIBUTE
575void __sanitizer_ptr_sub(void *a, void *b) {
576CheckForInvalidPointerPair(a, b);
577}
578SANITIZER_INTERFACE_ATTRIBUTE
579void __sanitizer_ptr_cmp(void *a, void *b) {
580CheckForInvalidPointerPair(a, b);
581}
582} // extern "C"
583
584// Provide default implementation of __asan_on_error that does nothing
585// and may be overriden by user.
586SANITIZER_INTERFACE_WEAK_DEF(void, __asan_on_error, void) {}
587