Skip to content
Merged
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
24 changes: 23 additions & 1 deletion runtime/shims/dstorage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,19 @@ bool guarded_move(void* destination, const void* source, size_t size) {
}
}

// Reads one byte of every 4 KiB page of the range from user mode. Title memory that xmem maps from physical pages is
// committed by a vectored handler on first touch; a kernel write (ReadFile) raises no user-mode fault and fails with
// ERROR_NOACCESS instead. No C++ objects here: the function has __try.
void touch_pages(void* buffer, size_t size) {
const uintptr_t start = reinterpret_cast<uintptr_t>(buffer);
for (uintptr_t page = start & ~uintptr_t{0xfff}; page < start + size; page += 0x1000) {
__try {
(void)*reinterpret_cast<volatile const unsigned char*>(page < start ? start : page);
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
}
}

HRESULT read_error(DWORD error) {
switch (error) {
case ERROR_NOACCESS:
Expand All @@ -432,7 +445,16 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3
at.Offset = static_cast<DWORD>(position);
at.OffsetHigh = static_cast<DWORD>(position >> 32);
DWORD got = 0;
if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError());
if (!ReadFile(handle, out + done, size - done, &got, &at)) {
const DWORD error = GetLastError();
if (error != ERROR_NOACCESS) return read_error(error);
// Destination pages not committed yet (see touch_pages): commit them from user mode and read again once.
touch_pages(out + done, size - done);
at = OVERLAPPED{};
at.Offset = static_cast<DWORD>(position);
at.OffsetHigh = static_cast<DWORD>(position >> 32);
if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError());
}
if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check
done += got;
}
Expand Down
36 changes: 36 additions & 0 deletions runtime/shims/file_system.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,41 @@ void note_open_failure(const char* api, LPCWSTR name, DWORD error, const void* c
rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))));
}

// Reads one byte of every 4 KiB page of [buffer, buffer + size) from user mode, so that pages committed on first
// touch (xmem's physical-page views: a reserve-only section committed by its vectored handler) are committed before
// the kernel writes into them. A page that is not valid at all is left for the caller's ReadFile to refuse. No C++
// objects here: the function has __try.
bool touch_pages(void* buffer, DWORD size) {
auto* p = static_cast<volatile const unsigned char*>(buffer);
const uintptr_t first = reinterpret_cast<uintptr_t>(buffer) & ~uintptr_t{0xfff};
const uintptr_t end = reinterpret_cast<uintptr_t>(buffer) + size;
bool all = true;
for (uintptr_t page = first; page < end; page += 0x1000) {
const uintptr_t at = page < reinterpret_cast<uintptr_t>(p) ? reinterpret_cast<uintptr_t>(p) : page;
__try {
(void)*reinterpret_cast<volatile const unsigned char*>(at);
} __except (EXCEPTION_EXECUTE_HANDLER) {
all = false;
}
}
return all;
}

// ReadFile with one retry for a destination the kernel cannot write yet. The retail title reads into title memory
// that xmem maps from physical pages committed on first touch; the kernel's write raises no user-mode fault, so
// ReadFile 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 size, LPDWORD read, LPOVERLAPPED overlapped) {
if (ReadFile(file, buffer, size, read, overlapped)) return TRUE;
if (GetLastError() != ERROR_NOACCESS || !buffer || !size) return FALSE;
static std::atomic<bool> logged{false};
if (!logged.exchange(true))
std::fprintf(stderr, "[rt] fs: ReadFile into uncommitted title memory (ERROR_NOACCESS): committing the "
"destination pages and retrying (logged once)\n");
touch_pages(buffer, size);
return ReadFile(file, buffer, size, read, overlapped);
}

HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes,
DWORD disposition, DWORD flags, HANDLE template_file) {
if (!name) {
Expand Down Expand Up @@ -1405,6 +1440,7 @@ using namespace rt::fs;
{dll, "CreateFileA", reinterpret_cast<void*>(&create_file_a)}, \
{dll, "CreateFileW", reinterpret_cast<void*>(&create_file_w)}, \
{dll, "CreateFile2", reinterpret_cast<void*>(&create_file2)}, \
{dll, "ReadFile", reinterpret_cast<void*>(&read_file)}, \
{dll, "FindFirstFileA", reinterpret_cast<void*>(&find_first_file_a)}, \
{dll, "FindFirstFileW", reinterpret_cast<void*>(&find_first_file_w)}, \
{dll, "FindFirstFileExA", reinterpret_cast<void*>(&find_first_file_ex_a)}, \
Expand Down
59 changes: 59 additions & 0 deletions runtime/test/file_system_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

#include <algorithm>
#include <clocale>
#include <cstring>
#include <cstdio>
#include <exception>
#include <filesystem>
Expand Down Expand Up @@ -183,6 +184,63 @@ bool host_renames_case(const std::filesystem::path& folder) {

void run_checks(const std::filesystem::path& root);

// Title memory committed on first touch, as xmem maps physical pages: a view of a reserve-only pagefile section whose
// pages a vectored handler commits when user-mode code faults on them. The kernel's write in ReadFile raises no such
// fault, so the host ReadFile fails with ERROR_NOACCESS; the shim commits the pages and reads again.
char* g_first_touch = nullptr;
SIZE_T g_first_touch_size = 0;

LONG CALLBACK commit_on_touch(EXCEPTION_POINTERS* info) {
const EXCEPTION_RECORD* r = info->ExceptionRecord;
if (r->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH;
auto* at = reinterpret_cast<char*>(r->ExceptionInformation[1]);
if (at < g_first_touch || at >= g_first_touch + g_first_touch_size) return EXCEPTION_CONTINUE_SEARCH;
auto* page = reinterpret_cast<char*>(reinterpret_cast<uintptr_t>(at) & ~uintptr_t{0xfff});
return VirtualAlloc(page, 0x1000, MEM_COMMIT, PAGE_READWRITE) ? EXCEPTION_CONTINUE_EXECUTION
: EXCEPTION_CONTINUE_SEARCH;
}

void check_read_file_first_touch(const std::filesystem::path& root) {
using ReadFileFn = BOOL(WINAPI*)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
const auto shim_read = reinterpret_cast<ReadFileFn>(rt::shims::find("kernel32.dll", "ReadFile"));
check(shim_read != nullptr, "ReadFile is served by the file shims");
if (!shim_read) return;

std::filesystem::create_directories(root);
const std::filesystem::path file = root / "first_touch.bin";
constexpr DWORD kSize = 3 * 0x10000 + 123; // crosses several pages and ends inside one
std::vector<unsigned char> data(kSize);
for (DWORD i = 0; i < kSize; ++i) data[i] = static_cast<unsigned char>(i * 7 + 3);
std::ofstream(file, std::ios::binary).write(reinterpret_cast<const char*>(data.data()), kSize);

g_first_touch_size = 4 * 0x10000;
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0,
static_cast<DWORD>(g_first_touch_size), nullptr);
g_first_touch = section ? static_cast<char*>(MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0)) : nullptr;
check(g_first_touch != nullptr, "a reserve-only section view stands in for first-touch title memory");
if (!g_first_touch) return;
void* const handler = AddVectoredExceptionHandler(1, &commit_on_touch);

auto read_into_view = [&](ReadFileFn read) {
HANDLE h = CreateFileW(file.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
DWORD got = 0;
const BOOL ok = read(h, g_first_touch + 0x800, kSize, &got, nullptr);
const DWORD error = ok ? 0 : GetLastError();
CloseHandle(h);
return std::make_pair(ok ? got : 0, error);
};
const auto host = read_into_view(&::ReadFile);
check(host.second == ERROR_NOACCESS, "the host ReadFile into uncommitted pages fails with ERROR_NOACCESS");
const auto shimmed = read_into_view(shim_read);
check(shimmed.second == 0 && shimmed.first == kSize, "the shimmed ReadFile commits the pages and reads it all");
check(std::memcmp(g_first_touch + 0x800, data.data(), kSize) == 0, "the bytes read are the file's");

RemoveVectoredExceptionHandler(handler);
UnmapViewOfFile(g_first_touch);
CloseHandle(section);
g_first_touch = nullptr;
}

} // namespace

int main() {
Expand All @@ -198,6 +256,7 @@ int main() {
// An exception from one check (std::filesystem throws on a host error) ends the checks, not the run: it is a
// failure, the folder is still removed and the summary is still printed.
try {
check_read_file_first_touch(root / "first_touch");
run_checks(root);
} catch (const std::exception& e) {
check(false, (std::string("the checks run to the end (stopped by: ") + e.what() + ")").c_str());
Expand Down