Echo Writes Code

windows_backtrace.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#include "crucible/core/backtrace.hpp"

#include "crucible/core/format.hpp"

#include <Windows.h>
#include <DbgHelp.h>

#include <cstddef>
#include <cstring>
#include <limits>
#include <mutex>
#include <optional>
#include <utility>

namespace crucible
{
	namespace
	{
		constexpr std::size_t MAXIMUM_SYMBOL_LENGTH { 1024 };

		std::mutex backtrace_mutex;

		class symbol_handler
		{
		public:
			symbol_handler(::DWORD const new_options)
			{
				m_original_options = ::SymGetOptions();
				::SymSetOptions(m_original_options | new_options);

				// Search path is where to look for pdb files. If null, searches the CWD, then
				// ${_NT_SYMBOL_PATH}, then ${_NT_ALTERNATE_SYMBOL_PATH}.
				constexpr ::PCSTR search_path { nullptr };

				// Invading the whole process entails enumerating all loaded DLLs and loading symbols for
				// each.
				constexpr ::BOOL invade_whole_process { TRUE };

				if (::SymInitialize(::GetCurrentProcess(), search_path, invade_whole_process) == TRUE) {
					m_initialized = true;
				}
			}

			~symbol_handler()
			{
				m_initialized = false;
				::SymCleanup(::GetCurrentProcess());
				::SymSetOptions(m_original_options);
			}

			auto is_initialized() const -> bool
			{
				return m_initialized;
			}

			symbol_handler(symbol_handler const &) = delete;

			symbol_handler(symbol_handler &&) = delete;

			auto operator=(symbol_handler const &) -> symbol_handler & = delete;

			auto operator=(symbol_handler &&) -> symbol_handler && = delete;

		private:
			::DWORD m_original_options { 0 };

			bool m_initialized { false };
		};
	}

	auto backtrace() -> backtrace_result<heap_buffer<stack_frame>>
	{
		std::unique_lock<std::mutex> const backtrace_lock { backtrace_mutex };

		symbol_handler const symbols { SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES };
		if (!symbols.is_initialized()) {
			return make_failure<backtrace_error>(sym_initialize_failed {});
		}

		::CONTEXT processor_context {};
		::RtlCaptureContext(&processor_context);

		::STACKFRAME64 stack_frame {};
		stack_frame.AddrPC.Offset = processor_context.Rip;
		stack_frame.AddrPC.Mode = ::AddrModeFlat;
		stack_frame.AddrFrame.Offset = processor_context.Rbp;
		stack_frame.AddrFrame.Mode = ::AddrModeFlat;
		stack_frame.AddrStack.Offset = processor_context.Rsp;
		stack_frame.AddrStack.Mode = ::AddrModeFlat;

		::DWORD unused32 { 0 };
		::DWORD64 unused64 { 0 };

		// BARK BARK BARK BARK BARK
		alignas(::IMAGEHLP_SYMBOL64) std::byte symbol_storage[sizeof(::IMAGEHLP_SYMBOL64) + MAXIMUM_SYMBOL_LENGTH];
		::IMAGEHLP_SYMBOL64 *symbol { new (&symbol_storage) ::IMAGEHLP_SYMBOL64 };

		auto result { make_heap_buffer<stack_frame>() };

		do {
			::BOOL const have_next_frame = ::StackWalk64(
				IMAGE_FILE_MACHINE_AMD64,
				::GetCurrentProcess(),
				::GetCurrentThread(),
				&stack_frame,
				&processor_context,
				nullptr,
				::SymFunctionTableAccess64,
				::SymGetModuleBase64,
				nullptr
			);

			if (have_next_frame != TRUE) {
				stack_frame frame;
				frame.function = format_unsigned_hexadecimal(stack_frame.AddrPC.Offset);
				frame.details = "Failed to find stack frame";
				result.push(frame);
				break;
			}

			symbol->SizeOfStruct = sizeof(::IMAGEHLP_SYMBOL64);
			symbol->MaxNameLength = MAXIMUM_SYMBOL_LENGTH;

			::BOOL const have_next_symbol {
				::SymGetSymFromAddr64(
					process_handle,
					stack_frame.AddrPC.Offset,
					&unused64,
					symbol
				)
			};

			if (have_next_symbol != TRUE) {
				stack_frame frame;
				frame.function = format_unsigned_hexadecimal(stack_frame.AddrPC.Offset);
				frame.details = "Failed to find symbol";
				result.push(frame);
				break;
			}

			::IMAGEHLP_LINE64 line {};
			line.SizeOfStruct = sizeof(::IMAGEHLP_LINE64);

			::BOOL const have_next_line {
				::SymGetLineFromAddr64(
					process_handle,
					stack_frame.AddrPC.Offset,
					&unused32,
					&line
				)
			};

			if (have_next_line != TRUE) {
				stack_frame frame;
				frame.function = string { symbol->Name, std::strlen(symbol->Name) } + "()";
				frame.details = "Failed to find file and line";
				result.push(frame);
				continue;
			}

			CRUCIBLE_ASSERT_GE(line.LineNumber, 0u);
			CRUCIBLE_ASSERT_LE(static_cast<int>(line.LineNumber), std::numeric_limits<int>::max());

			string_view const file { line.FileName, std::strlen(line.FileName) };
			auto const relative_file { file.view().strip_prefix(CRUCIBLE_SOURCE_ROOT) };

			stack_frame frame;
			frame.function = string { symbol->Name, std::strlen(symbol->Name) } + "()";
			frame.location = relative_file + ":" + format_integral(line.LineNumber);
			result.push(frame);
		} while (stack_frame.AddrReturn.Offset != 0);

		return make_success(std::move(result));
	}
}