diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:26:00 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:26:00 -0500 |
| commit | 154e4ec034902deffa4b89b2cbca9a949f38baec (patch) | |
| tree | 1b2ef5656de42c172291bc6009efa4c510650815 /runtime/src/thread_stacks.cpp | |
| parent | eb6a08cd359d98b5777e70d54d0ae8a75879495a (diff) | |
| parent | 8a242efebf823aeb23c72d17c3d666daf0bbd3e2 (diff) | |
Merge the #984 result (main + RT-PROTON-STORY-LOAD) into #939
The base is 8a242efeb, the merge of main and #984. 68 files conflicted; they were resolved in seven groups by
one rule: the same change in two forms keeps the base's form, everything only #939 has is kept, and where the
two solve one problem in two ways the base's is the frame and #939's plugs into it.
A, the Xbox proxy (d3d12_xs_device.cpp/.h, d3d12_xs.cpp, d3d12_xs_pso_stream.cpp/.h, d3d12_xs_alloc_size.h,
d3d12_xs_desc_clean.h, device_proxy_test.cpp, queue_proxy_test.cpp): the base's files with #939's additions
ported in. Device slot 57 asks #939's NativeGraphicsFactory first and falls back to the base's
proxy_create_graphics_pipeline_from_native_code on E_NOTIMPL. Kept from #939: the providers (texture lease,
raw texture view, resource by address, constant view, descriptor mapping, depth-stencil UAV, texture pages),
the title-backed descriptor mirror, slot 13's feature answers, GPU labels on list slots 71/72. Dropped: #939's
duplicates of the boot ladder routes, its fallback window, its slot 133 stand-in.
A2 (xs_proxy_mock_test.cpp): the base's test with #939's slot 70 raw-buffer case; presentation cases follow
#939's rule that a device which ever had a handler has no queue fallback.
B1, the Vulkan device (d3d12_vulkan_device.cpp, d3d12_com.cpp/.h, shader_library.h, queue_families.h,
pipeline_cache_file.h, startup_trace.h): one lazy-pipeline mechanism, the base's; #939's pending_base_compile
and first_use_backend_pipelines dropped, prepare_on_bind and cold_graphics_compile kept. create_texture keeps
the base's signature; #939's deferred backing is folded into the base's placed-memory binder. #939's quad
lists as triangle indices.
B2, the D3D12 tests (d3d12_existing_heap, a8_dimensions, pipeline_cache_seed, title_va, rect_list,
shader_library, loader_tls_index0, draw, compute, xmem_placed, shader_library_corpus): the base's tests where
both carry the same case, #939's cases added (rebound tables, linear texture map, large vertex batch,
executable shaders, default A8 views).
C, the backend (vulkan_replay.h, vulkan_backend.h, vulkan_bindless.h, vulkan_scratch.h, vulkan_present.h,
rect_list_geometry.h, vk_test_device.h, vk_pipeline_check.cpp, vk_store_test.cpp, bindless_sizing_test.cpp,
replay_texture_barrier_test.cpp): the base's prepare_draw and lazy compute, its #1055 release rule and its
rectangle generator; #939's rectangle variants, GPU quad index expansion, 1D/3D and depth-stencil UAVs, the
label fence on the base's submit.
D, memory, services, presentation (xmem.cpp/.h, xg_xs.cpp, xg_xs_test.cpp, title_va_alias.h and its test,
main.cpp, frame_pacer.h, xbox_present.cpp/.h; xgameruntime_offline.cpp for one comment): the base's xmem with
#939's label hooks, file-backed sections and pin_mapped_data; both texture computers in xg_xs.cpp, the base's
answering first; --first-run-ui kept without host speech in its profile.
E, build, tools, docs (runtime/CMakeLists.txt, make_game.py, tools/rdna2spirv.py, tools/shader_disasm.py,
scripts, tests, docs; docs/README.md and tests/test_exe_shaders_stage.py beyond the conflicts): the base's
v_dot4 decode, #281's disassembler form and tests/semantic/test_fspx_dot4_op_sel_disasm.py dropped; the
base's executable-shader step with #939's cache fix; 366 registered tests.
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.cpp | 237 |
1 files changed, 237 insertions, 0 deletions
diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp new file mode 100644 index 000000000..67188d908 --- /dev/null +++ b/runtime/src/thread_stacks.cpp | |||
| @@ -0,0 +1,237 @@ | |||
| 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 | |||
| 18 | namespace rt { | ||
| 19 | namespace { | ||
| 20 | |||
| 21 | using Clock = std::chrono::steady_clock; | ||
| 22 | using GetDescription = HRESULT(WINAPI*)(HANDLE, PWSTR*); | ||
| 23 | using QueryThread = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); | ||
| 24 | |||
| 25 | struct 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. | ||
| 32 | bool 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), ®ion, 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. | ||
| 56 | bool 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 | |||
| 76 | size_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 | |||
| 101 | std::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 | |||
| 117 | struct 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 | |||
| 124 | void print_traces(unsigned at, const std::vector<ThreadTrace>& traces) { | ||
| 125 | std::string out = "[rt] stacks t=" + std::to_string(at) + ": " + std::to_string(traces.size()) + " threads\n"; | ||
| 126 | for (auto it = traces.begin(); it != traces.end(); ++it) { | ||
| 127 | out += "[rt] stacks t=" + std::to_string(at) + " 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 | |||
| 145 | void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describe, QueryThread query) { | ||
| 146 | const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); | ||
| 147 | if (snapshot == INVALID_HANDLE_VALUE) { | ||
| 148 | std::fprintf(stderr, "[rt] stacks t=%u: thread list failed (error %lu)\n", at, GetLastError()); | ||
| 149 | return; | ||
| 150 | } | ||
| 151 | std::vector<ThreadTrace> traces; | ||
| 152 | traces.reserve(512); | ||
| 153 | const DWORD pid = GetCurrentProcessId(); | ||
| 154 | const DWORD self = GetCurrentThreadId(); | ||
| 155 | THREADENTRY32 entry{}; | ||
| 156 | entry.dwSize = sizeof(entry); | ||
| 157 | for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) { | ||
| 158 | entry.dwSize = sizeof(entry); | ||
| 159 | if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue; | ||
| 160 | const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, | ||
| 161 | FALSE, entry.th32ThreadID); | ||
| 162 | if (!thread) continue; | ||
| 163 | if (GetProcessIdOfThread(thread) == pid) { // The listed thread may have exited and its ID been reused. | ||
| 164 | ThreadTrace& trace = traces.emplace_back(); | ||
| 165 | trace.tid = entry.th32ThreadID; | ||
| 166 | trace.label = thread_label(thread, describe, query); // Before sampling: it allocates. | ||
| 167 | trace.count = sampler.sample(thread, trace.frames.data()); | ||
| 168 | } | ||
| 169 | CloseHandle(thread); | ||
| 170 | } | ||
| 171 | CloseHandle(snapshot); | ||
| 172 | print_traces(at, traces); | ||
| 173 | } | ||
| 174 | |||
| 175 | } // namespace | ||
| 176 | |||
| 177 | StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite<std::byte[]>(kMaxStackBytes)) {} | ||
| 178 | |||
| 179 | std::size_t StackSampler::sample(void* thread, std::uint64_t* frames) { | ||
| 180 | CONTEXT context{}; | ||
| 181 | CopiedStack stack; | ||
| 182 | if (!copy_context_and_stack(static_cast<HANDLE>(thread), context, stack_.get(), stack)) { | ||
| 183 | if (!context.Rip) return 0; | ||
| 184 | frames[0] = context.Rip; // The context without its stack: the innermost frame only. | ||
| 185 | return 1; | ||
| 186 | } | ||
| 187 | return walk_copy(context, stack, frames); | ||
| 188 | } | ||
| 189 | |||
| 190 | bool parse_stack_times(std::string_view text, std::vector<unsigned>& seconds) { | ||
| 191 | seconds.clear(); | ||
| 192 | for (;;) { | ||
| 193 | const auto comma = text.find(','); | ||
| 194 | const auto token = text.substr(0, comma); | ||
| 195 | unsigned value = 0; | ||
| 196 | const auto [end, error] = std::from_chars(token.data(), token.data() + token.size(), value); | ||
| 197 | if (token.empty() || error != std::errc{} || end != token.data() + token.size()) { | ||
| 198 | seconds.clear(); | ||
| 199 | return false; | ||
| 200 | } | ||
| 201 | seconds.push_back(value); | ||
| 202 | if (comma == std::string_view::npos) break; | ||
| 203 | text.remove_prefix(comma + 1); | ||
| 204 | } | ||
| 205 | std::sort(seconds.begin(), seconds.end()); | ||
| 206 | seconds.erase(std::unique(seconds.begin(), seconds.end()), seconds.end()); | ||
| 207 | return true; | ||
| 208 | } | ||
| 209 | |||
| 210 | std::jthread start_thread_stacks() { | ||
| 211 | const auto start = Clock::now(); | ||
| 212 | char spec[1024]; | ||
| 213 | const DWORD length = GetEnvironmentVariableA("LEONIDA_STACKS", spec, sizeof(spec)); | ||
| 214 | if (!length) return {}; | ||
| 215 | std::vector<unsigned> times; | ||
| 216 | if (length >= sizeof(spec) || !parse_stack_times(std::string_view(spec, length), times)) { | ||
| 217 | std::fprintf(stderr, "[rt] LEONIDA_STACKS: expected comma-separated whole seconds\n"); | ||
| 218 | return {}; | ||
| 219 | } | ||
| 220 | return std::jthread([start, times = std::move(times)](std::stop_token stop) { | ||
| 221 | const auto describe = reinterpret_cast<GetDescription>(reinterpret_cast<void*>( | ||
| 222 | GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"))); | ||
| 223 | const auto query = reinterpret_cast<QueryThread>(reinterpret_cast<void*>( | ||
| 224 | GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); | ||
| 225 | StackSampler sampler; | ||
| 226 | std::condition_variable_any wake; | ||
| 227 | std::mutex mutex; | ||
| 228 | std::unique_lock lock(mutex); | ||
| 229 | for (const unsigned at : times) { | ||
| 230 | wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; }); | ||
| 231 | if (stop.stop_requested()) break; | ||
| 232 | snapshot_threads(at, sampler, describe, query); | ||
| 233 | } | ||
| 234 | }); | ||
| 235 | } | ||
| 236 | |||
| 237 | } // namespace rt | ||