diff options
| author | Moriz82 <72836413+Moriz82@users.noreply.github.com> | 2026-11-24 11:42:12 -0600 |
|---|---|---|
| committer | Moriz82 <72836413+Moriz82@users.noreply.github.com> | 2026-11-24 11:42:12 -0600 |
| commit | 273b3bdf9d6e736442ad584ad464df6e86ee928b (patch) | |
| tree | 3886a0af7c74ffa7d9415d662d8dc0fb708f1c08 /runtime/src/thread_stacks.cpp | |
| parent | ece4ba5b31ebc6f345c8e29eae1261f2f780057a (diff) | |
[integration] Linux/Proton and native Windows: boot through the story load (RT-PROTON-STORY-LOAD)
One squashed commit of a fork that was developed on a Linux/Proton machine and
tested on two native Windows machines. On all of them the retail 1.0.2.1
package now launches, shows its launch movie, first-run pages and landing
prompt, runs the story load to its end with the loading slideshow drawing its
artwork, and enters the world phase. A first world frame is not verified yet.
docs/linux_proton.md has the setup, a healthy boot's timeline, the machines
and where it stops.
Runtime: frames in the title's own window; DirectStorage pinned reads,
page-list scatter/gather, BCPack and unshuffle with a locally generated
predictor file; pooled, device-local and deferred image backing for streamed
and placed textures; enhanced barriers into LAYOUT_UNDEFINED; a bindless table
that degrades instead of refusing a submission; a descriptor hash finalizer
(off until a library carries it); directly indexed heap offsets for compute
dispatches and VS/PS/GS draws; title buffer windows outside a fragmented
arena; opt-in device-local copies of streamed buffer views; write-fault
retries under the tracker lock, shared trackers and write-watched title memory
for native Windows; device-loss, compute-input and memory probes.
Translator: loop bounds at structured exits, the eight FidelityFX programs
that use a packed-dot form the disassembler skips, buffer bounds modes per
view kind, a compaction option, the hash finalizer option.
Tools and scripts: Linux boot scripts (Wine/Proton, no network), a Windows
boot script, the paired compute translation script.
No game data. AI-assisted (Claude Code and Codex agents), reviewed and booted
by people on the machines named in docs/linux_proton.md.
Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com>
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 | ||