libcruft-util/backtrace_win32.cpp

69 lines
1.8 KiB
C++
Raw Normal View History

2016-02-26 13:36:01 +11:00
/*
2018-08-04 15:14:06 +10:00
* 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/.
2016-02-26 13:36:01 +11:00
*
* Copyright:
* 2012-2016, Danny Robson <danny@nerdcruft.net>
2016-02-26 13:36:01 +11:00
*/
#include "backtrace.hpp"
2012-05-10 16:53:29 +10:00
#include "win32/error.hpp"
#include "win32/handle.hpp"
#include "debug.hpp"
#include "except.hpp"
2012-05-10 16:53:29 +10:00
#include <cstdlib>
#include <windows.h>
#include <dbghelp.h>
///////////////////////////////////////////////////////////////////////////////
debug::backtrace::backtrace (void)
{
2012-05-10 16:53:29 +10:00
m_frames.resize (DEFAULT_DEPTH);
auto process = GetCurrentProcess();
if (!SymInitialize (process, NULL, TRUE))
cruft::win32::error::throw_code ();
while (true) {
auto res = CaptureStackBackTrace (1, m_frames.size (), m_frames.data (), NULL);
if (res != m_frames.size ()) {
m_frames.resize (res);
break;
}
2012-05-10 16:53:29 +10:00
m_frames.resize (m_frames.size () * 2);
}
2012-05-10 16:53:29 +10:00
}
///////////////////////////////////////////////////////////////////////////////
2012-05-10 16:53:29 +10:00
std::ostream&
debug::operator <<(std::ostream &os, const debug::backtrace &rhs) {
static auto self = GetCurrentProcess ();
static auto ready = SymInitialize (self, nullptr, TRUE);
CHECK (ready);
2012-05-10 16:53:29 +10:00
static constexpr size_t MAX_LENGTH = 255;
struct {
SYMBOL_INFO info;
char name[MAX_LENGTH + 1];
} symbol;
2012-05-10 16:53:29 +10:00
symbol.info.MaxNameLen = MAX_LENGTH;
symbol.info.SizeOfStruct = sizeof (SYMBOL_INFO);
2012-05-10 16:53:29 +10:00
for (void *frame: rhs.frames ()) {
symbol.name[0] = '\0';
SymFromAddr (self, (DWORD64)frame, 0, &symbol.info);
symbol.name[MAX_LENGTH] = '\0';
os << self << "\t" << frame << "\t" << symbol.name << "\n";
2012-05-10 16:53:29 +10:00
}
return os;
}