diff --git a/compiler-rt/lib/asan/asan_rtl.cpp b/compiler-rt/lib/asan/asan_rtl.cpp --- a/compiler-rt/lib/asan/asan_rtl.cpp +++ b/compiler-rt/lib/asan/asan_rtl.cpp @@ -551,7 +551,40 @@ static AsanInitializer asan_initializer; #endif // ASAN_DYNAMIC -} // namespace __asan +/// Tries to find stack bounds of default stack. +/// +/// \param[in] LocalStack address of a variable on the stack, used to find stack +/// bottom. +/// \param[in] CurrThread current thread, used to look up cached stack top. Can +/// be null, in which case we ask the OS for stack boundaries. +/// \param[out] Top Top of the default stack. Only guaranteed to be written if +/// return value is true. +/// \param[out] Bottom Bottom of the default stack. Only guaranteed to be +/// written if return value is true. +/// +/// \returns true on success (= stack boundaries could be determined). +static bool getDefaultStackBounds(uptr LocalStack, AsanThread *CurrThread, + /*out*/ uptr *Top, /*out*/ uptr *Bottom) { + if (CurrThread) { + uptr PageSize = GetPageSizeCached(); + *Top = CurrThread->stack_top(); + *Bottom = (LocalStack - PageSize) & ~(PageSize - 1); + return true; + } else if (SANITIZER_RTEMS) { + // Give up On RTEMS. + return false; + } else { + CHECK(!SANITIZER_FUCHSIA); + // If we haven't seen this thread, try asking the OS for stack bounds. + uptr TlsAddr, TlsSize, StackSize; + GetThreadStackAndTls(/*main=*/false, Bottom, &StackSize, &TlsAddr, + &TlsSize); + *Top = *Bottom + StackSize; + return true; + } +} + +} // namespace __asan // ---------------------- Interface ---------------- {{{1 using namespace __asan; @@ -561,40 +594,58 @@ return; int local_stack; - AsanThread *curr_thread = GetCurrentThread(); - uptr PageSize = GetPageSizeCached(); + uptr top, bottom; - if (curr_thread) { - top = curr_thread->stack_top(); - bottom = ((uptr)&local_stack - PageSize) & ~(PageSize - 1); - } else if (SANITIZER_RTEMS) { - // Give up On RTEMS. - return; + AsanThread *CurrThread = GetCurrentThread(); + + AlternateStackInfo const SignalStack = GetSignalAlternateStack(); + if (0 == SignalStack.error) { + if (SignalStack.on_stack) { + bottom = SignalStack.bottom; + top = SignalStack.top; + } else { + if (!getDefaultStackBounds((uptr)&local_stack, CurrThread, &top, &bottom)) + return; + } } else { - CHECK(!SANITIZER_FUCHSIA); - // If we haven't seen this thread, try asking the OS for stack bounds. - uptr tls_addr, tls_size, stack_size; - GetThreadStackAndTls(/*main=*/false, &bottom, &stack_size, &tls_addr, - &tls_size); - top = bottom + stack_size; + // This should not happen according to the error list of sigaltstack. + + static bool ReportedWarning = false; + if (!ReportedWarning) { + ReportedWarning = true; + Report( + "WARNING: ASan might fail to perform requested " + "__asan_handle_no_return correctly: " + "error code %d from sigaltstack\n" + "False positive error reports may follow\n", + SignalStack.error); + } + + // We don't know if we're on the alternate stack, + // but we can't get any information on it anyway. + // So we assume we're on the default stack. + if (!getDefaultStackBounds((uptr)&local_stack, CurrThread, &top, &bottom)) + return; } + static const uptr kMaxExpectedCleanupSize = 64 << 20; // 64M if (top - bottom > kMaxExpectedCleanupSize) { static bool reported_warning = false; if (reported_warning) return; reported_warning = true; - Report("WARNING: ASan is ignoring requested __asan_handle_no_return: " - "stack top: %p; bottom %p; size: %p (%zd)\n" - "False positive error reports may follow\n" - "For details see " - "https://github.com/google/sanitizers/issues/189\n", - top, bottom, top - bottom, top - bottom); + Report( + "WARNING: ASan is ignoring requested __asan_handle_no_return: " + "stack top: %p; bottom %p; size: %p (%zd)\n" + "False positive error reports may follow\n" + "For details see " + "https://github.com/google/sanitizers/issues/189\n", + top, bottom, top - bottom, top - bottom); return; } PoisonShadow(bottom, top - bottom, 0); - if (curr_thread && curr_thread->has_fake_stack()) - curr_thread->fake_stack()->HandleNoReturn(); + if (CurrThread && CurrThread->has_fake_stack()) + CurrThread->fake_stack()->HandleNoReturn(); } extern "C" void *__asan_extra_spill_area() { diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_common.h b/compiler-rt/lib/sanitizer_common/sanitizer_common.h --- a/compiler-rt/lib/sanitizer_common/sanitizer_common.h +++ b/compiler-rt/lib/sanitizer_common/sanitizer_common.h @@ -317,6 +317,18 @@ // Alternative signal stack (POSIX-only). void SetAlternateSignalStack(); void UnsetAlternateSignalStack(); +// Returns true IFF this thread is running on the signal alternate stack. +// Writes the signal alternate stack top and bottom into *stack_top and +// *stack_bottom. These values are only meaningful if a signal alternate stack +// has been installed. +struct AlternateStackInfo { + // The values are only meaningful if error == 0 + uptr bottom; + uptr top; + int error; // 0 == success, other codes are platform-dependent + bool on_stack; +}; +AlternateStackInfo GetSignalAlternateStack(); // We don't want a summary too long. const int kMaxSummaryLength = 1024; diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp b/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp --- a/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp +++ b/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp @@ -196,9 +196,24 @@ UnmapOrDie(oldstack.ss_sp, oldstack.ss_size); } -static void MaybeInstallSigaction(int signum, - SignalHandlerType handler) { - if (GetHandleSignalMode(signum) == kHandleSignalNo) return; +AlternateStackInfo GetSignalAlternateStack() { + stack_t signal_stack; + if (0 == sigaltstack(nullptr, &signal_stack)) { + if (signal_stack.ss_flags == SS_ONSTACK) { + uptr const bottom = (uptr)signal_stack.ss_sp; + uptr const top = + (uptr)((char *)signal_stack.ss_sp + signal_stack.ss_size); + return {bottom, top, 0, true}; + } else { + return {0, 0, 0, false}; + } + } else { + return {0, 0, errno, false}; + } +} +static void MaybeInstallSigaction(int signum, SignalHandlerType handler) { + if (GetHandleSignalMode(signum) == kHandleSignalNo) + return; struct sigaction sigact; internal_memset(&sigact, 0, sizeof(sigact)); diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp b/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp --- a/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp +++ b/compiler-rt/lib/sanitizer_common/sanitizer_win.cpp @@ -860,6 +860,8 @@ // FIXME: Decide what to do on Windows. } +AlternateStackInfo GetSignalAlternateStack() { return {0, 0, 0, false}; } + void InstallDeadlySignalHandlers(SignalHandlerType handler) { (void)handler; // FIXME: Decide what to do on Windows. diff --git a/compiler-rt/test/asan/TestCases/unpoison-alternate-stack.cpp b/compiler-rt/test/asan/TestCases/unpoison-alternate-stack.cpp new file mode 100644 --- /dev/null +++ b/compiler-rt/test/asan/TestCases/unpoison-alternate-stack.cpp @@ -0,0 +1,176 @@ +// Tests that __asan_handle_no_return properly unpoisons the signal alternate +// stack. + +// Don't optimize, otherwise the variables which create redzones might be +// dropped. +// RUN: %clangxx_asan -fexceptions -O0 %s -o %t -pthread +// RUN: %run %t + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#define HANDLE_ERROR_FROM_RETVAL(EXPRESSION) \ + handleErrorFromRetval((EXPRESSION), #EXPRESSION, __FUNCTION__, __FILE__, __LINE__) + +// If EXPRESSION == 0, no error happened. +#define HANDLE_ERROR_FROM_ERRNO(EXPRESSION) \ + handleErrorFromErrno((EXPRESSION) != 0, #EXPRESSION, __FUNCTION__, __FILE__, __LINE__) + +#define ERROR(STR, ERRNO) \ + error(ERRNO, STR, __FUNCTION__, __FILE__, __LINE__) + +namespace { + +void error(int Err, char const *Expression, + char const *Function, char const *File, int Line) { + std::fprintf(stderr, + "Error %d: %s\nIn expression %s\nIn function %s\nIn file %s:%d\nAborting.\n\n", + Err, std::strerror(Err), Expression, Function, File, Line); + std::abort(); +} + +void handleErrorFromRetval(int Err, char const *Expression, + char const *Function, char const *File, int Line) { + if (Err) + error(Err, Expression, Function, File, Line); +} + +void handleErrorFromErrno(bool Failed, char const *Expression, + char const *Function, char const *File, int Line) { + if (Failed) + error(errno, Expression, Function, File, Line); +} + +char *LeftRedzone; +char *RightRedzone; + +// Create redzones for stack variables in shadow memory and throw, +// which should unpoison the entire stack. +void __attribute__((noinline)) prepareStackShadow() { + char Blob[100]; // This variable must not be optimized out, because we use it + // to create redzones. + + LeftRedzone = Blob - 1; + RightRedzone = Blob + sizeof(Blob); + + assert(__asan_address_is_poisoned(LeftRedzone)); + assert(__asan_address_is_poisoned(RightRedzone)); + + // Trigger stack unwinding, which avoids normal cleanup of redzone markers. + // Instead, __asan_handle_no_return is called which unpoisons the entire + // stack. + throw "up"; +} + +// Ensure that the redzones created by prepareStackShadow have been removed. +void __attribute__((noinline)) assertNoRedzones() { + assert(0 == __asan_region_is_poisoned(LeftRedzone, + RightRedzone - LeftRedzone)); +} + +// - Create redzones for a stack variable +// - Unwind the stack +// - Ensure that the redzones have been removed +void testHandleNoReturn() { + try { + prepareStackShadow(); + } catch (...) { + assertNoRedzones(); + } +} + +// Signal handler which must be run on signal alternate stack, +// and tests if stack unwinding properly triggers stack unpoisoning. +void signalHandler(int, siginfo_t *, void *) { + stack_t Stack; + HANDLE_ERROR_FROM_ERRNO(sigaltstack(nullptr, &Stack)); + assert(Stack.ss_flags == SS_ONSTACK); + + // second test on alt stack (actual check) + testHandleNoReturn(); +} + +// Main test function. +// Must be run on another thread to be able to control memory placement between +// default stack and alternate signal stack. +// If the alternate signal stack is placed in close proximity before the +// default stack, __asan_handle_no_return might unpoison both, even without +// being aware of the signal alternate stack. +// We want to test reliable that __asan_handle_no_return can properly unpoison +// the signal alternate stack. +void *threadFun(void *AltStack) { + // first test on default stack (sanity check) + testHandleNoReturn(); + + HANDLE_ERROR_FROM_ERRNO(sigaltstack((stack_t const *)AltStack, nullptr)); + + struct sigaction const Action = { + .sa_sigaction = signalHandler, + .sa_mask = {0}, + .sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK, + .sa_restorer = nullptr}; + HANDLE_ERROR_FROM_ERRNO(sigaction(SIGSEGV, &Action, nullptr)); + + if (0 != raise(SIGSEGV)) + assert(false && "failed to raise SIGSEGV"); + + return nullptr; +} + +} // namespace + +// Check that __asan_handle_no_return properly unpoisons a signal alternate +// stack. +// __asan_handle_no_return tries to determine the stack boundaries and +// unpoisons all memory inside those. +// If the determination of stack boundaries does not work properly on the +// signal alternate stack, then the unpoisoning might be omitted. +// This can leave redzones for variables on the signal alternate stack, which +// can lead to false positive reports when the stack is reused. +int main() { + size_t const PageSize = sysconf(_SC_PAGESIZE); + // To align the alternate stack, we round this up to page_size. + size_t const DefaultStackSize = + (PTHREAD_STACK_MIN - 1 + PageSize) & ~(PageSize - 1); + // The alternate stack needs a certain size, or the signal handler segfaults. + size_t const AltStackSize = 10 * PageSize; + size_t const MappingSize = DefaultStackSize + AltStackSize; + // Using mmap guarantees proper alignment. + void *const Mapping = mmap(nullptr, MappingSize, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, + 0, 0); + if ((void *)-1 == Mapping) + ERROR("mmap", errno); + + stack_t const AltStack = { + .ss_sp = (char *)Mapping + DefaultStackSize, + .ss_flags = 0, + .ss_size = AltStackSize}; + + pthread_t Thread; + pthread_attr_t ThreadAttr; + HANDLE_ERROR_FROM_RETVAL(pthread_attr_init(&ThreadAttr)); + HANDLE_ERROR_FROM_RETVAL(pthread_attr_setstack(&ThreadAttr, Mapping, + DefaultStackSize)); + HANDLE_ERROR_FROM_RETVAL(pthread_create(&Thread, &ThreadAttr, &threadFun, + (void *)&AltStack)); + + if (int const Err = pthread_join(Thread, nullptr)) + if (EINVAL != Err) // EINVAL means the other thread exited first + ERROR("pthread_join", Err); + + HANDLE_ERROR_FROM_RETVAL(munmap(Mapping, MappingSize)); +}