upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/src/thread_stacks.cpp
diff options
context:
space:
mode:
authorNotRexed <therealnothingfn@gmail.com>2026-11-27 17:50:37 -0500
committerNotRexed <therealnothingfn@gmail.com>2026-11-27 17:50:37 -0500
commitb87abdef5735adc68a614b2025ffcf9869a47cc5 (patch)
tree0d8b473e8e753883a01e00153175994d6b7949c2 /runtime/src/thread_stacks.cpp
parent84e728faffb36cd96a08934e5632ba9b194801f3 (diff)
parent34e33d3ddc4dd95ad14a074db886df3d25588201 (diff)
Merge mandy's main into port/d3d12-nvidia
Brings the D3D12 runtime branch (d3d12/, its launcher scripts and notes, and the pull requests reviewed and applied on it) together with mandy's main. Conflicts (67 files, none under d3d12/): docs/, make_game.py, runtime/, scripts/build_runtime.ps1, tests/ and tools/. Every one takes main's side: main is where that code is maintained, and this branch's copies were older states of the same files or the same pull requests in another form. tests/test_fspx_unpack.py is main's too, as it tests main's tools/fspx_unpack.py. Nothing under d3d12/ is changed by the merge. Checked before pushing: python -m compileall over make_game.py, tools and tests; make_game.py --help; scripts/check_no_game_data.py over the files this adds to main; tests/test_text_write_line_endings.py. The translator suite, the C++ runtime build and CI have not run on the result. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/thread_stacks.cpp')
-rw-r--r--runtime/src/thread_stacks.cpp253
1 files changed, 253 insertions, 0 deletions
diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp
new file mode 100644
index 000000000..38d7cc2a4
--- /dev/null
+++ b/runtime/src/thread_stacks.cpp
@@ -0,0 +1,253 @@
1#include "thread_stacks.h"
2
3#include <windows.h>
4#include <tlhelp32.h>
5
6#include <algorithm>
7#include <array>
8#include <charconv>
9#include <chrono>
10#include <condition_variable>
11#include <cstdio>
12#include <mutex>
13#include <string>
14
15#include "../shims/shims.h"
16#include "../shims/startup_trace.h"
17
18namespace rt {
19namespace {
20
21using Clock = std::chrono::steady_clock;
22using GetDescription = HRESULT(WINAPI*)(HANDLE, PWSTR*);
23using QueryThread = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*);
24
25struct CopiedStack {
26 DWORD64 copy = 0; // Where the bytes are now.
27 DWORD64 original = 0; // Where they were in the thread: [original, original + size).
28 size_t size = 0;
29};
30
31// Suspended section: system calls and a copy only.
32bool copy_context_and_stack(HANDLE thread, CONTEXT& context, std::byte* buffer, CopiedStack& stack) {
33 if (SuspendThread(thread) == DWORD(-1)) return false;
34 context.ContextFlags = CONTEXT_FULL;
35 MEMORY_BASIC_INFORMATION region{};
36 bool copied = false;
37 if (GetThreadContext(thread, &context) &&
38 VirtualQuery(reinterpret_cast<void*>(context.Rsp), &region, sizeof(region)) &&
39 region.State == MEM_COMMIT && !(region.Protect & (PAGE_GUARD | PAGE_NOACCESS))) {
40 // From RSP (rounded down to keep the 16-byte alignment the copy buffer also has) to the top of the committed
41 // run of stack pages, at most kMaxStackBytes.
42 stack.original = context.Rsp & ~DWORD64(15);
43 const DWORD64 top = reinterpret_cast<DWORD64>(region.BaseAddress) + region.RegionSize;
44 stack.size = static_cast<size_t>(std::min<DWORD64>(StackSampler::kMaxStackBytes, top - stack.original));
45 SIZE_T read = 0;
46 copied = ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<void*>(stack.original), buffer, stack.size,
47 &read) && read == stack.size;
48 }
49 ResumeThread(thread);
50 stack.copy = reinterpret_cast<DWORD64>(buffer);
51 return copied;
52}
53
54// A frame's code can be unloaded after its thread resumes and a damaged stack can hand the unwinder a bad pointer:
55// both are access violations here, and end the walk.
56bool unwind_frame(CONTEXT& context) {
57 __try {
58 DWORD64 image_base = 0;
59 if (const auto* entry = RtlLookupFunctionEntry(context.Rip, &image_base, nullptr)) {
60 void* handler_data = nullptr;
61 DWORD64 establisher = 0;
62 RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, context.Rip, const_cast<PRUNTIME_FUNCTION>(entry),
63 &context, &handler_data, &establisher, nullptr);
64 } else {
65 // No function entry: a leaf (or a thunk without unwind data) that has not moved RSP.
66 context.Rip = *reinterpret_cast<const DWORD64*>(context.Rsp);
67 context.Rsp += sizeof(DWORD64);
68 }
69 } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR
70 ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
71 return false;
72 }
73 return true;
74}
75
76size_t walk_copy(CONTEXT& context, const CopiedStack& stack, std::uint64_t* frames) {
77 // An address in the copied range now names the same word in the copy.
78 const auto rebase = [&](DWORD64& address) {
79 if (address >= stack.original && address - stack.original < stack.size) address += stack.copy - stack.original;
80 };
81 const auto in_copy = [&](DWORD64 address) {
82 return address >= stack.copy && address - stack.copy + sizeof(DWORD64) <= stack.size;
83 };
84 size_t count = 0;
85 rebase(context.Rsp);
86 while (context.Rip && count < StackSampler::kMaxFrames) {
87 frames[count++] = context.Rip;
88 if (!in_copy(context.Rsp)) break;
89 const DWORD64 rsp = context.Rsp;
90 // Any nonvolatile register can be a frame pointer, including one just restored from the copy's bytes.
91 for (DWORD64* reg : {&context.Rbx, &context.Rbp, &context.Rsi, &context.Rdi,
92 &context.R12, &context.R13, &context.R14, &context.R15})
93 rebase(*reg);
94 if (!unwind_frame(context)) break;
95 rebase(context.Rsp); // A machine frame restores RSP from the copy as well.
96 if (context.Rsp <= rsp) break;
97 }
98 return count;
99}
100
101std::string thread_label(HANDLE thread, GetDescription describe, QueryThread query) {
102 if (describe) {
103 PWSTR description = nullptr;
104 if (SUCCEEDED(describe(thread, &description)) && description) {
105 std::string name = startup_trace::detail::utf8_from_wide(description, static_cast<int>(wcslen(description)));
106 LocalFree(description);
107 if (!name.empty()) return name;
108 }
109 }
110 constexpr int kWin32StartAddress = 9; // ThreadQuerySetWin32StartAddress
111 DWORD64 start = 0;
112 if (query && query(thread, kWin32StartAddress, &start, sizeof(start), nullptr) >= 0 && start)
113 return "start " + shims::module_offset(start);
114 return "start unknown";
115}
116
117struct ThreadTrace {
118 DWORD tid = 0;
119 std::string label;
120 std::array<std::uint64_t, StackSampler::kMaxFrames> frames{};
121 size_t count = 0;
122};
123
124void print_traces(const std::string& tag, const std::vector<ThreadTrace>& traces) {
125 std::string out = "[rt] stacks " + tag + ": " + std::to_string(traces.size()) + " threads\n";
126 for (auto it = traces.begin(); it != traces.end(); ++it) {
127 out += "[rt] stacks " + tag + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n";
128 const auto same = std::find_if(traces.begin(), it, [&](const ThreadTrace& earlier) {
129 return it->count && it->count == earlier.count &&
130 std::equal(it->frames.begin(), it->frames.begin() + it->count, earlier.frames.begin());
131 });
132 if (same != it) {
133 out += " same as thread " + std::to_string(same->tid) + "\n";
134 } else if (!it->count) {
135 out += " stack unavailable\n";
136 } else {
137 for (size_t i = 0; i < it->count; ++i)
138 out += " #" + std::to_string(i) + " " + shims::module_offset(it->frames[i]) + "\n";
139 }
140 }
141 std::fputs(out.c_str(), stderr);
142 std::fflush(stderr);
143}
144
145void snapshot_threads(const std::string& tag, StackSampler& sampler, GetDescription describe, QueryThread query,
146 DWORD only = 0) {
147 const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
148 if (snapshot == INVALID_HANDLE_VALUE) {
149 std::fprintf(stderr, "[rt] stacks %s: thread list failed (error %lu)\n", tag.c_str(), GetLastError());
150 return;
151 }
152 std::vector<ThreadTrace> traces;
153 traces.reserve(512);
154 const DWORD pid = GetCurrentProcessId();
155 const DWORD self = GetCurrentThreadId();
156 THREADENTRY32 entry{};
157 entry.dwSize = sizeof(entry);
158 for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) {
159 entry.dwSize = sizeof(entry);
160 if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue;
161 if (only && entry.th32ThreadID != only) continue;
162 const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
163 FALSE, entry.th32ThreadID);
164 if (!thread) continue;
165 if (GetProcessIdOfThread(thread) == pid) { // The listed thread may have exited and its ID been reused.
166 ThreadTrace& trace = traces.emplace_back();
167 trace.tid = entry.th32ThreadID;
168 trace.label = thread_label(thread, describe, query); // Before sampling: it allocates.
169 trace.count = sampler.sample(thread, trace.frames.data());
170 }
171 CloseHandle(thread);
172 }
173 CloseHandle(snapshot);
174 print_traces(tag, traces);
175}
176
177} // namespace
178
179StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite<std::byte[]>(kMaxStackBytes)) {}
180
181std::size_t StackSampler::sample(void* thread, std::uint64_t* frames) {
182 CONTEXT context{};
183 CopiedStack stack;
184 if (!copy_context_and_stack(static_cast<HANDLE>(thread), context, stack_.get(), stack)) {
185 if (!context.Rip) return 0;
186 frames[0] = context.Rip; // The context without its stack: the innermost frame only.
187 return 1;
188 }
189 return walk_copy(context, stack, frames);
190}
191
192bool parse_stack_times(std::string_view text, std::vector<unsigned>& seconds) {
193 seconds.clear();
194 for (;;) {
195 const auto comma = text.find(',');
196 const auto token = text.substr(0, comma);
197 unsigned value = 0;
198 const auto [end, error] = std::from_chars(token.data(), token.data() + token.size(), value);
199 if (token.empty() || error != std::errc{} || end != token.data() + token.size()) {
200 seconds.clear();
201 return false;
202 }
203 seconds.push_back(value);
204 if (comma == std::string_view::npos) break;
205 text.remove_prefix(comma + 1);
206 }
207 std::sort(seconds.begin(), seconds.end());
208 seconds.erase(std::unique(seconds.begin(), seconds.end()), seconds.end());
209 return true;
210}
211
212void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept {
213 static std::mutex mutex;
214 try {
215 std::lock_guard lock(mutex);
216 static StackSampler sampler;
217 const auto describe = reinterpret_cast<GetDescription>(reinterpret_cast<void*>(
218 GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription")));
219 const auto query = reinterpret_cast<QueryThread>(reinterpret_cast<void*>(
220 GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
221 snapshot_threads(why ? why : "now", sampler, describe, query, tid);
222 } catch (...) {
223 }
224}
225
226std::jthread start_thread_stacks() {
227 const auto start = Clock::now();
228 char spec[1024];
229 const DWORD length = GetEnvironmentVariableA("LEONIDA_STACKS", spec, sizeof(spec));
230 if (!length) return {};
231 std::vector<unsigned> times;
232 if (length >= sizeof(spec) || !parse_stack_times(std::string_view(spec, length), times)) {
233 std::fprintf(stderr, "[rt] LEONIDA_STACKS: expected comma-separated whole seconds\n");
234 return {};
235 }
236 return std::jthread([start, times = std::move(times)](std::stop_token stop) {
237 const auto describe = reinterpret_cast<GetDescription>(reinterpret_cast<void*>(
238 GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription")));
239 const auto query = reinterpret_cast<QueryThread>(reinterpret_cast<void*>(
240 GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")));
241 StackSampler sampler;
242 std::condition_variable_any wake;
243 std::mutex mutex;
244 std::unique_lock lock(mutex);
245 for (const unsigned at : times) {
246 wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; });
247 if (stop.stop_requested()) break;
248 snapshot_threads("t=" + std::to_string(at), sampler, describe, query);
249 }
250 });
251}
252
253} // namespace rt