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:
authorOreoFR <29048345+OreoFR@users.noreply.github.com>2026-11-29 13:51:28 +0100
committerOreoFR <29048345+OreoFR@users.noreply.github.com>2026-11-29 13:51:28 +0100
commit3beeb56bfb3dc99f60e85e85211ba3c2d88223bc (patch)
tree5f563496290a7775a669864fbf61d85b9161cfd8 /runtime/src/thread_stacks.cpp
parented34b996ce2aef1ae2800b0f0840ca6878b89b73 (diff)
parentcc0f662a70b6e6e561692f56342b5a7df3831bd7 (diff)
Merge origin/main into carry/pr-2031
submit_phases: main's nested-phase Scope kept; the PR's skip now applies only when nothing reads the times (timing_wanted(): period 0 and LEONIDA_DEV_OVERLAY not 1). Co-authored-by: Ilyass Roussi <76879547+IlyassRS3@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src/thread_stacks.cpp')
-rw-r--r--runtime/src/thread_stacks.cpp70
1 files changed, 52 insertions, 18 deletions
diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp
index 67188d908..d87d91482 100644
--- a/runtime/src/thread_stacks.cpp
+++ b/runtime/src/thread_stacks.cpp
@@ -9,6 +9,7 @@
9#include <chrono> 9#include <chrono>
10#include <condition_variable> 10#include <condition_variable>
11#include <cstdio> 11#include <cstdio>
12#include <limits>
12#include <mutex> 13#include <mutex>
13#include <string> 14#include <string>
14 15
@@ -39,12 +40,18 @@ bool copy_context_and_stack(HANDLE thread, CONTEXT& context, std::byte* buffer,
39 region.State == MEM_COMMIT && !(region.Protect & (PAGE_GUARD | PAGE_NOACCESS))) { 40 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 // 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 // run of stack pages, at most kMaxStackBytes.
43 const DWORD64 base = reinterpret_cast<DWORD64>(region.BaseAddress);
42 stack.original = context.Rsp & ~DWORD64(15); 44 stack.original = context.Rsp & ~DWORD64(15);
43 const DWORD64 top = reinterpret_cast<DWORD64>(region.BaseAddress) + region.RegionSize; 45 if (region.RegionSize > 0 && region.RegionSize <= std::numeric_limits<DWORD64>::max() - base) {
44 stack.size = static_cast<size_t>(std::min<DWORD64>(StackSampler::kMaxStackBytes, top - stack.original)); 46 const DWORD64 top = base + region.RegionSize;
45 SIZE_T read = 0; 47 if (stack.original >= base && top > stack.original) {
46 copied = ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<void*>(stack.original), buffer, stack.size, 48 stack.size = static_cast<size_t>(std::min<DWORD64>(StackSampler::kMaxStackBytes, top - stack.original));
47 &read) && read == stack.size; 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 }
48 } 55 }
49 ResumeThread(thread); 56 ResumeThread(thread);
50 stack.copy = reinterpret_cast<DWORD64>(buffer); 57 stack.copy = reinterpret_cast<DWORD64>(buffer);
@@ -79,7 +86,8 @@ size_t walk_copy(CONTEXT& context, const CopiedStack& stack, std::uint64_t* fram
79 if (address >= stack.original && address - stack.original < stack.size) address += stack.copy - stack.original; 86 if (address >= stack.original && address - stack.original < stack.size) address += stack.copy - stack.original;
80 }; 87 };
81 const auto in_copy = [&](DWORD64 address) { 88 const auto in_copy = [&](DWORD64 address) {
82 return address >= stack.copy && address - stack.copy + sizeof(DWORD64) <= stack.size; 89 return stack.size >= sizeof(DWORD64) && address >= stack.copy &&
90 address - stack.copy <= stack.size - sizeof(DWORD64);
83 }; 91 };
84 size_t count = 0; 92 size_t count = 0;
85 rebase(context.Rsp); 93 rebase(context.Rsp);
@@ -102,7 +110,10 @@ std::string thread_label(HANDLE thread, GetDescription describe, QueryThread que
102 if (describe) { 110 if (describe) {
103 PWSTR description = nullptr; 111 PWSTR description = nullptr;
104 if (SUCCEEDED(describe(thread, &description)) && description) { 112 if (SUCCEEDED(describe(thread, &description)) && description) {
105 std::string name = startup_trace::detail::utf8_from_wide(description, static_cast<int>(wcslen(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);
106 LocalFree(description); 117 LocalFree(description);
107 if (!name.empty()) return name; 118 if (!name.empty()) return name;
108 } 119 }
@@ -121,10 +132,10 @@ struct ThreadTrace {
121 size_t count = 0; 132 size_t count = 0;
122}; 133};
123 134
124void print_traces(unsigned at, const std::vector<ThreadTrace>& traces) { 135void print_traces(const std::string& tag, const std::vector<ThreadTrace>& traces) {
125 std::string out = "[rt] stacks t=" + std::to_string(at) + ": " + std::to_string(traces.size()) + " threads\n"; 136 std::string out = "[rt] stacks " + tag + ": " + std::to_string(traces.size()) + " threads\n";
126 for (auto it = traces.begin(); it != traces.end(); ++it) { 137 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"; 138 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) { 139 const auto same = std::find_if(traces.begin(), it, [&](const ThreadTrace& earlier) {
129 return it->count && it->count == earlier.count && 140 return it->count && it->count == earlier.count &&
130 std::equal(it->frames.begin(), it->frames.begin() + it->count, earlier.frames.begin()); 141 std::equal(it->frames.begin(), it->frames.begin() + it->count, earlier.frames.begin());
@@ -142,10 +153,11 @@ void print_traces(unsigned at, const std::vector<ThreadTrace>& traces) {
142 std::fflush(stderr); 153 std::fflush(stderr);
143} 154}
144 155
145void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describe, QueryThread query) { 156void snapshot_threads(const std::string& tag, StackSampler& sampler, GetDescription describe, QueryThread query,
157 DWORD only = 0) {
146 const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); 158 const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
147 if (snapshot == INVALID_HANDLE_VALUE) { 159 if (snapshot == INVALID_HANDLE_VALUE) {
148 std::fprintf(stderr, "[rt] stacks t=%u: thread list failed (error %lu)\n", at, GetLastError()); 160 std::fprintf(stderr, "[rt] stacks %s: thread list failed (error %lu)\n", tag.c_str(), GetLastError());
149 return; 161 return;
150 } 162 }
151 std::vector<ThreadTrace> traces; 163 std::vector<ThreadTrace> traces;
@@ -157,6 +169,7 @@ void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describ
157 for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) { 169 for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) {
158 entry.dwSize = sizeof(entry); 170 entry.dwSize = sizeof(entry);
159 if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue; 171 if (entry.th32OwnerProcessID != pid || entry.th32ThreadID == self) continue;
172 if (only && entry.th32ThreadID != only) continue;
160 const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 173 const HANDLE thread = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
161 FALSE, entry.th32ThreadID); 174 FALSE, entry.th32ThreadID);
162 if (!thread) continue; 175 if (!thread) continue;
@@ -169,7 +182,7 @@ void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describ
169 CloseHandle(thread); 182 CloseHandle(thread);
170 } 183 }
171 CloseHandle(snapshot); 184 CloseHandle(snapshot);
172 print_traces(at, traces); 185 print_traces(tag, traces);
173} 186}
174 187
175} // namespace 188} // namespace
@@ -177,6 +190,7 @@ void snapshot_threads(unsigned at, StackSampler& sampler, GetDescription describ
177StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite<std::byte[]>(kMaxStackBytes)) {} 190StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite<std::byte[]>(kMaxStackBytes)) {}
178 191
179std::size_t StackSampler::sample(void* thread, std::uint64_t* frames) { 192std::size_t StackSampler::sample(void* thread, std::uint64_t* frames) {
193 if (!thread || !frames) return 0;
180 CONTEXT context{}; 194 CONTEXT context{};
181 CopiedStack stack; 195 CopiedStack stack;
182 if (!copy_context_and_stack(static_cast<HANDLE>(thread), context, stack_.get(), stack)) { 196 if (!copy_context_and_stack(static_cast<HANDLE>(thread), context, stack_.get(), stack)) {
@@ -207,6 +221,20 @@ bool parse_stack_times(std::string_view text, std::vector<unsigned>& seconds) {
207 return true; 221 return true;
208} 222}
209 223
224void 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
210std::jthread start_thread_stacks() { 238std::jthread start_thread_stacks() {
211 const auto start = Clock::now(); 239 const auto start = Clock::now();
212 char spec[1024]; 240 char spec[1024];
@@ -218,10 +246,16 @@ std::jthread start_thread_stacks() {
218 return {}; 246 return {};
219 } 247 }
220 return std::jthread([start, times = std::move(times)](std::stop_token stop) { 248 return std::jthread([start, times = std::move(times)](std::stop_token stop) {
221 const auto describe = reinterpret_cast<GetDescription>(reinterpret_cast<void*>( 249 const HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll");
222 GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"))); 250 const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
223 const auto query = reinterpret_cast<QueryThread>(reinterpret_cast<void*>( 251 const auto describe =
224 GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); 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;
225 StackSampler sampler; 259 StackSampler sampler;
226 std::condition_variable_any wake; 260 std::condition_variable_any wake;
227 std::mutex mutex; 261 std::mutex mutex;
@@ -229,7 +263,7 @@ std::jthread start_thread_stacks() {
229 for (const unsigned at : times) { 263 for (const unsigned at : times) {
230 wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; }); 264 wake.wait_until(lock, stop, start + std::chrono::seconds(at), [] { return false; });
231 if (stop.stop_requested()) break; 265 if (stop.stop_requested()) break;
232 snapshot_threads(at, sampler, describe, query); 266 snapshot_threads("t=" + std::to_string(at), sampler, describe, query);
233 } 267 }
234 }); 268 });
235} 269}