C++23 std::stacktrace in segmentation fault

114 views Asked by At

I have noticed that c++23 has a std::stacktrace. Sometimes our unit tests are crashing on jenkins in a segfault but we cannot reproduce the issue locally. That's why I'd like to use std::stacktrace.

MSVC 17 has a good working std::stacktrace, that why we are starting with msvc. But later it should be used on linux as well.

First something to clarify:

  1. I know that catching a segfault is not that trivial. Many things (like malloc() are not allowed in a signal handler). While some issues like malloc can be easily avoiding by providing a statically allocated memory pool allocator other things like printf() and std::cerr can not be avoiding easily. However this is only in test code. The produtive code will not get messed up
  2. we are using /Ehsc so no windows speific SEH Excecption handling is possible

However my signal handler is not called. This is my setup

#include <gtest/gtest.h>

#include <csignal>
#include <cstdlib>
#include <stacktrace>


static void SignalHandler(int signal);
static void SignalHandler(int signal)
{
  const std::stacktrace stacktrace = std::stacktrace::current(0, 10);
  std::cerr << "Caught Signal " << signal <<": " << stacktrace << std::endl;
}

int main(int argc, char* argv[])
{
#if defined(_MSC_VER) && defined(_DEBUG)
  _set_error_mode(_OUT_TO_STDERR);
  _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

  [[maybe_unused]] auto prevSignalHandlerSegfault = std::signal(SIGSEGV, SignalHandler);
  ::testing::InitGoogleTest(&argc, argv);
  int res = RUN_ALL_TESTS();
  return res;
}

Inside my Test I'm simply calling to trigger a segfault

TEST(Foo,Bar)
{
  int* pFoo = nullptr;
  *pFoo = 10;
}

I have set a breakpoint in SignalHandler() but I'm never getting into this function. The console only shows the obvious

unknown file: error: SEH exception with code 0xc0000005 thrown in the test body.

Am I missing something? Can I not catch segfaults by overwriting the signal handlers?

0

There are 0 answers