Path: blob/main/contrib/llvm-project/compiler-rt/lib/asan/asan_report.cpp
35233 views
//===-- asan_report.cpp ---------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file is a part of AddressSanitizer, an address sanity checker.9//10// This file contains error reporting code.11//===----------------------------------------------------------------------===//1213#include "asan_report.h"1415#include "asan_descriptions.h"16#include "asan_errors.h"17#include "asan_flags.h"18#include "asan_internal.h"19#include "asan_mapping.h"20#include "asan_scariness_score.h"21#include "asan_stack.h"22#include "asan_thread.h"23#include "sanitizer_common/sanitizer_common.h"24#include "sanitizer_common/sanitizer_flags.h"25#include "sanitizer_common/sanitizer_interface_internal.h"26#include "sanitizer_common/sanitizer_placement_new.h"27#include "sanitizer_common/sanitizer_report_decorator.h"28#include "sanitizer_common/sanitizer_stackdepot.h"29#include "sanitizer_common/sanitizer_symbolizer.h"3031namespace __asan {3233// -------------------- User-specified callbacks ----------------- {{{134static void (*error_report_callback)(const char*);35using ErrorMessageBuffer = InternalMmapVectorNoCtor<char, true>;36alignas(37alignof(ErrorMessageBuffer)) static char error_message_buffer_placeholder38[sizeof(ErrorMessageBuffer)];39static ErrorMessageBuffer *error_message_buffer = nullptr;40static Mutex error_message_buf_mutex;41static const unsigned kAsanBuggyPcPoolSize = 25;42static __sanitizer::atomic_uintptr_t AsanBuggyPcPool[kAsanBuggyPcPoolSize];4344void AppendToErrorMessageBuffer(const char *buffer) {45Lock l(&error_message_buf_mutex);46if (!error_message_buffer) {47error_message_buffer =48new (error_message_buffer_placeholder) ErrorMessageBuffer();49error_message_buffer->Initialize(kErrorMessageBufferSize);50}51uptr error_message_buffer_len = error_message_buffer->size();52uptr buffer_len = internal_strlen(buffer);53error_message_buffer->resize(error_message_buffer_len + buffer_len);54internal_memcpy(error_message_buffer->data() + error_message_buffer_len,55buffer, buffer_len);56}5758// ---------------------- Helper functions ----------------------- {{{15960void PrintMemoryByte(InternalScopedString *str, const char *before, u8 byte,61bool in_shadow, const char *after) {62Decorator d;63str->AppendF("%s%s%x%x%s%s", before,64in_shadow ? d.ShadowByte(byte) : d.MemoryByte(), byte >> 4,65byte & 15, d.Default(), after);66}6768static void PrintZoneForPointer(uptr ptr, uptr zone_ptr,69const char *zone_name) {70if (zone_ptr) {71if (zone_name) {72Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n", (void *)ptr,73(void *)zone_ptr, zone_name);74} else {75Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n",76(void *)ptr, (void *)zone_ptr);77}78} else {79Printf("malloc_zone_from_ptr(%p) = 0\n", (void *)ptr);80}81}8283// ---------------------- Address Descriptions ------------------- {{{18485bool ParseFrameDescription(const char *frame_descr,86InternalMmapVector<StackVarDescr> *vars) {87CHECK(frame_descr);88const 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// or "offset size len ObjectName:line".93uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10);94if (n_objects == 0)95return false;9697for (uptr i = 0; i < n_objects; i++) {98uptr beg = (uptr)internal_simple_strtoll(p, &p, 10);99uptr size = (uptr)internal_simple_strtoll(p, &p, 10);100uptr len = (uptr)internal_simple_strtoll(p, &p, 10);101if (beg == 0 || size == 0 || *p != ' ') {102return false;103}104p++;105char *colon_pos = internal_strchr(p, ':');106uptr line = 0;107uptr name_len = len;108if (colon_pos != nullptr && colon_pos < p + len) {109name_len = colon_pos - p;110line = (uptr)internal_simple_strtoll(colon_pos + 1, nullptr, 10);111}112StackVarDescr var = {beg, size, p, name_len, line};113vars->push_back(var);114p += len;115}116117return true;118}119120// -------------------- Different kinds of reports ----------------- {{{1121122// Use ScopedInErrorReport to run common actions just before and123// immediately after printing error report.124class ScopedInErrorReport {125public:126explicit ScopedInErrorReport(bool fatal = false)127: halt_on_error_(fatal || flags()->halt_on_error) {128// Make sure the registry and sanitizer report mutexes are locked while129// we're printing an error report.130// We can lock them only here to avoid self-deadlock in case of131// recursive reports.132asanThreadRegistry().Lock();133Printf(134"=================================================================\n");135}136137~ScopedInErrorReport() {138if (halt_on_error_ && !__sanitizer_acquire_crash_state()) {139asanThreadRegistry().Unlock();140return;141}142ASAN_ON_ERROR();143if (current_error_.IsValid()) current_error_.Print();144145// Make sure the current thread is announced.146DescribeThread(GetCurrentThread());147// We may want to grab this lock again when printing stats.148asanThreadRegistry().Unlock();149// Print memory stats.150if (flags()->print_stats)151__asan_print_accumulated_stats();152153if (common_flags()->print_cmdline)154PrintCmdline();155156if (common_flags()->print_module_map == 2)157DumpProcessMap();158159// Copy the message buffer so that we could start logging without holding a160// lock that gets acquired during printing.161InternalScopedString buffer_copy;162{163Lock l(&error_message_buf_mutex);164error_message_buffer->push_back('\0');165buffer_copy.Append(error_message_buffer->data());166// Clear error_message_buffer so that if we find other errors167// we don't re-log this error.168error_message_buffer->clear();169}170171LogFullErrorReport(buffer_copy.data());172173if (error_report_callback) {174error_report_callback(buffer_copy.data());175}176177if (halt_on_error_ && common_flags()->abort_on_error) {178// On Android the message is truncated to 512 characters.179// FIXME: implement "compact" error format, possibly without, or with180// highly compressed stack traces?181// FIXME: or just use the summary line as abort message?182SetAbortMessage(buffer_copy.data());183}184185// In halt_on_error = false mode, reset the current error object (before186// unlocking).187if (!halt_on_error_)188internal_memset(¤t_error_, 0, sizeof(current_error_));189190if (halt_on_error_) {191Report("ABORTING\n");192Die();193}194}195196void ReportError(const ErrorDescription &description) {197// Can only report one error per ScopedInErrorReport.198CHECK_EQ(current_error_.kind, kErrorKindInvalid);199internal_memcpy(¤t_error_, &description, sizeof(current_error_));200}201202static ErrorDescription &CurrentError() {203return current_error_;204}205206private:207ScopedErrorReportLock error_report_lock_;208// Error currently being reported. This enables the destructor to interact209// with the debugger and point it to an error description.210static ErrorDescription current_error_;211bool halt_on_error_;212};213214ErrorDescription ScopedInErrorReport::current_error_(LINKER_INITIALIZED);215216void ReportDeadlySignal(const SignalContext &sig) {217ScopedInErrorReport in_report(/*fatal*/ true);218ErrorDeadlySignal error(GetCurrentTidOrInvalid(), sig);219in_report.ReportError(error);220}221222void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) {223ScopedInErrorReport in_report;224ErrorDoubleFree error(GetCurrentTidOrInvalid(), free_stack, addr);225in_report.ReportError(error);226}227228void ReportNewDeleteTypeMismatch(uptr addr, uptr delete_size,229uptr delete_alignment,230BufferedStackTrace *free_stack) {231ScopedInErrorReport in_report;232ErrorNewDeleteTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,233delete_size, delete_alignment);234in_report.ReportError(error);235}236237void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) {238ScopedInErrorReport in_report;239ErrorFreeNotMalloced error(GetCurrentTidOrInvalid(), free_stack, addr);240in_report.ReportError(error);241}242243void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack,244AllocType alloc_type,245AllocType dealloc_type) {246ScopedInErrorReport in_report;247ErrorAllocTypeMismatch error(GetCurrentTidOrInvalid(), free_stack, addr,248alloc_type, dealloc_type);249in_report.ReportError(error);250}251252void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) {253ScopedInErrorReport in_report;254ErrorMallocUsableSizeNotOwned error(GetCurrentTidOrInvalid(), stack, addr);255in_report.ReportError(error);256}257258void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr,259BufferedStackTrace *stack) {260ScopedInErrorReport in_report;261ErrorSanitizerGetAllocatedSizeNotOwned error(GetCurrentTidOrInvalid(), stack,262addr);263in_report.ReportError(error);264}265266void ReportCallocOverflow(uptr count, uptr size, BufferedStackTrace *stack) {267ScopedInErrorReport in_report(/*fatal*/ true);268ErrorCallocOverflow error(GetCurrentTidOrInvalid(), stack, count, size);269in_report.ReportError(error);270}271272void ReportReallocArrayOverflow(uptr count, uptr size,273BufferedStackTrace *stack) {274ScopedInErrorReport in_report(/*fatal*/ true);275ErrorReallocArrayOverflow error(GetCurrentTidOrInvalid(), stack, count, size);276in_report.ReportError(error);277}278279void ReportPvallocOverflow(uptr size, BufferedStackTrace *stack) {280ScopedInErrorReport in_report(/*fatal*/ true);281ErrorPvallocOverflow error(GetCurrentTidOrInvalid(), stack, size);282in_report.ReportError(error);283}284285void ReportInvalidAllocationAlignment(uptr alignment,286BufferedStackTrace *stack) {287ScopedInErrorReport in_report(/*fatal*/ true);288ErrorInvalidAllocationAlignment error(GetCurrentTidOrInvalid(), stack,289alignment);290in_report.ReportError(error);291}292293void ReportInvalidAlignedAllocAlignment(uptr size, uptr alignment,294BufferedStackTrace *stack) {295ScopedInErrorReport in_report(/*fatal*/ true);296ErrorInvalidAlignedAllocAlignment error(GetCurrentTidOrInvalid(), stack,297size, alignment);298in_report.ReportError(error);299}300301void ReportInvalidPosixMemalignAlignment(uptr alignment,302BufferedStackTrace *stack) {303ScopedInErrorReport in_report(/*fatal*/ true);304ErrorInvalidPosixMemalignAlignment error(GetCurrentTidOrInvalid(), stack,305alignment);306in_report.ReportError(error);307}308309void ReportAllocationSizeTooBig(uptr user_size, uptr total_size, uptr max_size,310BufferedStackTrace *stack) {311ScopedInErrorReport in_report(/*fatal*/ true);312ErrorAllocationSizeTooBig error(GetCurrentTidOrInvalid(), stack, user_size,313total_size, max_size);314in_report.ReportError(error);315}316317void ReportRssLimitExceeded(BufferedStackTrace *stack) {318ScopedInErrorReport in_report(/*fatal*/ true);319ErrorRssLimitExceeded error(GetCurrentTidOrInvalid(), stack);320in_report.ReportError(error);321}322323void ReportOutOfMemory(uptr requested_size, BufferedStackTrace *stack) {324ScopedInErrorReport in_report(/*fatal*/ true);325ErrorOutOfMemory error(GetCurrentTidOrInvalid(), stack, requested_size);326in_report.ReportError(error);327}328329void ReportStringFunctionMemoryRangesOverlap(const char *function,330const char *offset1, uptr length1,331const char *offset2, uptr length2,332BufferedStackTrace *stack) {333ScopedInErrorReport in_report;334ErrorStringFunctionMemoryRangesOverlap error(335GetCurrentTidOrInvalid(), stack, (uptr)offset1, length1, (uptr)offset2,336length2, function);337in_report.ReportError(error);338}339340void ReportStringFunctionSizeOverflow(uptr offset, uptr size,341BufferedStackTrace *stack) {342ScopedInErrorReport in_report;343ErrorStringFunctionSizeOverflow error(GetCurrentTidOrInvalid(), stack, offset,344size);345in_report.ReportError(error);346}347348void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end,349uptr old_mid, uptr new_mid,350BufferedStackTrace *stack) {351ScopedInErrorReport in_report;352ErrorBadParamsToAnnotateContiguousContainer error(353GetCurrentTidOrInvalid(), stack, beg, end, old_mid, new_mid);354in_report.ReportError(error);355}356357void ReportBadParamsToAnnotateDoubleEndedContiguousContainer(358uptr storage_beg, uptr storage_end, uptr old_container_beg,359uptr old_container_end, uptr new_container_beg, uptr new_container_end,360BufferedStackTrace *stack) {361ScopedInErrorReport in_report;362ErrorBadParamsToAnnotateDoubleEndedContiguousContainer error(363GetCurrentTidOrInvalid(), stack, storage_beg, storage_end,364old_container_beg, old_container_end, new_container_beg,365new_container_end);366in_report.ReportError(error);367}368369void ReportODRViolation(const __asan_global *g1, u32 stack_id1,370const __asan_global *g2, u32 stack_id2) {371ScopedInErrorReport in_report;372ErrorODRViolation error(GetCurrentTidOrInvalid(), g1, stack_id1, g2,373stack_id2);374in_report.ReportError(error);375}376377// ----------------------- CheckForInvalidPointerPair ----------- {{{1378static NOINLINE void ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp,379uptr a1, uptr a2) {380ScopedInErrorReport in_report;381ErrorInvalidPointerPair error(GetCurrentTidOrInvalid(), pc, bp, sp, a1, a2);382in_report.ReportError(error);383}384385static bool IsInvalidPointerPair(uptr a1, uptr a2) {386if (a1 == a2)387return false;388389// 256B in shadow memory can be iterated quite fast390static const uptr kMaxOffset = 2048;391392uptr left = a1 < a2 ? a1 : a2;393uptr right = a1 < a2 ? a2 : a1;394uptr offset = right - left;395if (offset <= kMaxOffset)396return __asan_region_is_poisoned(left, offset);397398AsanThread *t = GetCurrentThread();399400// check whether left is a stack memory pointer401if (uptr shadow_offset1 = t->GetStackVariableShadowStart(left)) {402uptr shadow_offset2 = t->GetStackVariableShadowStart(right);403return shadow_offset2 == 0 || shadow_offset1 != shadow_offset2;404}405406// check whether left is a heap memory address407HeapAddressDescription hdesc1, hdesc2;408if (GetHeapAddressInformation(left, 0, &hdesc1) &&409hdesc1.chunk_access.access_type == kAccessTypeInside)410return !GetHeapAddressInformation(right, 0, &hdesc2) ||411hdesc2.chunk_access.access_type != kAccessTypeInside ||412hdesc1.chunk_access.chunk_begin != hdesc2.chunk_access.chunk_begin;413414// check whether left is an address of a global variable415GlobalAddressDescription gdesc1, gdesc2;416if (GetGlobalAddressInformation(left, 0, &gdesc1))417return !GetGlobalAddressInformation(right - 1, 0, &gdesc2) ||418!gdesc1.PointsInsideTheSameVariable(gdesc2);419420if (t->GetStackVariableShadowStart(right) ||421GetHeapAddressInformation(right, 0, &hdesc2) ||422GetGlobalAddressInformation(right - 1, 0, &gdesc2))423return true;424425// At this point we know nothing about both a1 and a2 addresses.426return false;427}428429static inline void CheckForInvalidPointerPair(void *p1, void *p2) {430switch (flags()->detect_invalid_pointer_pairs) {431case 0:432return;433case 1:434if (p1 == nullptr || p2 == nullptr)435return;436break;437}438439uptr a1 = reinterpret_cast<uptr>(p1);440uptr a2 = reinterpret_cast<uptr>(p2);441442if (IsInvalidPointerPair(a1, a2)) {443GET_CALLER_PC_BP_SP;444ReportInvalidPointerPair(pc, bp, sp, a1, a2);445}446}447// ----------------------- Mac-specific reports ----------------- {{{1448449void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name,450BufferedStackTrace *stack) {451ScopedInErrorReport in_report;452Printf(453"mz_realloc(%p) -- attempting to realloc unallocated memory.\n"454"This is an unrecoverable problem, exiting now.\n",455(void *)addr);456PrintZoneForPointer(addr, zone_ptr, zone_name);457stack->Print();458DescribeAddressIfHeap(addr);459}460461// -------------- SuppressErrorReport -------------- {{{1462// Avoid error reports duplicating for ASan recover mode.463static bool SuppressErrorReport(uptr pc) {464if (!common_flags()->suppress_equal_pcs) return false;465for (unsigned i = 0; i < kAsanBuggyPcPoolSize; i++) {466uptr cmp = atomic_load_relaxed(&AsanBuggyPcPool[i]);467if (cmp == 0 && atomic_compare_exchange_strong(&AsanBuggyPcPool[i], &cmp,468pc, memory_order_relaxed))469return false;470if (cmp == pc) return true;471}472Die();473}474475void ReportGenericError(uptr pc, uptr bp, uptr sp, uptr addr, bool is_write,476uptr access_size, u32 exp, bool fatal) {477if (__asan_test_only_reported_buggy_pointer) {478*__asan_test_only_reported_buggy_pointer = addr;479return;480}481if (!fatal && SuppressErrorReport(pc)) return;482ENABLE_FRAME_POINTER;483484// Optimization experiments.485// The experiments can be used to evaluate potential optimizations that remove486// instrumentation (assess false negatives). Instead of completely removing487// some instrumentation, compiler can emit special calls into runtime488// (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass489// mask of experiments (exp).490// The reaction to a non-zero value of exp is to be defined.491(void)exp;492493ScopedInErrorReport in_report(fatal);494ErrorGeneric error(GetCurrentTidOrInvalid(), pc, bp, sp, addr, is_write,495access_size);496in_report.ReportError(error);497}498499} // namespace __asan500501// --------------------------- Interface --------------------- {{{1502using namespace __asan;503504void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write,505uptr access_size, u32 exp) {506ENABLE_FRAME_POINTER;507bool fatal = flags()->halt_on_error;508ReportGenericError(pc, bp, sp, addr, is_write, access_size, exp, fatal);509}510511void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) {512Lock l(&error_message_buf_mutex);513error_report_callback = callback;514}515516void __asan_describe_address(uptr addr) {517// Thread registry must be locked while we're describing an address.518asanThreadRegistry().Lock();519PrintAddressDescription(addr, 1, "");520asanThreadRegistry().Unlock();521}522523int __asan_report_present() {524return ScopedInErrorReport::CurrentError().kind != kErrorKindInvalid;525}526527uptr __asan_get_report_pc() {528if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)529return ScopedInErrorReport::CurrentError().Generic.pc;530return 0;531}532533uptr __asan_get_report_bp() {534if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)535return ScopedInErrorReport::CurrentError().Generic.bp;536return 0;537}538539uptr __asan_get_report_sp() {540if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)541return ScopedInErrorReport::CurrentError().Generic.sp;542return 0;543}544545uptr __asan_get_report_address() {546ErrorDescription &err = ScopedInErrorReport::CurrentError();547if (err.kind == kErrorKindGeneric)548return err.Generic.addr_description.Address();549else if (err.kind == kErrorKindDoubleFree)550return err.DoubleFree.addr_description.addr;551return 0;552}553554int __asan_get_report_access_type() {555if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)556return ScopedInErrorReport::CurrentError().Generic.is_write;557return 0;558}559560uptr __asan_get_report_access_size() {561if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)562return ScopedInErrorReport::CurrentError().Generic.access_size;563return 0;564}565566const char *__asan_get_report_description() {567if (ScopedInErrorReport::CurrentError().kind == kErrorKindGeneric)568return ScopedInErrorReport::CurrentError().Generic.bug_descr;569return ScopedInErrorReport::CurrentError().Base.scariness.GetDescription();570}571572extern "C" {573SANITIZER_INTERFACE_ATTRIBUTE574void __sanitizer_ptr_sub(void *a, void *b) {575CheckForInvalidPointerPair(a, b);576}577SANITIZER_INTERFACE_ATTRIBUTE578void __sanitizer_ptr_cmp(void *a, void *b) {579CheckForInvalidPointerPair(a, b);580}581} // extern "C"582583// Provide default implementation of __asan_on_error that does nothing584// and may be overriden by user.585SANITIZER_INTERFACE_WEAK_DEF(void, __asan_on_error, void) {}586587588