Files
mandy/runtime/test/call_trace_test.cpp
ubiquitarianism e2572082c0 RT-CALL-TRACE: review fixes (entry stub unwind range, bounded writer lock, caller in helpers)
The entry stub's RUNTIME_FUNCTION now ends before its final jmp [r10], so a stack walk there finds the return
address. The writer lock is taken with a 10 ms bound: a dropped record is counted and the next one writes
`# dropped <count>`. The next view is mapped ahead so a failed remap still ends the file in `# truncated`.
title_free_impl and create_file_w take the caller from the exported shim; a failed VirtualProtect deletes the
function table; pe_loader builds the module name only when tracing. Rules: 205, hash 873cd3bb78a70bc5.

Tested: full runtime build passes; ctest on the 149 non-GPU tests: 100% tests passed, 0 tests failed out of 149; xmem alone: 1/1 passed; xs_proxy_mock|xmem_: 100% tests passed, 0 tests failed out of 13; python -I tests/test_call_trace_rules.py OK. Not run in game.
2026-11-30 19:10:50 -05:00

796 lines
32 KiB
C++

// LEONIDA_CALL_TRACE (shims/call_trace.h): the thunks, the two common stubs, RT_CALLER and the writer, exercised with
// hand-written functions only. No game files, no GPU, no mapped image.
//
// One process-wide trace is opened in main(); each case calls its own sites ("ctt.dll!<name>") and reads the file
// back, filtering by that name. The cases that end the process (TerminateProcess) or need another cap run in a child
// of this executable. Exits 0 when everything passed.
#include <windows.h>
#include <algorithm>
#include <csetjmp>
#include <cstdint>
#include <cstdio>
#include <regex>
#include <string>
#include <vector>
#include "../shims/call_trace.h"
namespace ct = rt::call_trace;
namespace {
int g_failures = 0;
#define CHECK(cond) \
do { \
if (!(cond)) { \
std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
++g_failures; \
} \
} while (0)
// The same rules hash as leonida-hle asserts; tests/test_call_trace_rules.py recomputes it from the rules file and
// fails when the two differ, so a rule change shows up in both stacks.
constexpr const char kExpectedRulesHash[] = "873cd3bb78a70bc5";
std::wstring widen(const std::string& s) { return std::wstring(s.begin(), s.end()); }
std::string slurp(const std::wstring& path) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) return {};
std::string out;
char buf[1 << 16];
DWORD got = 0;
while (ReadFile(h, buf, sizeof buf, &got, nullptr) && got) out.append(buf, got);
CloseHandle(h);
return out;
}
uint64_t file_size(const std::wstring& path) {
WIN32_FILE_ATTRIBUTE_DATA d{};
if (!GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &d)) return 0;
return (static_cast<uint64_t>(d.nFileSizeHigh) << 32) | d.nFileSizeLow;
}
struct Rec {
uint64_t seq = 0;
uint32_t tid = 0;
char kind = 0; // T, C, R, E
std::vector<std::string> f;
};
std::vector<std::string> split(const std::string& s, char sep) {
std::vector<std::string> out;
size_t at = 0;
for (;;) {
const size_t next = s.find(sep, at);
out.push_back(s.substr(at, next == std::string::npos ? std::string::npos : next - at));
if (next == std::string::npos) break;
at = next + 1;
}
return out;
}
struct Parsed {
std::vector<std::string> comments;
std::vector<std::string> bad; // lines that match no format
std::vector<Rec> recs;
std::vector<std::string> lines;
bool partial_tail = false;
};
// The trailing NULs of the last view and a partial last line are dropped, as call_trace_diff.py does.
Parsed parse(const std::wstring& path) {
Parsed p;
std::string text = slurp(path);
while (!text.empty() && text.back() == '\0') text.pop_back();
if (!text.empty() && text.back() != '\n') {
p.partial_tail = true;
const size_t nl = text.rfind('\n');
text.resize(nl == std::string::npos ? 0 : nl + 1);
}
static const std::regex header(R"(# leonida-call-trace 1 stack=gta6rt rules=[0-9a-f]{16})");
static const std::regex bound(R"(# (title-bound [!-~]+|dropped [1-9]\d*))");
static const std::regex where(R"((\?|[!-~]+\+0x[0-9a-f]+))");
static const std::regex t_line(R"(\d+\t\d+\tT\t(main|\?|[a-z0-9_.\-]+\+0x[0-9a-f]+)\t\d+)");
static const std::regex c_line(
R"(\d+\t\d+\t[CE]\t[a-z0-9_.\-]+![!-~]+\t(\?|[a-z0-9_.\-]+\+0x[0-9a-f]+)\t(shim|hle|host|unimpl))");
static const std::regex r_line(R"(\d+\t\d+\tR\t\d+\t(hr:0x[0-9a-f]{8}|u:0x[0-9a-f]{8}|b:[01]|p:(0|1|-1)|-))");
(void)where;
size_t at = 0;
while (at < text.size()) {
const size_t nl = text.find('\n', at);
const std::string line = text.substr(at, nl - at);
at = nl + 1;
p.lines.push_back(line);
if (line[0] == '#') {
p.comments.push_back(line);
if (!std::regex_match(line, header) && !std::regex_match(line, bound) && line != "# truncated")
p.bad.push_back(line);
continue;
}
Rec r;
r.f = split(line, '\t');
const bool ok = r.f.size() >= 4 && ((r.f[2] == "T" && std::regex_match(line, t_line)) ||
((r.f[2] == "C" || r.f[2] == "E") && std::regex_match(line, c_line)) ||
(r.f[2] == "R" && std::regex_match(line, r_line)));
if (!ok) {
p.bad.push_back(line);
continue;
}
r.seq = std::strtoull(r.f[0].c_str(), nullptr, 10);
r.tid = static_cast<uint32_t>(std::strtoul(r.f[1].c_str(), nullptr, 10));
r.kind = r.f[2][0];
p.recs.push_back(std::move(r));
}
return p;
}
// The C and E records of one site, in file order.
std::vector<Rec> calls_of(const Parsed& p, const std::string& site) {
std::vector<Rec> out;
for (const Rec& r : p.recs)
if ((r.kind == 'C' || r.kind == 'E') && r.f[3] == site) out.push_back(r);
return out;
}
const Rec* ret_of(const Parsed& p, const Rec& call) {
for (const Rec& r : p.recs)
if (r.kind == 'R' && r.f[3] == std::to_string(call.seq)) return &r;
return nullptr;
}
std::wstring g_trace; // the process-wide trace
uint64_t g_exe_base = 0;
std::string game_caller(const void* ra) {
char b[48];
std::snprintf(b, sizeof b, "game+0x%llx", static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(ra) - g_exe_base));
return b;
}
template <class F>
F* traced(F* f, const char* sym, ct::Bind bind = ct::Bind::Shim) {
return reinterpret_cast<F*>(ct::wrap(reinterpret_cast<void*>(f), "ctt.dll", sym, bind));
}
template <class F>
bool same_fn(F* a, F* b) {
return reinterpret_cast<void*>(a) == reinterpret_cast<void*>(b);
}
// ---- the targets: plain functions, each its own site ------------------------------------------------------------
uint64_t __stdcall ints20(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e, uint64_t f, uint64_t g, uint64_t h,
uint64_t i, uint64_t j, uint64_t k, uint64_t l, uint64_t m, uint64_t n, uint64_t o, uint64_t p,
uint64_t q, uint64_t r, uint64_t s, uint64_t t) {
return a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 7 * g + 8 * h + 9 * i + 10 * j + 11 * k + 12 * l + 13 * m +
14 * n + 15 * o + 16 * p + 17 * q + 18 * r + 19 * s + 20 * t;
}
double __stdcall floats(double a, float b, double c, double d, double e, float f) {
return a + b * 2.0 + c * 3.0 + d * 4.0 + e * 5.0 + f * 6.0;
}
float __stdcall float_out(float a, float b) { return a * b + 0.25f; }
struct Big {
uint64_t a, b, c;
};
// A console method returning a struct by value: the hidden return pointer is in RCX and `this` in RDX, so `self`
// stands for `this` here and `x` is the first real argument.
Big __stdcall get_desc(void* self, uint64_t x) {
const uint64_t s = reinterpret_cast<uint64_t>(self);
return Big{x, s, x ^ s};
}
DWORD g_error_seen = 0;
uint64_t __stdcall error_probe() {
g_error_seen = GetLastError();
SetLastError(1234);
return 0;
}
using ProbeFn = void(__stdcall*)(void**, void**);
void __stdcall caller_probe(void** raw, void** caller) {
*raw = _ReturnAddress();
*caller = RT_CALLER();
}
// One call instruction for every call through a pointer, so a direct call and a call through a thunk return to the
// same address.
__declspec(noinline) void invoke(ProbeFn f, void** raw, void** caller) {
f(raw, caller);
volatile int keep_the_return_here = 1;
(void)keep_the_return_here;
}
void* __stdcall entry_probe() { return _ReturnAddress(); }
using EntryFn = void*(__stdcall*)();
__declspec(noinline) void* invoke_entry(EntryFn f) {
void* r = f();
volatile int keep_the_return_here = 1;
(void)keep_the_return_here;
return r;
}
std::jmp_buf g_jump;
void __stdcall long_jumper() { std::longjmp(g_jump, 1); }
void __stdcall thrower() { throw 5; }
void __stdcall quiet() {}
using VoidFn = void(__stdcall*)();
VoidFn g_inner = nullptr;
void __stdcall outer() { g_inner(); }
void __stdcall inner() {}
uint64_t __stdcall ret_all_ones() { return ~0ull; }
uint64_t __stdcall ret_low_ones() { return 0xffffffffull; }
uint64_t __stdcall ret_high_ones() { return 0xffffffff00000000ull; }
uint64_t __stdcall ret_zero() { return 0; }
uint64_t __stdcall ret_one() { return 77; }
uint64_t __stdcall ret_hr() { return 0xdeadbeef80004005ull; } // garbage above the HRESULT
uint64_t __stdcall ret_bool_true() { return 0xdeadbeef00000001ull; }
uint64_t __stdcall ret_bool_false() { return 0xdeadbeef12345600ull; }
uint64_t __stdcall ret_void() { return 0x1122334455667788ull; }
uint64_t __stdcall stress(uint64_t x) { return x + 1; }
uint64_t __stdcall kill_me() { TerminateProcess(GetCurrentProcess(), 7); return 0; }
uint64_t __stdcall before_kill(uint64_t x) { return x; }
int g_data = 5;
// ---- cases -------------------------------------------------------------------------------------------------------
void case_rules() {
using namespace ct::detail;
CHECK(decide("kernel32.dll", "malloc").action == kSkip);
CHECK(decide("kernel32.dll", "__chkstk").action == kSkip);
CHECK(decide("api-ms-win-crt-string-l1-1-0.dll", "anything").action == kSkip);
CHECK(decide("kernel32.dll", "_setjmpex").action == kEntry);
CHECK(decide("api-ms-win-crt-stdio-l1-1-0.dll", "__stdio_common_vfprintf").action == kEntry);
CHECK(decide("kernel32.dll", "ExitProcess").action == kEntry);
CHECK(decide("kernel32.dll", "OutputDebugStringA").cls == kClsVoid);
CHECK(decide("xgameruntime.dll", "XUserIsStoreUser").cls == kClsBool);
CHECK(decide("xgameruntime.dll", "XGameRuntimeInitialize").cls == kClsHr);
CHECK(decide("xgameruntime.dll", "XUserAddAsync").cls == kClsHr);
CHECK(decide("xgameruntime.dll", "XUserCompare").cls == kClsP); // CT_NOT_HR beats CT_HR_MOD
CHECK(decide("d3d12.dll", "D3D12CreateDevice").cls == kClsHr);
CHECK(decide("other.dll", "D3D12CreateDevice").cls == kClsP); // CT_HR_MOD is per module
CHECK(decide("kernel32.dll", "CreateFileW").action == kWrap && decide("kernel32.dll", "CreateFileW").cls == kClsP);
CHECK(decide("kernel32.dll", "#12").action == kWrap);
// The ten probes both stacks classify the same way (agreed with the leonida-hle tests).
struct Probe {
const char* module;
const char* fn;
Action action;
Cls cls;
};
const Probe probes[] = {
{"kernel32.dll", "EnterCriticalSection", kSkip, kClsP},
{"api-ms-win-crt-string-l1-1-0.dll", "strcpy", kSkip, kClsP},
{"ucrtbase.dll", "_setjmp", kEntry, kClsP},
{"ucrtbase.dll", "snprintf", kEntry, kClsP},
{"kernel32.dll", "ExitProcess", kEntry, kClsP},
{"kernel32.dll", "WaitForSingleObject", kWrap, kClsVoid},
{"xgameruntime.dll", "XTaskQueueDispatch", kWrap, kClsBool},
{"xgameruntime.dll", "XUserAddAsync", kWrap, kClsHr},
{"d3d12.dll", "D3D12CreateDevice", kWrap, kClsHr},
{"xgameruntime.dll", "XUserCompare", kWrap, kClsP},
};
for (const Probe& pr : probes) {
const Decision d = decide(pr.module, pr.fn);
CHECK(d.action == pr.action && (pr.action != kWrap || d.cls == pr.cls));
}
// Stack walks cannot have a wrap frame in front of them; SVML passes YMM arguments the stubs do not carry.
CHECK(decide("kernel32.dll", "RtlCaptureStackBackTrace").action == kEntry);
CHECK(decide("kernel32.dll", "RtlCaptureContext2").action == kEntry);
CHECK(decide("vcruntime140.dll", "__vdecl_sin2").action == kSkip);
CHECK(sizeof kRules / sizeof kRules[0] == 205);
char hash[24];
std::snprintf(hash, sizeof hash, "%016llx", static_cast<unsigned long long>(rules_hash()));
CHECK(std::string(kExpectedRulesHash) == hash);
}
void case_off() {
// Before open_from_env: the target comes back unchanged and RT_CALLER() is _ReturnAddress().
CHECK(!ct::enabled());
CHECK(ct::wrap(reinterpret_cast<void*>(&ints20), "ctt.dll", "ints20", ct::Bind::Shim) ==
reinterpret_cast<void*>(&ints20));
CHECK(ct::g_wrap_ret == nullptr);
void *raw = nullptr, *caller = nullptr;
invoke(&caller_probe, &raw, &caller);
CHECK(raw && raw == caller);
CHECK(ct::open_from_env() == ct::OpenResult::Off); // unset
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", L"");
CHECK(ct::open_from_env() == ct::OpenResult::Off); // empty
CHECK(!ct::enabled());
}
void case_refusals() {
// An existing file is refused and left as it was.
const std::wstring existing = g_trace + L".exists";
HANDLE h = CreateFileW(existing.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
DWORD wrote = 0;
WriteFile(h, "keep", 4, &wrote, nullptr);
CloseHandle(h);
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", existing.c_str());
CHECK(ct::open_from_env() == ct::OpenResult::Failed);
CHECK(slurp(existing) == "keep");
CHECK(!ct::enabled());
CHECK(ct::wrap(reinterpret_cast<void*>(&ints20), "ctt.dll", "ints20", ct::Bind::Shim) ==
reinterpret_cast<void*>(&ints20));
DeleteFileW(existing.c_str());
// A cap that is not a whole number of MiB refuses before the file is created.
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", g_trace.c_str());
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", L"12x");
CHECK(ct::open_from_env() == ct::OpenResult::Failed);
CHECK(GetFileAttributesW(g_trace.c_str()) == INVALID_FILE_ATTRIBUTES);
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", nullptr);
// An unwritable place is refused too.
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", (g_trace + L"_no_dir\\x.txt").c_str());
CHECK(ct::open_from_env() == ct::OpenResult::Failed);
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", g_trace.c_str());
}
void case_header_and_modules() {
const Parsed p = parse(g_trace);
CHECK(!p.comments.empty());
if (!p.comments.empty()) {
CHECK(p.comments[0].rfind("# leonida-call-trace 1 stack=gta6rt rules=", 0) == 0);
CHECK(p.comments[0].substr(p.comments[0].size() - 16) == kExpectedRulesHash);
}
int bound = 0;
for (const std::string& c : p.comments) bound += c == "# title-bound foo.dll";
CHECK(bound == 1); // named once, lower-cased
CHECK(ct::detail::g_stub && ct::g_wrap_ret == ct::detail::g_stub + 0x159);
// `jmp [r10]` (41 FF 22 at 0x7F) is not an epilogue the unwinder knows: the entry stub's function ends before it,
// so a stack walk there treats it as a leaf and finds the return address at [rsp].
if (ct::detail::g_stub) {
DWORD64 base = 0;
PRUNTIME_FUNCTION f = RtlLookupFunctionEntry(reinterpret_cast<DWORD64>(ct::detail::g_stub + 0x7E), &base, nullptr);
CHECK(f != nullptr && f->BeginAddress == 0 && f->EndAddress == 0x7F);
CHECK(RtlLookupFunctionEntry(reinterpret_cast<DWORD64>(ct::detail::g_stub + 0x7F), &base, nullptr) == nullptr);
CHECK(RtlLookupFunctionEntry(reinterpret_cast<DWORD64>(ct::detail::g_stub + 0x81), &base, nullptr) == nullptr);
CHECK(ct::detail::g_stub[0x7F] == 0x41 && ct::detail::g_stub[0x80] == 0xFF && ct::detail::g_stub[0x81] == 0x22);
PRUNTIME_FUNCTION w = RtlLookupFunctionEntry(reinterpret_cast<DWORD64>(ct::g_wrap_ret), &base, nullptr);
CHECK(w != nullptr && w->BeginAddress == 0x90 && w->EndAddress == 0x19A);
}
}
void case_ints() {
auto f = traced(&ints20, "ints20");
CHECK(!same_fn(f, &ints20));
const uint64_t want = ints20(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
const uint64_t got = f(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
CHECK(got == want);
const Parsed p = parse(g_trace);
const auto calls = calls_of(p, "ctt.dll!ints20");
CHECK(calls.size() == 1 && calls[0].kind == 'C' && calls[0].f[5] == "shim");
if (!calls.empty()) {
const Rec* r = ret_of(p, calls[0]);
CHECK(r && r->f[4] == "p:1" && r->seq > calls[0].seq);
CHECK(calls[0].f[4].rfind("game+0x", 0) == 0);
}
}
void case_floats() {
auto f = traced(&floats, "floats");
CHECK(f(1.5, 2.5f, 3.5, 4.5, 5.5, 6.5f) == floats(1.5, 2.5f, 3.5, 4.5, 5.5, 6.5f));
auto g = traced(&float_out, "float_out");
CHECK(g(3.0f, 4.0f) == float_out(3.0f, 4.0f));
}
void case_struct_return() {
auto f = traced(&get_desc, "get_desc");
int self = 0;
const Big got = f(&self, 0x1234);
const Big want = get_desc(&self, 0x1234);
CHECK(got.a == want.a && got.b == want.b && got.c == want.c);
CHECK(got.a == 0x1234);
}
void case_last_error() {
for (const char* sym : {"error_wrap", "exit"}) { // `exit` is an entry-only rule
auto f = traced(&error_probe, sym);
SetLastError(55);
g_error_seen = 0;
f();
CHECK(GetLastError() == 1234); // the target's value survives the trace
CHECK(g_error_seen == 55); // and the target saw the caller's
}
}
void case_caller() {
void *raw0 = nullptr, *caller0 = nullptr, *raw1 = nullptr, *caller1 = nullptr;
invoke(&caller_probe, &raw0, &caller0);
auto f = traced(&caller_probe, "caller_probe");
invoke(f, &raw1, &caller1);
CHECK(raw0 == caller0);
CHECK(raw1 == ct::g_wrap_ret); // the shim is called by the wrap stub
CHECK(caller1 == raw0); // RT_CALLER() sees through it
const Parsed p = parse(g_trace);
const auto calls = calls_of(p, "ctt.dll!caller_probe");
CHECK(calls.size() == 1 && calls[0].f[4] == game_caller(raw0));
}
void case_entry_only() {
void* direct = invoke_entry(&entry_probe);
auto f = traced(&entry_probe, "terminate"); // CT_ENTRY
void* through = invoke_entry(f);
CHECK(direct == through); // no frame between the title and the target
auto g = traced(&entry_probe, "unimpl_probe", ct::Bind::Unimpl);
CHECK(invoke_entry(g) == direct);
const Parsed p = parse(g_trace);
const auto e = calls_of(p, "ctt.dll!terminate");
CHECK(e.size() == 1 && e[0].kind == 'E' && e[0].f[5] == "shim" && e[0].f[4] == game_caller(direct));
CHECK(e.empty() || ret_of(p, e[0]) == nullptr);
const auto u = calls_of(p, "ctt.dll!unimpl_probe");
CHECK(u.size() == 1 && u[0].kind == 'E' && u[0].f[5] == "unimpl");
}
// Kept apart from anything with a destructor or a handler: setjmp and C++ unwinding do not mix in one frame.
#pragma warning(push)
#pragma warning(disable : 4611) // setjmp under /EHsc: nothing here has a destructor
__declspec(noinline) int jump_past(VoidFn f) {
volatile int jumped = 0;
if (setjmp(g_jump) == 0) {
f();
jumped = 2;
} else {
jumped = 1;
}
return jumped;
}
#pragma warning(pop)
__declspec(noinline) int throw_through(VoidFn f) {
try {
f();
} catch (int v) {
return v;
}
return 0;
}
void case_jump_and_throw() {
auto ok = traced(&quiet, "after_jump");
CHECK(jump_past(traced(&long_jumper, "long_jumper")) == 1);
ok();
CHECK(throw_through(traced(&thrower, "thrower")) == 5);
ok();
const Parsed p = parse(g_trace);
for (const char* name : {"ctt.dll!long_jumper", "ctt.dll!thrower"}) {
const auto c = calls_of(p, name);
CHECK(c.size() == 1 && c[0].kind == 'C' && ret_of(p, c[0]) == nullptr); // a C without an R
}
const auto a = calls_of(p, "ctt.dll!after_jump");
CHECK(a.size() == 2);
for (const Rec& c : a) CHECK(ret_of(p, c) != nullptr);
}
void case_nested() {
g_inner = traced(&inner, "nested_inner");
auto o = traced(&outer, "nested_outer");
o();
const Parsed p = parse(g_trace);
const auto co = calls_of(p, "ctt.dll!nested_outer");
const auto ci = calls_of(p, "ctt.dll!nested_inner");
CHECK(co.size() == 1 && ci.size() == 1);
if (co.size() != 1 || ci.size() != 1) return;
const Rec* ro = ret_of(p, co[0]);
const Rec* ri = ret_of(p, ci[0]);
CHECK(ro && ri);
if (!ro || !ri) return;
CHECK(co[0].seq < ci[0].seq && ci[0].seq < ri->seq && ri->seq < ro->seq); // C C R R
CHECK(ri->f[3] == std::to_string(ci[0].seq) && ro->f[3] == std::to_string(co[0].seq));
}
void case_unchanged_returns() {
void* f = reinterpret_cast<void*>(&quiet);
CHECK(ct::wrap(f, "ctt.dll", "malloc", ct::Bind::Host) == f); // CT_SKIP
CHECK(ct::wrap(f, "ctt.dll", "my_chkstk_thing", ct::Bind::Host) == f); // CT_SKIP_HAS
CHECK(ct::wrap(f, "API-MS-WIN-CRT-STRING-L1-1-0.dll", "whatever", ct::Bind::Host) == f); // CT_SKIP_MODULE
CHECK(ct::wrap(&g_data, "ctt.dll", "data_import", ct::Bind::Host) == static_cast<void*>(&g_data)); // data
CHECK(ct::wrap(nullptr, "ctt.dll", "null_import", ct::Bind::Host) == nullptr);
const Parsed p = parse(g_trace);
CHECK(calls_of(p, "ctt.dll!malloc").empty() && calls_of(p, "ctt.dll!data_import").empty());
}
void case_classes() {
struct Row {
uint64_t (__stdcall* fn)();
const char* sym;
const char* want;
};
const Row rows[] = {
{&ret_all_ones, "cls_all_ones", "p:-1"}, {&ret_low_ones, "cls_low_ones", "p:-1"},
{&ret_high_ones, "cls_high_ones", "p:1"}, {&ret_zero, "cls_zero", "p:0"},
{&ret_one, "cls_one", "p:1"}, {&ret_hr, "XGameRuntimeInitialize", "hr:0x80004005"},
{&ret_bool_true, "XUserIsStoreUser", "b:1"}, {&ret_bool_false, "XStoreIsLicenseValid", "b:0"},
{&ret_void, "OutputDebugStringA", "-"},
};
for (const Row& row : rows) traced(row.fn, row.sym)();
const Parsed p = parse(g_trace);
for (const Row& row : rows) {
const auto c = calls_of(p, std::string("ctt.dll!") + row.sym);
CHECK(c.size() == 1);
if (c.size() != 1) continue;
const Rec* r = ret_of(p, c[0]);
CHECK(r && r->f[4] == row.want);
if (r && r->f[4] != row.want) std::printf(" %s: %s, wanted %s\n", row.sym, r->f[4].c_str(), row.want);
}
}
HANDLE g_start = nullptr; // workers wait for it, so they are all running before any records
HANDLE g_release = nullptr; // and for this one after they have recorded, so no thread id is reused
volatile LONG g_recorded = 0;
DWORD WINAPI worker(void* p) {
auto f = reinterpret_cast<uint64_t(__stdcall*)(uint64_t)>(p);
WaitForSingleObject(g_start, INFINITE);
uint64_t sum = 0;
for (uint64_t i = 0; i < 20000; ++i) sum += f(i);
InterlockedIncrement(&g_recorded);
WaitForSingleObject(g_release, INFINITE);
return sum == 20000ull * 20001 / 2 ? 0 : 1;
}
uint64_t __stdcall bulk_target(uint64_t x) { return x * 3; }
// 400 distinct sites need more than one 64 KiB pool of Sites (341 each).
void case_many_sites() {
constexpr int kSites = 400;
std::vector<uint64_t(__stdcall*)(uint64_t)> fns;
for (int i = 0; i < kSites; ++i) fns.push_back(traced(&bulk_target, ("bulk" + std::to_string(i)).c_str()));
for (int i = 0; i < kSites; ++i) CHECK(fns[static_cast<size_t>(i)](static_cast<uint64_t>(i)) == 3ull * static_cast<uint64_t>(i));
const Parsed p = parse(g_trace);
CHECK(p.bad.empty());
int found = 0;
for (const Rec& r : p.recs)
if (r.kind == 'C' && r.f[3].rfind("ctt.dll!bulk", 0) == 0) ++found;
CHECK(found == kSites);
for (int i : {0, 340, 341, 399}) {
const auto c = calls_of(p, "ctt.dll!bulk" + std::to_string(i));
CHECK(c.size() == 1 && ret_of(p, c[0]) != nullptr);
}
}
// The writer lock is taken with a bound: a record that cannot get it is dropped after about 10 ms, and the next one
// that does says so.
struct LockHolder {
HANDLE locked;
HANDLE release;
};
DWORD WINAPI hold_writer_lock(void* p) {
auto* h = static_cast<LockHolder*>(p);
AcquireSRWLockExclusive(&ct::detail::g_lock);
SetEvent(h->locked);
WaitForSingleObject(h->release, INFINITE);
ReleaseSRWLockExclusive(&ct::detail::g_lock);
return 0;
}
void case_dropped_record() {
LockHolder h{CreateEventW(nullptr, TRUE, FALSE, nullptr), CreateEventW(nullptr, TRUE, FALSE, nullptr)};
HANDLE t = CreateThread(nullptr, 0, hold_writer_lock, &h, 0, nullptr);
WaitForSingleObject(h.locked, INFINITE);
auto f = traced(&stress, "dropped_probe");
LARGE_INTEGER freq, a, b;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&a);
const uint64_t got = f(41);
QueryPerformanceCounter(&b);
CHECK(got == 42); // the call itself went through
const double ms = 1000.0 * static_cast<double>(b.QuadPart - a.QuadPart) / static_cast<double>(freq.QuadPart);
CHECK(ms < 100.0);
if (ms >= 100.0) std::printf(" the dropped call took %.1f ms\n", ms);
SetEvent(h.release);
WaitForSingleObject(t, INFINITE);
CloseHandle(t);
CloseHandle(h.locked);
CloseHandle(h.release);
CHECK(ct::detail::g_dropped.load() == 1);
CHECK(f(1) == 2);
const Parsed p = parse(g_trace);
CHECK(p.bad.empty());
int dropped_line = -1, call_line = -1, calls = 0;
for (size_t i = 0; i < p.lines.size(); ++i) {
if (p.lines[i] == "# dropped 1") dropped_line = static_cast<int>(i);
if (p.lines[i].find("ctt.dll!dropped_probe") != std::string::npos) {
call_line = static_cast<int>(i);
++calls;
}
}
CHECK(calls == 1); // the first call left no C and no R
CHECK(dropped_line >= 0 && call_line > dropped_line);
const auto c = calls_of(p, "ctt.dll!dropped_probe");
CHECK(c.size() == 1 && ret_of(p, c[0]) != nullptr);
}
void case_threads() {
constexpr int kThreads = 4;
auto f = traced(&stress, "stress");
HANDLE h[kThreads];
g_start = CreateEventW(nullptr, TRUE, FALSE, nullptr);
g_release = CreateEventW(nullptr, TRUE, FALSE, nullptr);
g_recorded = 0;
for (HANDLE& t : h) t = CreateThread(nullptr, 0, worker, reinterpret_cast<void*>(f), 0, nullptr);
SetEvent(g_start);
for (int waited = 0; g_recorded < kThreads && waited < 120000; waited += 5) Sleep(5);
CHECK(g_recorded == kThreads);
SetEvent(g_release);
for (HANDLE t : h) {
WaitForSingleObject(t, INFINITE);
DWORD code = 99;
GetExitCodeThread(t, &code);
CHECK(code == 0);
CloseHandle(t);
}
CloseHandle(g_start);
CloseHandle(g_release);
CHECK(file_size(g_trace) >= 2 * ct::detail::kViewBytes); // the lines crossed a view boundary
const Parsed p = parse(g_trace);
CHECK(p.bad.empty());
if (!p.bad.empty()) std::printf(" first bad line: %s\n", p.bad[0].c_str());
uint64_t last = 0;
bool increasing = true;
for (const Rec& r : p.recs) {
if (r.seq <= last) increasing = false;
last = r.seq;
}
CHECK(increasing);
const auto c = calls_of(p, "ctt.dll!stress");
CHECK(c.size() == static_cast<size_t>(kThreads) * 20000);
std::vector<uint32_t> tids;
for (const Rec& r : c)
if (std::find(tids.begin(), tids.end(), r.tid) == tids.end()) tids.push_back(r.tid);
CHECK(tids.size() == kThreads);
for (uint32_t tid : tids) {
int t_lines = 0;
for (const Rec& r : p.recs) t_lines += r.kind == 'T' && r.tid == tid;
CHECK(t_lines == 1);
}
size_t returns = 0;
for (const Rec& r : p.recs) returns += r.kind == 'R';
CHECK(returns >= c.size());
}
void case_main_thread() {
const Parsed p = parse(g_trace);
const DWORD tid = GetCurrentThreadId();
int t_lines = 0;
for (const Rec& r : p.recs)
if (r.kind == 'T' && r.tid == tid) {
++t_lines;
CHECK(r.f[3] == "main");
}
CHECK(t_lines == 1);
}
// ---- children ----------------------------------------------------------------------------------------------------
DWORD run_child(const std::wstring& mode, const std::wstring& path, bool* started) {
wchar_t exe[MAX_PATH];
GetModuleFileNameW(nullptr, exe, MAX_PATH);
std::wstring cmd = L"\"" + std::wstring(exe) + L"\" " + mode + L" \"" + path + L"\"";
STARTUPINFOW si{};
si.cb = sizeof si;
PROCESS_INFORMATION pi{};
*started = CreateProcessW(exe, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi) != 0;
if (!*started) return 99;
WaitForSingleObject(pi.hProcess, 120000);
DWORD code = 98;
GetExitCodeProcess(pi.hProcess, &code);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return code;
}
void case_killed_child() {
const std::wstring path = g_trace + L".kill";
DeleteFileW(path.c_str());
bool started = false;
const DWORD code = run_child(L"--child-kill", path, &started);
CHECK(started && code == 7);
const Parsed p = parse(path);
CHECK(p.bad.empty());
const auto before = calls_of(p, "ctt.dll!before_kill");
CHECK(before.size() == 3);
for (const Rec& c : before) CHECK(ret_of(p, c) != nullptr);
const auto kill = calls_of(p, "ctt.dll!kill_me");
CHECK(kill.size() == 1 && ret_of(p, kill[0]) == nullptr);
CHECK(!p.recs.empty() && p.recs.back().kind == 'C' && p.recs.back().f[3] == "ctt.dll!kill_me"); // the open C is last
DeleteFileW(path.c_str());
}
void case_capped_child() {
const std::wstring path = g_trace + L".cap";
DeleteFileW(path.c_str());
bool started = false;
const DWORD code = run_child(L"--child-cap", path, &started);
CHECK(started && code == 0);
const Parsed p = parse(path);
CHECK(p.bad.empty());
CHECK(!p.lines.empty() && p.lines.back() == "# truncated");
size_t truncated = 0;
for (const std::string& l : p.lines) truncated += l == "# truncated";
CHECK(truncated == 1);
size_t bytes = 0;
for (const std::string& l : p.lines) bytes += l.size() + 1;
CHECK(bytes <= (size_t{1} << 20));
DeleteFileW(path.c_str());
}
int child_main(const std::wstring& mode, const std::wstring& path) {
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", path.c_str());
const bool cap = mode == L"--child-cap";
if (cap) SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", L"1");
if (ct::open_from_env() != ct::OpenResult::On) return 3;
if (cap) { // far more than 1 MiB of lines: the file ends in `# truncated` and the calls keep working
auto f = traced(&stress, "stress");
for (uint64_t i = 0; i < 40000; ++i)
if (f(i) != i + 1) return 4;
if (ct::enabled()) return 5; // the cap was reached
void* late = ct::wrap(reinterpret_cast<void*>(&stress), "ctt.dll", "after_cap", ct::Bind::Shim);
if (late != reinterpret_cast<void*>(&stress)) return 6; // no new thunk once recording has stopped
if (f(5) != 6) return 7; // an old one still forwards
return 0;
}
auto b = traced(&before_kill, "before_kill");
for (uint64_t i = 0; i < 3; ++i) b(i);
traced(&kill_me, "kill_me")();
return 5; // not reached
}
} // namespace
int wmain(int argc, wchar_t** argv) {
if (argc == 3 && (std::wstring(argv[1]) == L"--child-kill" || std::wstring(argv[1]) == L"--child-cap"))
return child_main(argv[1], argv[2]);
wchar_t temp[MAX_PATH];
GetTempPathW(MAX_PATH, temp);
g_trace = std::wstring(temp) + L"leonida_call_trace_test_" + std::to_wstring(GetCurrentProcessId()) + L".txt";
DeleteFileW(g_trace.c_str());
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE", nullptr);
SetEnvironmentVariableW(L"LEONIDA_CALL_TRACE_MAX_MB", nullptr);
auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(GetModuleHandleW(nullptr));
auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(reinterpret_cast<const uint8_t*>(dos) + dos->e_lfanew);
g_exe_base = reinterpret_cast<uintptr_t>(dos);
case_rules();
case_off();
case_refusals();
CHECK(ct::open_from_env() == ct::OpenResult::On);
if (!ct::enabled()) {
std::printf("FAIL: the trace did not open; stopping\n");
return 1;
}
ct::add_module("CTT.EXE", dos, nt->OptionalHeader.SizeOfImage);
ct::set_main_module(dos);
ct::note_title_bound("Foo.DLL");
ct::note_title_bound("foo.dll");
ct::mark_main_thread();
case_header_and_modules();
case_ints();
case_floats();
case_struct_return();
case_last_error();
case_caller();
case_entry_only();
case_jump_and_throw();
case_nested();
case_unchanged_returns();
case_classes();
case_many_sites();
case_dropped_record();
case_threads();
case_main_thread();
case_killed_child();
case_capped_child();
if (g_failures == 0) DeleteFileW(g_trace.c_str());
else std::printf("trace kept at %ls\n", g_trace.c_str());
std::printf(g_failures ? "call_trace_test: %d failure(s)\n" : "call_trace_test: ok\n", g_failures);
return g_failures ? 1 : 0;
}