Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/boot.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,13 @@ Useful switches:
diagnostic).
* `LEONIDA_DEVICE_FAULT=1` enables Vulkan device-loss diagnostics and checkpoints where available. The first
observed loss prints a `[rt] device-fault:` report to stderr.
* `LEONIDA_IO_TRACE=<file>` writes one line for every read the title asks for (`runtime/shims/io_trace.h`):
- `ds`: a DirectStorage request, with its file, file offset, source and destination sizes, zlib and BCPack, and the
request's name;
- `rf`: a ReadFile, ReadFileEx or ReadFileScatter on a disk file, with its path, offset and size.

Each line starts with the local time, as the `mem-probe` lines do. Each line is flushed at once and the file can be
read while the game runs, so the last reads before a crash or a device loss name what the title was loading.
* `LEONIDA_TITLE_HUD=1` shows live counters in the title bar of the window the title presents in
(`runtime/shims/title_hud.h`). It updates twice a second with:
- the frame rate and the average and worst frame time from PresentX, or, when no frame came in that half
Expand Down
7 changes: 7 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,13 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
target_link_options(lifecycle_test PRIVATE /OPT:NOREF)
target_link_libraries(lifecycle_test PRIVATE user32)

# LEONIDA_IO_TRACE (shims/io_trace.h): read lines written through and readable while the trace is open.
add_executable(io_trace_test test/io_trace_test.cpp)
target_include_directories(io_trace_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
target_compile_definitions(io_trace_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(io_trace_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME io_trace COMMAND io_trace_test)

# Console paths (GAME:) and the write overlay: the file shims resolved through the registry, over temporary folders.
add_executable(file_system_test
test/file_system_test.cpp
Expand Down
15 changes: 15 additions & 0 deletions runtime/shims/dstorage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
#include "../src/bcpack.h"
#include "../src/guarded_copy.h"
#include "../src/shader_directory.h"
#include "io_trace.h" // LEONIDA_IO_TRACE
#include "../src/dstorage_swizzle.h"
#include "../src/dstorage_trace.h"
#include "../src/dstorage_hold.h"
Expand Down Expand Up @@ -686,6 +687,20 @@ class Queue final : public IDStorageQueueX2 {
if (!e.file) e.enqueue_error = E_DSTORAGE_INVALID_FILE_HANDLE;
}
e.counted = true; // TotalRequestCount is "submitted requests" (DSTORAGE_PRIORITY_STATS): see submit_locked
if (rt::io_trace::enabled()) {
const bool from_file = options::source_type(o) == DSTORAGE_REQUEST_SOURCE_FILE;
std::string path = "<memory>";
if (from_file && e.file) {
const std::wstring& w = e.file->path();
const int len = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), int(w.size()), nullptr, 0, nullptr, nullptr);
path.assign(size_t(len), ' ');
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), int(w.size()), path.data(), len, nullptr, nullptr);
}
rt::io_trace::line("ds %s off=0x%llx src=%u dst=%u zlib=%d bcpack=%llu name=%s", path.c_str(),
from_file ? (unsigned long long)e.request.FileOffset : 0ull, e.request.SourceSize,
e.request.DestinationSize, int(options::zlib(o)),
(unsigned long long)options::bcpack(o), rt::io_trace::safe_name(e.request.Name).c_str());
}
}
enqueue(std::move(e));
}
Expand Down
4 changes: 4 additions & 0 deletions runtime/shims/file_system.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
#include "file_system.h"
#include "shims.h"
#include "startup_trace.h"
#include "io_trace.h" // LEONIDA_IO_TRACE
#include "../src/title_page_watch.h"

namespace rt::fs {
Expand Down Expand Up @@ -1713,6 +1714,7 @@ using namespace rt::fs;
// fails with ERROR_NOACCESS (998), and the title's read loop sleeps 1 ms and retries forever (measured on 1.0.2.1,
// native Windows). Touching the pages from user mode commits them; the read is then retried once.
BOOL WINAPI read_file(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) {
rt::io_trace::note_read_file(file, bytes, overlapped);
if (leonida::kernel_writes::read_file(file, buffer, bytes, read, overlapped)) return TRUE;
if (GetLastError() != ERROR_NOACCESS || !buffer || !bytes) return FALSE;
static std::atomic<bool> logged{false};
Expand All @@ -1724,10 +1726,12 @@ BOOL WINAPI read_file(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPO
}
BOOL WINAPI read_file_ex(HANDLE file, LPVOID buffer, DWORD bytes, LPOVERLAPPED overlapped,
LPOVERLAPPED_COMPLETION_ROUTINE routine) {
rt::io_trace::note_read_file(file, bytes, overlapped);
return leonida::kernel_writes::read_file_ex(file, buffer, bytes, overlapped, routine);
}
BOOL WINAPI read_file_scatter(HANDLE file, FILE_SEGMENT_ELEMENT segments[], DWORD bytes, LPDWORD reserved,
LPOVERLAPPED overlapped) {
rt::io_trace::note_read_file(file, bytes, overlapped);
return leonida::kernel_writes::read_file_scatter(file, segments, bytes, reserved, overlapped);
}

Expand Down
100 changes: 100 additions & 0 deletions runtime/shims/io_trace.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#pragma once
// LEONIDA_IO_TRACE=<file> writes one line for every read the title asks for, as it asks (RT-IO-TRACE):
// ds a DirectStorage request (dstorage.cpp): file, file offset, source and destination sizes, zlib/BCPack, the
// request's name;
// rf a ReadFile, ReadFileEx or ReadFileScatter on a disk file (file_system.cpp): path, offset (the OVERLAPPED's, else the handle's
// current position), size.
// Each line starts with the local wall-clock time, as the mem-probe lines in the log do, and is flushed at once, so
// the last reads before a crash or a device loss are on disk; the file is shared for reading while the game runs.
// What the title loaded just before a stop names the asset it was working on. Off, and free, without the variable.

#include <windows.h>
#include <share.h>

#include <cstdarg>
#include <cstdio>
#include <mutex>
#include <string>

namespace rt::io_trace {

inline FILE* out() {
static FILE* file = [] {
wchar_t path[MAX_PATH];
const DWORD n = GetEnvironmentVariableW(L"LEONIDA_IO_TRACE", path, MAX_PATH);
if (!n || n >= MAX_PATH) return static_cast<FILE*>(nullptr);
return _wfsopen(path, L"w", _SH_DENYNO); // readable while the game runs
}();
return file;
}

inline bool enabled() { return out() != nullptr; }

inline std::mutex& mutex() {
static std::mutex m;
return m;
}

// printf-style; the caller checks enabled() first so a disabled trace formats nothing.
inline void line(const char* format, ...) {
FILE* f = out();
if (!f) return;
SYSTEMTIME now;
GetLocalTime(&now);
std::lock_guard lock(mutex());
std::fprintf(f, "%02u:%02u:%02u.%03u ", now.wHour, now.wMinute, now.wSecond, now.wMilliseconds);
va_list args;
va_start(args, format);
std::vfprintf(f, format, args);
va_end(args);
std::fputc('\n', f);
std::fflush(f);
}

// The path of a file handle, asked of the handle each time: a handle value is reused after a close, so a cache by
// value would name the wrong file. ReadFile is a few thousand calls a boot; this is not the hot path.
inline std::string path_of(HANDLE file) {
wchar_t wide[1024];
const DWORD n = GetFinalPathNameByHandleW(file, wide, 1024, FILE_NAME_NORMALIZED);
if (!n || n >= 1024) return "?";
const int len = WideCharToMultiByte(CP_UTF8, 0, wide, int(n), nullptr, 0, nullptr, nullptr);
std::string utf8(size_t(len), ' ');
WideCharToMultiByte(CP_UTF8, 0, wide, int(n), utf8.data(), len, nullptr, nullptr);
return utf8;
}

// A request name the title passed, copied defensively (the pointer is the title's). No C++ objects: __try.
inline int copy_name(const char* name, char* copy, int capacity) {
int n = 0;
__try {
while (n + 1 < capacity && name[n]) {
copy[n] = name[n];
++n;
}
} __except (EXCEPTION_EXECUTE_HANDLER) {
return -1;
}
return n;
}

inline std::string safe_name(const char* name) {
if (!name) return "-";
char copy[128];
const int n = copy_name(name, copy, int(sizeof copy));
return n < 0 ? std::string("<unreadable>") : std::string(copy, size_t(n));
}

inline void note_read_file(HANDLE file, DWORD bytes, const OVERLAPPED* overlapped) {
if (!enabled()) return;
if (GetFileType(file) != FILE_TYPE_DISK) return;
unsigned long long offset = 0;
if (overlapped) {
offset = (unsigned long long)overlapped->Offset | ((unsigned long long)overlapped->OffsetHigh << 32);
} else {
LARGE_INTEGER zero{}, at{};
if (SetFilePointerEx(file, zero, &at, FILE_CURRENT)) offset = (unsigned long long)at.QuadPart;
}
line("rf %s off=0x%llx size=%lu", path_of(file).c_str(), offset, (unsigned long)bytes);
}

} // namespace rt::io_trace
85 changes: 85 additions & 0 deletions runtime/test/io_trace_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// shims/io_trace.h: LEONIDA_IO_TRACE's lines for reads, written through at once and readable while open. A
// temporary folder; no game files, no GPU.
#include "io_trace.h"

#include <windows.h>

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <string>

#define CHECK(condition) do { \
if (!(condition)) { \
std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \
return 1; \
} \
} while (0)

static std::string read_all(const std::filesystem::path& path) {
std::ifstream in(path, std::ios::binary); // works only because the trace shares its file for reading
std::stringstream text;
text << in.rdbuf();
return text.str();
}

int main() {
namespace fs = std::filesystem;
const fs::path dir = fs::temp_directory_path() / ("leonida_io_trace_test_" + std::to_string(GetCurrentProcessId()));
fs::create_directories(dir);
const fs::path trace = dir / "io.log";
const fs::path data = dir / "data.bin";
{ std::ofstream(data, std::ios::binary) << std::string(8192, 'x'); }

// out() opens the file once, at its first call, so the variable is set before anything else.
SetEnvironmentVariableW(L"LEONIDA_IO_TRACE", trace.c_str());
CHECK(rt::io_trace::enabled());

HANDLE file = CreateFileW(data.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
CHECK(file != INVALID_HANDLE_VALUE);
// A positioned read: the handle's current offset.
LARGE_INTEGER at{};
at.QuadPart = 0x1000;
CHECK(SetFilePointerEx(file, at, nullptr, FILE_BEGIN));
rt::io_trace::note_read_file(file, 512, nullptr);
// An overlapped read: the OVERLAPPED's offset, whatever the handle's position.
OVERLAPPED overlapped{};
overlapped.Offset = 0x1800;
rt::io_trace::note_read_file(file, 256, &overlapped);
CloseHandle(file);
// A handle value used again for another file names the new file.
const fs::path other = dir / "other.bin";
{ std::ofstream(other, std::ios::binary) << "y"; }
HANDLE second = CreateFileW(other.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
CHECK(second != INVALID_HANDLE_VALUE);
rt::io_trace::note_read_file(second, 1, nullptr);
CloseHandle(second);
// A DirectStorage-style line, with a name pointer the title owns and one that is not readable.
rt::io_trace::line("ds %s off=0x%llx name=%s", "<memory>", 0ull, rt::io_trace::safe_name("probe").c_str());
rt::io_trace::line("ds name=%s", rt::io_trace::safe_name(reinterpret_cast<const char*>(16)).c_str());
rt::io_trace::line("ds name=%s", rt::io_trace::safe_name(nullptr).c_str());

// Read back while the trace is still open: every line is already on disk.
const std::string text = read_all(trace);
std::fprintf(stderr, "%s", text.c_str());
CHECK(text.find("rf ") != std::string::npos && text.find("data.bin off=0x1000 size=512") != std::string::npos);
CHECK(text.find("data.bin off=0x1800 size=256") != std::string::npos);
CHECK(text.find("other.bin off=0x0 size=1") != std::string::npos);
CHECK(text.find("ds <memory> off=0x0 name=probe") != std::string::npos);
CHECK(text.find("name=<unreadable>") != std::string::npos);
CHECK(text.find("name=-") != std::string::npos);
// Each line starts with hh:mm:ss.mmm.
CHECK(text.size() > 13 && text[2] == ':' && text[5] == ':' && text[8] == '.');
// A pipe is not a disk file: no line.
HANDLE read_end = nullptr, write_end = nullptr;
CHECK(CreatePipe(&read_end, &write_end, nullptr, 0));
const std::size_t before = read_all(trace).size();
rt::io_trace::note_read_file(read_end, 4, nullptr);
CHECK(read_all(trace).size() == before);
CloseHandle(read_end);
CloseHandle(write_end);

std::printf("io_trace: positioned, overlapped and DirectStorage lines, written through and shared for reading\n");
return 0;
}
Loading