libcruft-util/debug/system.cpp

65 lines
1.9 KiB
C++
Raw Normal View History

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2010-2019 Danny Robson <danny@nerdcruft.net>
*/
#include "./system.hpp"
#include "debugger.hpp"
#include "../backtrace.hpp"
#include "../log.hpp"
#include <cstdlib>
////////////////////////////////////////////////////////////////////////////////
static void abort_with_trace (void)
{
// Manually trigger a breakpoint if possible so that the debugger won't
// silently dump us some place without further information.
// eg, CLion/GDB/Win32 silently dropping us out of the session.
breakpoint ();
// If this is because of an exception we may as well rethrow and hope that
// the system will print exception data during the abort process.
//
// But we can at least try to print anything derived from std::exception
// (which is a likely guess) before we self-destruct.
if (auto ptr = std::current_exception (); ptr) {
try {
std::rethrow_exception (ptr);
} catch (std::exception const &x) {
LOG_EMERGENCY ("unhandled exception: %!\n%!", x.what (), debug::backtrace {});
} catch (...) {
LOG_EMERGENCY ("unhandled exception: %!\n", debug::backtrace {});
}
} else {
LOG_EMERGENCY ("aborting: %!", debug::backtrace {});
}
std::abort ();
}
///////////////////////////////////////////////////////////////////////////////
void
cruft::debug::init [[gnu::constructor]] (void)
{
std::set_terminate (abort_with_trace);
if (!debug_enabled && !getenv ("DEBUG"))
return;
LOG_DEBUG ("setting debug environment");
//enable_fpe ();
force_console ();
prepare_debugger ();
if (getenv ("DEBUG_WAIT"))
await_debugger ();
}