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