1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
|
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "yuzu_cmd/nx2_sampler.h"
#ifdef _WIN32
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <set>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <windows.h>
#include <tlhelp32.h>
#include <dbghelp.h>
namespace Nx2Sampler {
namespace {
constexpr size_t MaxDepth = 40;
struct Sample {
unsigned thread;
unsigned depth;
std::array<DWORD64, MaxDepth> frames;
};
struct Target {
HANDLE handle;
std::string name;
};
double EnvSeconds(const char* name, double fallback) {
const char* text = std::getenv(name);
return text != nullptr ? std::strtod(text, nullptr) : fallback;
}
std::vector<std::string> SplitNames(const char* text) {
std::vector<std::string> names;
std::string current;
for (const char* c = text; *c != '\0'; ++c) {
if (*c == ',') {
names.push_back(current);
current.clear();
} else {
current += *c;
}
}
if (!current.empty()) {
names.push_back(current);
}
return names;
}
bool Matches(const std::string& thread_name, const std::vector<std::string>& patterns) {
for (const auto& pattern : patterns) {
if (!pattern.empty() && pattern.back() == '*') {
if (thread_name.compare(0, pattern.size() - 1, pattern, 0, pattern.size() - 1) == 0) {
return true;
}
} else if (thread_name == pattern) {
return true;
}
}
return false;
}
std::vector<Target> FindThreads(const std::vector<std::string>& patterns) {
using GetThreadDescriptionFn = HRESULT(WINAPI*)(HANDLE, PWSTR*);
const auto get_description = reinterpret_cast<GetThreadDescriptionFn>(
GetProcAddress(GetModuleHandleA("KernelBase.dll"), "GetThreadDescription"));
std::vector<Target> targets;
if (get_description == nullptr) {
return targets;
}
const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
return targets;
}
THREADENTRY32 entry{};
entry.dwSize = sizeof(entry);
const DWORD self = GetCurrentThreadId();
for (BOOL ok = Thread32First(snapshot, &entry); ok; ok = Thread32Next(snapshot, &entry)) {
if (entry.th32OwnerProcessID != GetCurrentProcessId() || entry.th32ThreadID == self) {
continue;
}
const HANDLE handle = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT |
THREAD_QUERY_LIMITED_INFORMATION,
FALSE, entry.th32ThreadID);
if (handle == nullptr) {
continue;
}
PWSTR wide{};
std::string name;
if (SUCCEEDED(get_description(handle, &wide)) && wide != nullptr) {
char buffer[256]{};
WideCharToMultiByte(CP_UTF8, 0, wide, -1, buffer, sizeof(buffer) - 1, nullptr,
nullptr);
name = buffer;
LocalFree(wide);
}
if (Matches(name, patterns)) {
targets.push_back({handle, name});
} else {
CloseHandle(handle);
}
}
CloseHandle(snapshot);
return targets;
}
// Walks a suspended thread's stack from its context. Nothing here may allocate: the thread
// could be paused holding the heap lock.
unsigned Walk(CONTEXT context, std::array<DWORD64, MaxDepth>& frames) {
unsigned depth = 0;
while (depth < MaxDepth && context.Rip != 0) {
frames[depth++] = context.Rip;
DWORD64 image_base{};
const PRUNTIME_FUNCTION function = RtlLookupFunctionEntry(context.Rip, &image_base, nullptr);
if (function == nullptr) {
// A leaf function (no unwind data): its return address is on top of the stack. JIT
// code has none either; past the first frame, stop there.
if (depth != 1) {
break;
}
context.Rip = *reinterpret_cast<const DWORD64*>(context.Rsp);
context.Rsp += 8;
continue;
}
PVOID handler_data{};
DWORD64 establisher_frame{};
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, context.Rip, function, &context,
&handler_data, &establisher_frame, nullptr);
}
return depth;
}
struct Symbolizer {
using SymInitializeFn = BOOL(WINAPI*)(HANDLE, PCSTR, BOOL);
using SymSetOptionsFn = DWORD(WINAPI*)(DWORD);
using SymFromAddrFn = BOOL(WINAPI*)(HANDLE, DWORD64, PDWORD64, PSYMBOL_INFO);
Symbolizer() {
const HMODULE dbghelp = LoadLibraryA("dbghelp.dll");
if (dbghelp == nullptr) {
return;
}
const auto set_options =
reinterpret_cast<SymSetOptionsFn>(GetProcAddress(dbghelp, "SymSetOptions"));
const auto initialize =
reinterpret_cast<SymInitializeFn>(GetProcAddress(dbghelp, "SymInitialize"));
from_address = reinterpret_cast<SymFromAddrFn>(GetProcAddress(dbghelp, "SymFromAddr"));
if (set_options == nullptr || initialize == nullptr || from_address == nullptr) {
from_address = nullptr;
return;
}
set_options(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
if (!initialize(GetCurrentProcess(), nullptr, TRUE)) {
from_address = nullptr;
}
}
const std::string& Name(DWORD64 address) {
const auto [it, is_new] = cache.try_emplace(address);
if (!is_new) {
return it->second;
}
if (from_address != nullptr) {
alignas(SYMBOL_INFO) char buffer[sizeof(SYMBOL_INFO) + 1024]{};
auto* const symbol = reinterpret_cast<SYMBOL_INFO*>(buffer);
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = 1024;
DWORD64 displacement{};
if (from_address(GetCurrentProcess(), address, &displacement, symbol)) {
it->second.assign(symbol->Name, std::min<size_t>(symbol->NameLen, 160));
return it->second;
}
}
HMODULE module{};
if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCSTR>(address), &module)) {
char path[MAX_PATH] = "?";
GetModuleFileNameA(module, path, sizeof(path));
const char* base = std::strrchr(path, '\\');
it->second = std::string{base != nullptr ? base + 1 : path} + "!?";
} else {
it->second = "(jit)";
}
return it->second;
}
SymFromAddrFn from_address{};
std::unordered_map<DWORD64, std::string> cache;
};
void Report(const std::vector<Target>& targets, const std::vector<Sample>& samples,
const char* path) {
Symbolizer symbolizer;
std::FILE* const file = std::fopen(path, "w");
if (file == nullptr) {
return;
}
for (unsigned thread = 0; thread < targets.size(); ++thread) {
std::map<std::string, unsigned> self;
std::map<std::string, unsigned> inclusive;
std::map<std::string, unsigned> self_caller;
unsigned total = 0;
for (const Sample& sample : samples) {
if (sample.thread != thread || sample.depth == 0) {
continue;
}
++total;
const std::string& top = symbolizer.Name(sample.frames[0]);
++self[top];
if (sample.depth > 1) {
++self_caller[top + " <- " + symbolizer.Name(sample.frames[1])];
}
std::set<std::string> seen;
for (unsigned i = 0; i < sample.depth; ++i) {
const std::string& name = symbolizer.Name(sample.frames[i]);
if (seen.insert(name).second) {
++inclusive[name];
}
}
}
const auto print = [&](const char* title, const std::map<std::string, unsigned>& counts,
size_t limit) {
std::vector<std::pair<unsigned, std::string>> sorted;
for (const auto& [name, count] : counts) {
sorted.emplace_back(count, name);
}
std::sort(sorted.rbegin(), sorted.rend());
std::fprintf(file, "-- %s\n", title);
for (size_t i = 0; i < (std::min)(limit, sorted.size()); ++i) {
std::fprintf(file, "%6u %5.1f%% %s\n", sorted[i].first,
100.0 * sorted[i].first / (std::max)(total, 1U),
sorted[i].second.c_str());
}
};
std::fprintf(file, "=== thread \"%s\": %u samples\n", targets[thread].name.c_str(), total);
print("self (where the thread is)", self, 60);
print("self <- caller", self_caller, 50);
print("inclusive (on the stack)", inclusive, 90);
std::fprintf(file, "\n");
}
std::fclose(file);
// <out>.folded: every distinct stack with its count, root first ("thread;a;b;c count").
std::map<std::string, unsigned> folded;
for (const Sample& sample : samples) {
std::string line = targets[sample.thread].name;
for (unsigned i = sample.depth; i-- > 0;) {
line += ';';
line += symbolizer.Name(sample.frames[i]);
}
++folded[line];
}
if (std::FILE* const out = std::fopen((std::string{path} + ".folded").c_str(), "w")) {
for (const auto& [line, count] : folded) {
std::fprintf(out, "%s %u\n", line.c_str(), count);
}
std::fclose(out);
}
}
void Run(std::vector<std::string> patterns, double start, double seconds, std::string out) {
std::this_thread::sleep_for(std::chrono::duration<double>(start));
const std::vector<Target> targets = FindThreads(patterns);
std::fprintf(stderr, "nx2 sampler: %zu threads match, sampling %.0f s\n", targets.size(),
seconds);
if (targets.empty()) {
return;
}
std::vector<Sample> samples;
samples.reserve(static_cast<size_t>(seconds * 1100.0) * targets.size() + 16);
const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration<double>(seconds);
while (std::chrono::steady_clock::now() < deadline &&
samples.size() + targets.size() <= samples.capacity()) {
for (unsigned i = 0; i < targets.size(); ++i) {
const HANDLE handle = targets[i].handle;
if (SuspendThread(handle) == static_cast<DWORD>(-1)) {
continue;
}
CONTEXT context{};
context.ContextFlags = CONTEXT_FULL;
if (GetThreadContext(handle, &context)) {
Sample& sample = samples.emplace_back();
sample.thread = i;
sample.depth = Walk(context, sample.frames);
}
ResumeThread(handle);
}
Sleep(1);
}
Report(targets, samples, out.c_str());
std::fprintf(stderr, "nx2 sampler: %zu samples written to %s\n", samples.size(), out.c_str());
for (const auto& target : targets) {
CloseHandle(target.handle);
}
}
} // Anonymous namespace
void StartFromEnvironment() {
const char* names = std::getenv("EDEN_NX2_SAMPLE");
if (names == nullptr || *names == '\0') {
return;
}
const char* out = std::getenv("EDEN_NX2_SAMPLE_OUT");
std::thread{Run, SplitNames(names), EnvSeconds("EDEN_NX2_SAMPLE_START", 60.0),
EnvSeconds("EDEN_NX2_SAMPLE_SECONDS", 30.0),
std::string{out != nullptr ? out : "nx2_samples.txt"}}
.detach();
}
} // namespace Nx2Sampler
#else
namespace Nx2Sampler {
void StartFromEnvironment() {}
} // namespace Nx2Sampler
#endif
|