upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src/thread_sampler.h
diff options
context:
space:
mode:
authorMoriz82 <72836413+Moriz82@users.noreply.github.com>2026-11-25 03:44:31 -0600
committerMoriz82 <72836413+Moriz82@users.noreply.github.com>2026-11-25 03:44:43 -0600
commitba626820ec54776fb0faffa2413727285befe85b (patch)
tree95a99f8029785bec5f3b07b7efc4277e5bc7510b /runtime/src/thread_sampler.h
parent3de22a19047b168d28a7a11152bf05d18ed0062e (diff)
Integrate post-story-load memory, queue and Vulkan runtime changes
Preserve physical window aliases across remaps, order console list values, and replay bounded indirect graphics with captured draw state. Coordinate pipeline lifetime, texture refresh and queue teardown. Add synthetic CPU and GPU coverage for the integrated paths. Co-authored-by: Plaaasma <47513553+Plaaasma@users.noreply.github.com> Co-authored-by: ivanepsilondelta <264061546+ivanepsilondelta@users.noreply.github.com>
Diffstat (limited to 'runtime/src/thread_sampler.h')
-rw-r--r--runtime/src/thread_sampler.h401
1 files changed, 401 insertions, 0 deletions
diff --git a/runtime/src/thread_sampler.h b/runtime/src/thread_sampler.h
new file mode 100644
index 000000000..9166fe552
--- /dev/null
+++ b/runtime/src/thread_sampler.h
@@ -0,0 +1,401 @@
1#pragma once
2// LEONIDA_SAMPLE_MS=<ms> (diagnostic, off by default): where the process's busy threads spend their CPU, without a
3// debugger or perf. A thread wakes every <ms>, and for each thread of the process that used CPU since its last look
4// suspends it, copies its context and resumes it at once; the stack is then unwound outside the suspension (through
5// the .pdata every module registers, the title's included), under __try, since the thread runs on meanwhile. Every
6// LEONIDA_SAMPLE_REPORT_S seconds (10) one block lists the busiest threads (CPU share) and the most frequent call
7// chains (up to eight frames, innermost first): title frames as t+RVA of the function, others as module+RVA. Nothing is
8// allocated or logged while a thread is suspended, so a suspended thread's locks are never waited for.
9#include <windows.h>
10#include <tlhelp32.h>
11
12#include <algorithm>
13#include <array>
14#include <cstdint>
15#include <cstdio>
16#include <cstdlib>
17#include <map>
18#include <string>
19#include <vector>
20
21#include "submit_phases.h"
22
23namespace leonida::thread_sampler {
24
25constexpr int kFrames = 8;
26using Chain = std::array<std::uint64_t, kFrames>; // function starts (or addresses), innermost first
27// LEONIDA_SAMPLE_SHIMS=1 (with LEONIDA_SAMPLE_MS): each sample is unwound this deep to tell whether a title thread
28// is inside our runtime (a frame of this executable called, at any depth, from title code), and where.
29constexpr int kDeepFrames = 48;
30using DeepChain = std::array<std::uint64_t, kDeepFrames>;
31
32
33struct Sampler {
34 std::uint8_t* title = nullptr;
35 std::uint64_t title_size = 0;
36 DWORD period_ms = 10;
37 DWORD report_ms = 10000;
38 bool waits = false; // LEONIDA_SAMPLE_WAITS=1: every thread, busy or waiting (where the wall time goes)
39 bool shims = false; // LEONIDA_SAMPLE_SHIMS=1: per title thread, the share of its samples inside our runtime
40 std::uint64_t self_base = 0, self_size = 0; // this executable (the runtime)
41 // LEONIDA_SAMPLE_DETAIL=<id>[,<id>...]: for these threads, the 10 most frequent chains, 16 frames deep, each as a
42 // share of that thread's samples (thread ids are stable from boot to boot: the title's main, render and submit).
43 std::vector<DWORD> detail;
44};
45
46// Per title thread (one with a title frame in its chain): how many samples were inside our runtime, and through which
47// entry (the runtime frame the title called) and which runtime function was innermost.
48struct ShimCounts {
49 std::uint64_t title = 0; // samples with a title frame
50 std::uint64_t ours = 0; // ... of which inside our runtime
51 std::uint64_t ours_busy = 0; // ... while the thread used CPU since the previous look
52 std::uint64_t busy = 0; // samples with a title frame while the thread used CPU
53 std::map<std::pair<std::uint64_t, std::uint64_t>, std::uint64_t> entries; // (our entry, title caller) -> samples
54 std::map<std::uint64_t, std::uint64_t> inner; // innermost runtime function -> samples
55 std::map<std::uint64_t, std::uint64_t> leaves; // innermost frame (any module) -> samples
56};
57
58// Classifies one deep chain (innermost first) for LEONIDA_SAMPLE_SHIMS.
59inline void count_shims(const Sampler& s, const DeepChain& chain, int n, bool moved, ShimCounts& c) {
60 const auto title = reinterpret_cast<std::uint64_t>(s.title);
61 const auto in_title = [&](std::uint64_t a) { return a >= title && a < title + s.title_size; };
62 const auto in_self = [&](std::uint64_t a) { return a >= s.self_base && a < s.self_base + s.self_size; };
63 int first_title = -1;
64 for (int i = 0; i < n; ++i)
65 if (in_title(chain[i])) {
66 first_title = i;
67 break;
68 }
69 if (first_title < 0) return;
70 ++c.title;
71 c.busy += moved;
72 int entry = -1, innermost = -1;
73 for (int i = 0; i < first_title; ++i)
74 if (in_self(chain[i])) {
75 if (innermost < 0) innermost = i;
76 entry = i; // the outermost runtime frame below the title's
77 }
78 if (entry < 0) return;
79 ++c.ours;
80 c.ours_busy += moved;
81 ++c.entries[{chain[entry], chain[first_title]}];
82 ++c.inner[chain[innermost]];
83 ++c.leaves[chain[0]];
84}
85
86// The chain of a context copied from a suspended thread: unwound under __try (its stack may be changing).
87template <std::size_t N>
88inline int unwind(CONTEXT context, std::array<std::uint64_t, N>& chain) {
89 int n = 0;
90 __try {
91 for (; n < int(N); ++n) {
92 const DWORD64 pc = context.Rip;
93 if (!pc) break;
94 DWORD64 image = 0;
95 PRUNTIME_FUNCTION entry = RtlLookupFunctionEntry(pc, &image, nullptr);
96 chain[n] = entry ? image + entry->BeginAddress : pc;
97 if (!entry) { // a leaf, or code with no unwind data: take the return address at the stack pointer
98 context.Rip = *reinterpret_cast<const DWORD64*>(context.Rsp);
99 context.Rsp += 8;
100 continue;
101 }
102 void* handler_data = nullptr;
103 DWORD64 frame = 0;
104 RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, pc, entry, &context, &handler_data, &frame, nullptr);
105 }
106 } __except (EXCEPTION_EXECUTE_HANDLER) {
107 }
108 return n;
109}
110
111inline std::string name_of(const Sampler& s, std::uint64_t at) {
112 char text[96];
113 const auto title = reinterpret_cast<std::uint64_t>(s.title);
114 if (at >= title && at < title + s.title_size) {
115 std::snprintf(text, sizeof(text), "t+%llx", static_cast<unsigned long long>(at - title));
116 return text;
117 }
118 HMODULE module = nullptr;
119 if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
120 reinterpret_cast<LPCWSTR>(at), &module) &&
121 module) {
122 wchar_t path[MAX_PATH] = {};
123 GetModuleFileNameW(module, path, MAX_PATH);
124 const wchar_t* base = path;
125 for (const wchar_t* p = path; *p; ++p)
126 if (*p == L'\\' || *p == L'/') base = p + 1;
127 std::snprintf(text, sizeof(text), "%ls+%llx", base,
128 static_cast<unsigned long long>(at - reinterpret_cast<std::uint64_t>(module)));
129 return text;
130 }
131 std::snprintf(text, sizeof(text), "0x%llx", static_cast<unsigned long long>(at));
132 return text;
133}
134
135inline DWORD WINAPI run(LPVOID parameter) {
136 const Sampler s = *static_cast<Sampler*>(parameter);
137 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
138 const DWORD self = GetCurrentThreadId(), pid = GetCurrentProcessId();
139 struct Thread {
140 HANDLE handle = nullptr;
141 std::uint64_t cpu = 0; // 100 ns, at the last look
142 std::uint64_t used = 0; // since the last report
143 std::uint64_t samples = 0;
144 };
145 std::map<DWORD, Thread> threads;
146 std::map<std::pair<DWORD, Chain>, std::uint64_t> chains;
147 std::map<DWORD, ShimCounts> shim_counts;
148 constexpr int kDetailFrames = 16;
149 using DetailChain = std::array<std::uint64_t, kDetailFrames>;
150 std::map<std::pair<DWORD, DetailChain>, std::uint64_t> detail_chains;
151 std::uint64_t total = 0;
152 ULONGLONG listed = 0, reported = GetTickCount64();
153 const auto cpu_of = [](HANDLE h) {
154 FILETIME created{}, exited{}, kernel{}, user{};
155 if (!GetThreadTimes(h, &created, &exited, &kernel, &user)) return std::uint64_t(0);
156 const auto ticks = [](const FILETIME& f) { return (std::uint64_t(f.dwHighDateTime) << 32) | f.dwLowDateTime; };
157 return ticks(kernel) + ticks(user);
158 };
159 for (;;) {
160 Sleep(s.period_ms);
161 const ULONGLONG now = GetTickCount64();
162 if (now - listed >= 2000) { // the thread list, every 2 s
163 listed = now;
164 const HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
165 if (snap != INVALID_HANDLE_VALUE) {
166 THREADENTRY32 e{sizeof(e)};
167 for (BOOL ok = Thread32First(snap, &e); ok; ok = Thread32Next(snap, &e)) {
168 if (e.th32OwnerProcessID != pid || e.th32ThreadID == self || threads.count(e.th32ThreadID)) continue;
169 const HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,
170 FALSE, e.th32ThreadID);
171 if (h) threads[e.th32ThreadID] = {h, cpu_of(h)};
172 e.dwSize = sizeof(e);
173 }
174 CloseHandle(snap);
175 }
176 }
177 for (auto it = threads.begin(); it != threads.end();) {
178 Thread& t = it->second;
179 const std::uint64_t cpu = cpu_of(t.handle);
180 DWORD code = 0;
181 if (GetExitCodeThread(t.handle, &code) && code != STILL_ACTIVE) {
182 CloseHandle(t.handle);
183 it = threads.erase(it);
184 continue;
185 }
186 const bool moved = cpu != t.cpu;
187 const bool busy = moved || s.waits;
188 t.used += cpu - t.cpu;
189 t.cpu = cpu;
190 if (busy) {
191 CONTEXT context{};
192 context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
193 bool got = false;
194 if (SuspendThread(t.handle) != DWORD(-1)) {
195 got = GetThreadContext(t.handle, &context) != FALSE;
196 ResumeThread(t.handle);
197 }
198 if (got) {
199 Chain chain{};
200 if (std::find(s.detail.begin(), s.detail.end(), it->first) != s.detail.end()) {
201 DetailChain deep{};
202 unwind(context, deep);
203 ++detail_chains[{it->first, deep}];
204 }
205 if (s.shims) {
206 DeepChain deep{};
207 const int n = unwind(context, deep);
208 std::copy_n(deep.begin(), kFrames, chain.begin());
209 count_shims(s, deep, n, moved, shim_counts[it->first]);
210 } else {
211 unwind(context, chain);
212 }
213 ++chains[{it->first, chain}];
214 ++t.samples;
215 ++total;
216 }
217 }
218 ++it;
219 }
220 if (now - reported < s.report_ms || !total) continue;
221 const double seconds = double(now - reported) / 1000.0;
222 reported = now;
223 std::vector<std::pair<std::uint64_t, DWORD>> busiest;
224 for (auto& [id, t] : threads)
225 if (t.used) busiest.emplace_back(t.used, id);
226 std::sort(busiest.rbegin(), busiest.rend());
227 std::string line;
228 for (std::size_t i = 0; i < busiest.size() && i < 8; ++i) {
229 char text[64];
230 std::snprintf(text, sizeof(text), "%s%lu %.0f%%", i ? ", " : "", busiest[i].second,
231 double(busiest[i].first) * 1e-5 / seconds);
232 line += text;
233 }
234 std::fprintf(stderr, "[rt] sampler: %llu samples in %.0f s; CPU by thread: %s\n",
235 static_cast<unsigned long long>(total), seconds, line.c_str());
236 std::vector<std::pair<std::uint64_t, const std::pair<DWORD, Chain>*>> top;
237 for (const auto& c : chains) top.emplace_back(c.second, &c.first);
238 std::sort(top.begin(), top.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
239 const auto print = [&](const auto& entry, std::uint64_t of, const char* what) {
240 std::string frames;
241 for (int f = 0; f < kFrames && entry.second->second[f]; ++f)
242 frames += (f ? " < " : "") + name_of(s, entry.second->second[f]);
243 std::fprintf(stderr, "[rt] sampler: %s %5.1f%% thread %lu: %s\n", what, 100.0 * double(entry.first) / double(of),
244 entry.second->first, frames.c_str());
245 };
246 for (std::size_t i = 0; i < top.size() && i < 16; ++i) print(top[i], total, " ");
247 // Apart: the submitting thread's chains, and the two busiest threads', each as a share of that thread's samples.
248 std::vector<DWORD> apart;
249 if (const DWORD submitter = submit_phases::totals().thread.load(std::memory_order_relaxed)) apart.push_back(submitter);
250 for (std::size_t i = 0; i < busiest.size() && i < 2; ++i)
251 if (std::find(apart.begin(), apart.end(), busiest[i].second) == apart.end()) apart.push_back(busiest[i].second);
252 // With waiting threads sampled: each thread's own most frequent chain, busiest first, so a thread that waits
253 // (the title's main thread behind its render thread, a render thread behind a lock) shows where.
254 if (s.waits) {
255 std::vector<std::pair<std::uint64_t, DWORD>> all;
256 for (auto& [id, t] : threads)
257 if (t.samples) all.emplace_back(t.used, id);
258 std::sort(all.rbegin(), all.rend());
259 std::size_t listed = 0;
260 for (const auto& [used, id] : all) {
261 if (listed++ >= 24) break;
262 const auto it = threads.find(id);
263 if (it == threads.end() || !it->second.samples) continue;
264 for (const auto& entry : top)
265 if (entry.second->first == id) {
266 print(entry, it->second.samples, "thread");
267 break;
268 }
269 }
270 }
271 for (const DWORD id : apart) {
272 const auto it = threads.find(id);
273 if (it == threads.end() || !it->second.samples) continue;
274 std::size_t shown = 0;
275 for (const auto& entry : top)
276 if (entry.second->first == id && shown++ < 8)
277 print(entry, it->second.samples, id == apart.front() && submit_phases::totals().thread.load() == id
278 ? "submit"
279 : "busy ");
280 }
281 for (const DWORD id : s.detail) {
282 std::vector<std::pair<std::uint64_t, const DetailChain*>> mine;
283 std::uint64_t all = 0;
284 for (const auto& [key, n] : detail_chains)
285 if (key.first == id) {
286 mine.emplace_back(n, &key.second);
287 all += n;
288 }
289 std::sort(mine.begin(), mine.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
290 for (std::size_t i = 0; i < mine.size() && i < 10; ++i) {
291 std::string frames;
292 for (int f = 0; f < kDetailFrames && (*mine[i].second)[f]; ++f)
293 frames += (f ? " < " : "") + name_of(s, (*mine[i].second)[f]);
294 std::fprintf(stderr, "[rt] sampler: detail thread %lu %5.1f%%: %s\n", id,
295 100.0 * double(mine[i].first) / double(all), frames.c_str());
296 }
297 }
298 detail_chains.clear();
299 if (s.shims) {
300 // Title threads by their samples inside our runtime: where the title's own threads (its main, render and
301 // Subrender workers, streaming) spend time in our shims, waiting or running.
302 const auto top_of = [&](const auto& counts, std::size_t limit, bool pair_key) {
303 std::vector<std::pair<std::uint64_t, std::string>> v;
304 for (const auto& [key, n] : counts) {
305 std::string name;
306 if constexpr (requires { key.first; }) {
307 name = name_of(s, key.first) + "<-" + name_of(s, key.second);
308 } else {
309 name = name_of(s, key);
310 }
311 v.emplace_back(n, std::move(name));
312 }
313 (void)pair_key;
314 std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
315 std::string text;
316 for (std::size_t i = 0; i < v.size() && i < limit; ++i) {
317 char n[24];
318 std::snprintf(n, sizeof(n), " %llu", static_cast<unsigned long long>(v[i].first));
319 text += (i ? ", " : "") + v[i].second + n;
320 }
321 return text;
322 };
323 std::vector<std::pair<std::uint64_t, DWORD>> order;
324 ShimCounts all;
325 for (const auto& [id, c] : shim_counts) {
326 if (!c.title) continue;
327 order.emplace_back(c.ours, id);
328 all.title += c.title;
329 all.ours += c.ours;
330 all.ours_busy += c.ours_busy;
331 all.busy += c.busy;
332 for (const auto& [k, n] : c.entries) all.entries[k] += n;
333 for (const auto& [k, n] : c.inner) all.inner[k] += n;
334 for (const auto& [k, n] : c.leaves) all.leaves[k] += n;
335 }
336 std::sort(order.rbegin(), order.rend());
337 std::fprintf(stderr, "[rt] sampler: shims: title-thread samples inside our runtime %llu of %llu (%.1f%%), "
338 "%llu of them while the thread used CPU\n",
339 static_cast<unsigned long long>(all.ours), static_cast<unsigned long long>(all.title),
340 all.title ? 100.0 * double(all.ours) / double(all.title) : 0.0,
341 static_cast<unsigned long long>(all.ours_busy));
342 for (std::size_t i = 0; i < order.size() && i < 12 && order[i].first; ++i) {
343 const ShimCounts& c = shim_counts[order[i].second];
344 std::fprintf(stderr, "[rt] sampler: shims thread %lu: %llu of %llu samples ours (%.0f%%; %llu busy), "
345 "thread busy in %llu; entries: %s; innermost ours: %s; leaves: %s\n",
346 order[i].second, static_cast<unsigned long long>(c.ours),
347 static_cast<unsigned long long>(c.title), 100.0 * double(c.ours) / double(c.title),
348 static_cast<unsigned long long>(c.ours_busy), static_cast<unsigned long long>(c.busy),
349 top_of(c.entries, 5, true).c_str(), top_of(c.inner, 5, false).c_str(),
350 top_of(c.leaves, 3, false).c_str());
351 }
352 std::fprintf(stderr, "[rt] sampler: shims all: entries: %s\n", top_of(all.entries, 16, true).c_str());
353 std::fprintf(stderr, "[rt] sampler: shims all: innermost ours: %s\n", top_of(all.inner, 16, false).c_str());
354 std::fprintf(stderr, "[rt] sampler: shims all: leaves: %s\n", top_of(all.leaves, 12, false).c_str());
355 shim_counts.clear();
356 }
357 chains.clear();
358 total = 0;
359 for (auto& [id, t] : threads) t.used = t.samples = 0;
360 }
361}
362
363// From main, once the title is mapped. Does nothing without LEONIDA_SAMPLE_MS.
364inline void start(std::uint8_t* title, std::uint64_t title_size) {
365 char text[16] = {};
366 const DWORD n = GetEnvironmentVariableA("LEONIDA_SAMPLE_MS", text, sizeof(text));
367 if (!n || n >= sizeof(text)) return;
368 static Sampler s;
369 s.title = title;
370 s.title_size = title_size;
371 s.period_ms = (std::max)(1ul, std::strtoul(text, nullptr, 10));
372 char report[16] = {};
373 if (GetEnvironmentVariableA("LEONIDA_SAMPLE_REPORT_S", report, sizeof(report)) > 0)
374 s.report_ms = (std::max)(1ul, std::strtoul(report, nullptr, 10)) * 1000;
375 char waits[4] = {};
376 s.waits = GetEnvironmentVariableA("LEONIDA_SAMPLE_WAITS", waits, sizeof(waits)) == 1 && waits[0] == '1';
377 char detail[128] = {};
378 if (const DWORD n = GetEnvironmentVariableA("LEONIDA_SAMPLE_DETAIL", detail, sizeof(detail)); n && n < sizeof(detail))
379 for (char* at = detail; *at;) {
380 char* end = nullptr;
381 const unsigned long id = std::strtoul(at, &end, 10);
382 if (end == at) break;
383 if (id) s.detail.push_back(DWORD(id));
384 at = *end == ',' ? end + 1 : end;
385 }
386 char shims[4] = {};
387 s.shims = GetEnvironmentVariableA("LEONIDA_SAMPLE_SHIMS", shims, sizeof(shims)) == 1 && shims[0] == '1';
388 if (const auto self = reinterpret_cast<const std::uint8_t*>(GetModuleHandleW(nullptr))) {
389 const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(self);
390 const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(self + dos->e_lfanew);
391 s.self_base = reinterpret_cast<std::uint64_t>(self);
392 s.self_size = nt->OptionalHeader.SizeOfImage;
393 }
394 if (const HANDLE h = CreateThread(nullptr, 0, &run, &s, 0, nullptr)) {
395 CloseHandle(h);
396 std::fprintf(stderr, "[rt] sampler: every %lu ms, report every %lu s%s%s\n", s.period_ms, s.report_ms / 1000,
397 s.waits ? ", waiting threads too" : "", s.shims ? ", title threads inside our runtime" : "");
398 }
399}
400
401} // namespace leonida::thread_sampler