Skip to content
Closed
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
6 changes: 6 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
target_compile_definitions(title_write_watch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
target_compile_options(title_write_watch_test PRIVATE /W4 /permissive- /utf-8)

# src/title_page_watch.h at the top of the address space and across reservation edges: no wrap, no endless walk.
add_executable(title_page_watch_bounds_test test/title_page_watch_bounds_test.cpp)
target_compile_definitions(title_page_watch_bounds_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
target_compile_options(title_page_watch_bounds_test PRIVATE /W4 /permissive- /utf-8)

# title_memory_map (src/title_page_watch.h): map changes by range, and the texture pass that probes only what they hit.
add_executable(title_memory_map_test test/title_memory_map_test.cpp)
target_compile_definitions(title_memory_map_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
Expand Down Expand Up @@ -1743,6 +1748,7 @@ if(BUILD_TESTING)
endif()
if(WIN32 AND TARGET title_write_watch_test)
add_test(NAME title_write_watch COMMAND title_write_watch_test)
add_test(NAME title_page_watch_bounds COMMAND title_page_watch_bounds_test)
add_test(NAME title_write_watch_on COMMAND title_write_watch_test)
set_tests_properties(title_write_watch_on PROPERTIES ENVIRONMENT "LEONIDA_WRITE_WATCH=1")
endif()
Expand Down
64 changes: 50 additions & 14 deletions runtime/src/title_page_watch.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
#include "guarded_copy.h"

#include <algorithm>
#include <array>
#include <atomic>
#include <cstdint>
#include <cstdio>
Expand Down Expand Up @@ -217,13 +218,23 @@ inline std::size_t sample(std::vector<std::uintptr_t>& out, std::size_t n) {
return s.aliased.size();
}

// Calls `f(va)` for each aliased 64 KiB page overlapping [begin, end).
// Calls `f(va)` for each aliased 64 KiB page overlapping [begin, end), in no set order. The pages are counted, not
// walked to `end`, so a range ending at the top of the address space (title_memory_map::changed()'s whole range)
// ends; a range with more pages than there are aliased pages looks through the aliased pages instead.
template<class F>
void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) {
State& s = state();
std::shared_lock lock(s.mutex);
if (s.aliased.empty()) return;
for (std::uintptr_t va = begin & ~(kPageSize - 1); va < end; va += kPageSize)
const std::uintptr_t first = begin & ~(kPageSize - 1);
if (s.aliased.empty() || end <= first) return;
const std::uintptr_t pages = (end - first - 1) / kPageSize + 1;
if (pages > s.aliased.size()) {
for (const std::uintptr_t va : s.aliased)
if (va >= first && va < end) f(va);
return;
}
std::uintptr_t va = first;
for (std::uintptr_t i = 0; i < pages; ++i, va += kPageSize)
if (s.aliased.count(va)) f(va);
}

Expand Down Expand Up @@ -400,7 +411,8 @@ inline void note(const void* begin, std::size_t bytes) {
State& s = state();
std::lock_guard lock(s.mutex);
const auto at = reinterpret_cast<std::uintptr_t>(begin);
if (s.ranges.size() < 4096) s.ranges.emplace_back(at, at + bytes);
const std::uintptr_t end = bytes > UINTPTR_MAX - at ? UINTPTR_MAX : at + bytes; // no wrap past the top
if (s.ranges.size() < 4096) s.ranges.emplace_back(at, end);
else s.overflow = true;
s.pending.store(true, std::memory_order_release);
}
Expand Down Expand Up @@ -541,7 +553,9 @@ inline State& state() {
inline void add(std::uintptr_t base, std::uintptr_t size) {
if (!size) return;
State& s = state();
const std::uintptr_t end = base + ((size + kPage - 1) & ~(kPage - 1));
// Whole pages, and no wrap past the top of the address space (the reservation then ends at UINTPTR_MAX).
const std::uintptr_t room = UINTPTR_MAX - base;
const std::uintptr_t end = size > room - (room % kPage) ? UINTPTR_MAX : base + ((size + kPage - 1) & ~(kPage - 1));
std::unique_lock lock(s.mutex);
// A reservation released without remove() overlapping the new one is gone.
auto it = s.regions.lower_bound(base);
Expand Down Expand Up @@ -602,18 +616,35 @@ void for_each_in(std::uintptr_t begin, std::uintptr_t end, F&& f) {
// xmem: [from, to) of a write-watched reservation changed with no write the kernel sees (decommitted, committed again,
// reset): every reader takes its pages as written at its next asking. Past kKeep pages, every reader takes all of its
// write-watched pages as written instead.
// Every write-watched part of [from, to) counts, also when the range starts before a reservation or covers several.
inline void mark(std::uintptr_t from, std::uintptr_t to) {
from &= ~(kPage - 1);
to = (to + kPage - 1) & ~(kPage - 1);
if (from >= to || !contains(from)) return;
to = to > UINTPTR_MAX - (kPage - 1) ? UINTPTR_MAX : (to + kPage - 1) & ~(kPage - 1); // saturates, as changed() does
if (from >= to) return;
// The parts, gathered before the journal's lock (for_each_in takes the record's); past the room here, or past
// kKeep pages in all, every reader takes all of its pages as written.
std::array<std::pair<std::uintptr_t, std::uintptr_t>, 16> parts{};
std::size_t found = 0;
std::uint64_t pages = 0;
bool all = false;
for_each_in(from, to, [&](std::uintptr_t lo, std::uintptr_t hi) {
pages += (hi - lo + kPage - 1) / kPage;
if (found < parts.size()) parts[found++] = {lo, hi};
else all = true;
});
if (!found) return;
State& s = state();
std::lock_guard lock(s.journal);
const std::uint64_t now = s.asked.fetch_add(1, std::memory_order_acq_rel) + 1;
if ((to - from) / kPage > kKeep) {
if (all || pages > kKeep) {
s.floor = now;
return;
}
for (std::uintptr_t p = from; p < to; p += kPage) s.written[p] = now;
for (std::size_t i = 0; i < found; ++i) {
std::uintptr_t p = parts[i].first;
for (std::uint64_t n = (parts[i].second - parts[i].first + kPage - 1) / kPage; n; --n, p += kPage)
s.written[p] = now;
}
}

// A new reader, which has seen everything asked so far (its pages are not known yet: it copies them all first).
Expand Down Expand Up @@ -792,15 +823,16 @@ inline std::uint64_t begin_write(const void* buffer, std::size_t bytes, const OV
const Opener opener = s.opener.load(std::memory_order_acquire);
if (!opener || !buffer || !bytes) return 0;
const auto begin = reinterpret_cast<std::uintptr_t>(buffer);
const std::uintptr_t end = bytes > UINTPTR_MAX - begin ? UINTPTR_MAX : begin + bytes; // no wrap past the top
std::uint64_t id = 0;
{
std::lock_guard lock(s.mutex);
id = s.next_id++;
s.pins.push_back({begin, begin + bytes, overlapped, id, false});
s.pins.push_back({begin, end, overlapped, id, false});
s.count.store(s.pins.size(), std::memory_order_release);
}
// After the pin: a refresh that runs from here on leaves the range writable.
opener(begin, begin + bytes);
opener(begin, end);
return id;
}

Expand Down Expand Up @@ -830,15 +862,16 @@ inline std::uint64_t hold(const void* buffer, std::size_t bytes) {
if (!buffer || !bytes) return 0;
State& s = state();
const auto begin = reinterpret_cast<std::uintptr_t>(buffer);
const std::uintptr_t end = bytes > UINTPTR_MAX - begin ? UINTPTR_MAX : begin + bytes; // no wrap past the top
std::uint64_t id = 0;
{
std::lock_guard lock(s.mutex);
id = s.next_id++;
s.pins.push_back({begin, begin + bytes, nullptr, id});
s.pins.push_back({begin, end, nullptr, id});
s.count.store(s.pins.size(), std::memory_order_release);
}
// After the pin: a guard a refresh made before it is lifted, and no refresh from here on makes one.
if (const Opener opener = s.opener.load(std::memory_order_acquire)) opener(begin, begin + bytes);
if (const Opener opener = s.opener.load(std::memory_order_acquire)) opener(begin, end);
return id;
}

Expand Down Expand Up @@ -950,7 +983,10 @@ inline BOOL read_file_scatter(HANDLE file, FILE_SEGMENT_ELEMENT segments[], DWOR
SYSTEM_INFO info{};
GetSystemInfo(&info);
std::vector<std::uint64_t> pins;
const DWORD count = segments ? (bytes + info.dwPageSize - 1) / info.dwPageSize : 0;
// Counted in 64 bits: `bytes` near 4 GiB would wrap the rounding in a DWORD and pin nothing.
const DWORD count = segments && info.dwPageSize
? DWORD((std::uint64_t(bytes) + info.dwPageSize - 1) / info.dwPageSize)
: 0;
for (DWORD i = 0; i < count; ++i)
pins.push_back(begin_write(segments[i].Buffer, info.dwPageSize, overlapped));
BOOL ok = ::ReadFileScatter(file, segments, bytes, reserved, overlapped);
Expand Down
143 changes: 143 additions & 0 deletions runtime/test/title_page_watch_bounds_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// runtime/src/title_page_watch.h at the edges of the address space and of a write-watched reservation. Only address
// arithmetic: nothing is mapped at the addresses used, nothing reads or writes them. No game data, no GPU.
// 1. title_page_aliases::for_each_in over a range that ends at UINTPTR_MAX ends, and finds the aliased pages in it;
// 2. title_write_watch::mark of a range that starts before a reservation marks the reservation's pages in it;
// 3. title_write_watch::mark of a range that ends near UINTPTR_MAX is not dropped;
// 4. title_write_watch::add of a reservation at the top of the address space does not wrap;
// 5. kernel_writes::begin_write and hold pin a range at the top of the address space without wrapping;
// 6. title_texel_writes::note keeps such a range in order.
#include <windows.h>

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <thread>
#include <vector>

#include "../src/title_page_watch.h"

namespace {

int g_checks = 0;
int g_failures = 0;

void check(bool condition, const char* what) {
++g_checks;
std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
if (!condition) ++g_failures;
}

void opener(std::uintptr_t, std::uintptr_t) {}

} // namespace

int main() {
// 1. Aliased pages near the top; a walk to UINTPTR_MAX must end (it wrapped to 0 and went on before). Run on a
// thread so a hang is reported as a failure instead of stopping the test.
{
namespace aliases = leonida::title_page_aliases;
const std::uintptr_t top = UINTPTR_MAX & ~(aliases::kPageSize - 1);
aliases::set(top, true);
aliases::set(top - 4 * aliases::kPageSize, true);
aliases::set(0x10000000, true); // outside the range below
std::atomic<bool> done{false};
std::vector<std::uintptr_t> found;
std::thread walk([&] {
aliases::for_each_in(top - 8 * aliases::kPageSize, UINTPTR_MAX, [&](std::uintptr_t va) {
if (found.size() < 64) found.push_back(va);
});
done = true;
});
const auto until = std::chrono::steady_clock::now() + std::chrono::seconds(5);
while (!done && std::chrono::steady_clock::now() < until) std::this_thread::sleep_for(std::chrono::milliseconds(5));
check(done, "for_each_in over a range ending at UINTPTR_MAX ends");
if (!done) {
std::printf("title_page_watch_bounds_test: FAILED (the walk did not end)\n");
std::fflush(stdout);
TerminateProcess(GetCurrentProcess(), 1);
}
walk.join();
const bool has_top = std::find(found.begin(), found.end(), top) != found.end();
const bool has_lower = std::find(found.begin(), found.end(), top - 4 * aliases::kPageSize) != found.end();
check(found.size() == 2 && has_top && has_lower, "it finds the two aliased pages in the range, and not the third");
found.clear();
aliases::for_each_in(0x10000000 + 5, 0x10000000 + 6, [&](std::uintptr_t va) { found.push_back(va); });
check(found.size() == 1 && found[0] == 0x10000000, "a range inside one aliased page finds it");
aliases::set(top, false);
aliases::set(top - 4 * aliases::kPageSize, false);
aliases::set(0x10000000, false);
}

namespace ww = leonida::title_write_watch;
const std::uint64_t reader = ww::open_reader();

// 2. A reservation [base, base + 16 pages); a change from one page before it to one page into it.
{
const std::uintptr_t base = 0x7a0000000000;
ww::add(base, 16 * ww::kPage);
ww::mark(base - ww::kPage, base + ww::kPage);
auto& s = ww::state();
bool marked = false, outside = false;
{
std::lock_guard lock(s.journal);
marked = s.written.count(base) != 0;
outside = s.written.count(base - ww::kPage) != 0;
}
check(marked, "mark of a range starting before a reservation marks its first page");
check(!outside, "and not the page before it, which is not write-watched");
ww::remove(base);
}

// 3 and 4. A reservation that ends at the top of the address space.
{
const std::uintptr_t base = UINTPTR_MAX - 0x20000 + 1; // 0x...fffe0000
ww::add(base, 0x40000); // past the top: ends at UINTPTR_MAX
check(ww::contains(base) && ww::contains(UINTPTR_MAX - 1),
"add of a reservation past the top of the address space keeps it (its end does not wrap)");
ww::mark(base + 3 * ww::kPage, UINTPTR_MAX);
auto& s = ww::state();
bool marked = false;
{
std::lock_guard lock(s.journal);
marked = s.written.count(base + 3 * ww::kPage) != 0 && s.written.count(UINTPTR_MAX & ~(ww::kPage - 1)) != 0;
}
check(marked, "mark of a range ending at UINTPTR_MAX marks its pages (the rounding saturates)");
ww::remove(base);
}
ww::close_reader(reader);

// 5. Pins at the top of the address space.
{
namespace kw = leonida::kernel_writes;
kw::set_opener(&opener);
auto* const near_top = reinterpret_cast<void*>(UINTPTR_MAX - 0xfff);
const std::uint64_t pin = kw::begin_write(near_top, 0x2000, nullptr);
int seen = 0;
kw::for_each_pin(UINTPTR_MAX - 0x1000, UINTPTR_MAX, [&](std::uintptr_t, std::uintptr_t) { ++seen; });
check(pin != 0 && seen == 1, "begin_write past the top pins a range for_each_pin finds");
kw::end_write(pin, false);
const std::uint64_t held = kw::hold(near_top, 0x2000);
seen = 0;
kw::for_each_pin(UINTPTR_MAX - 0x1000, UINTPTR_MAX, [&](std::uintptr_t, std::uintptr_t) { ++seen; });
check(held != 0 && seen == 1, "hold past the top pins a range for_each_pin finds");
kw::release(held);
kw::set_opener(nullptr);
}

// 6. A texel write noted past the top.
{
namespace tw = leonida::title_texel_writes;
bool overflow = false;
(void)tw::take(overflow);
tw::note(reinterpret_cast<const void*>(UINTPTR_MAX - 0xfff), 0x2000);
const auto ranges = tw::take(overflow);
check(ranges.size() == 1 && ranges[0].first < ranges[0].second && ranges[0].second == UINTPTR_MAX,
"a texel write past the top is kept as [begin, UINTPTR_MAX)");
}

std::printf("title_page_watch_bounds_test: %s (%d checks, %d failures)\n", g_failures ? "FAILED" : "OK", g_checks,
g_failures);
return g_failures ? 1 : 0;
}
Loading