#ifndef CORE_LIBS_PRX_LIBC_INCLUDE_WINDOWSMAPPINGS_HPP #define CORE_LIBS_PRX_LIBC_INCLUDE_WINDOWSMAPPINGS_HPP #ifdef _WIN32 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace GuestArena { class WindowsMappings { public: enum class Collection { All, Armed, Fresh }; static WindowsMappings& Get() { static auto* mappings = new WindowsMappings; return *mappings; } #ifdef APS5_COUNT_MAPPING_QUERIES static std::uint64_t MemoryQueries() { return queries.load(std::memory_order_relaxed); } bool ResidentRunHasNoAccess(std::uintptr_t address) { std::lock_guard lock(mutex); const auto next = residentRuns.upper_bound(address); if (next == residentRuns.begin()) return false; const auto run = std::prev(next); return address < run->second.end && run->second.hasNoAccess; } #endif void* Reserve(void* address, std::size_t bytes) { return allocate(GetCurrentProcess(), address, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0); } std::vector> Commit(void* address, std::size_t bytes, DWORD protection, std::size_t granule, bool watched) { if (granule == 0) throw std::invalid_argument("guest memory commit granule is zero"); std::vector> created; std::lock_guard lock(mutex); collectableRanges.clear(); disown(reinterpret_cast(address), reinterpret_cast(address) + bytes); const DWORD flags = MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER | (watched ? MEM_WRITE_WATCH : 0); const auto cut = [](std::uintptr_t at, std::size_t size, const char* operation) { if (!VirtualFree(reinterpret_cast(at), size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail(operation); }; const auto replace = [&](std::uintptr_t at, std::size_t size) { if (!allocate(GetCurrentProcess(), reinterpret_cast(at), size, flags, protection, nullptr, 0)) fail("replace guest placeholder with private memory"); privateAllocations.emplace(at, at + size); if (watched) markZero(at, at + size); if (!created.empty() && created.back().first + created.back().second == at) created.back().second += size; else created.emplace_back(at, size); }; const auto end = reinterpret_cast(address) + bytes; for (auto cursor = reinterpret_cast(address); cursor < end;) { const auto memory = query(cursor); const auto regionEnd = reinterpret_cast(memory.BaseAddress) + memory.RegionSize; const auto stop = std::min(end, regionEnd); if (memory.State == MEM_RESERVE && std::min(end, cursor + granule) <= regionEnd) { privateAllocations.erase(privateAllocations.lower_bound(cursor), privateAllocations.lower_bound(stop)); forgetClean(cursor, stop); const auto holder = reinterpret_cast(memory.AllocationBase); if (holder != cursor) cut(holder, cursor - holder, "split guest placeholder prefix"); if (stop != regionEnd) cut(cursor, stop - cursor, "split guest placeholder suffix"); while (cursor < stop && std::min(end, cursor + granule) <= stop) { const auto size = std::min(end, cursor + granule) - cursor; if (cursor + size != stop) cut(cursor, size, "split guest placeholder suffix"); replace(cursor, size); cursor += size; } continue; } if (memory.State == MEM_RESERVE) { const auto limit = std::min(end, cursor + granule); auto placeholderEnd = stop; while (placeholderEnd < limit) { const auto next = query(placeholderEnd); if (next.State != MEM_RESERVE) break; placeholderEnd = reinterpret_cast(next.BaseAddress) + next.RegionSize; } const auto size = std::min(limit, placeholderEnd) - cursor; reset(cursor, size); replace(cursor, size); cursor += size; } else { if (memory.State != MEM_COMMIT) throw std::runtime_error("guest memory is not committed"); for (auto mapped = views.lower_bound(cursor & ~(pageBytes - 1)); mapped != views.end() && mapped->first < stop; ++mapped) { mapped->second.protection = protection; mapped->second.armed = 0; invalidate(mapped->first, mapped->second); } updateResidentNoAccess(cursor & ~(pageBytes - 1), stop, protection); DWORD previous; if (!VirtualProtect(reinterpret_cast(cursor), stop - cursor, protection, &previous)) fail("protect guest memory"); cursor = stop; } } return created; } void Reset(void* address, std::size_t bytes) { std::lock_guard lock(mutex); reset(reinterpret_cast(address), bytes); } void MapZero(void* address, std::size_t bytes) { std::lock_guard lock(mutex); if (zeroSection == nullptr && (zeroSection = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READONLY, 0, static_cast(pageBytes), nullptr)) == nullptr) fail("create the read-only zero guest page"); const auto start = reinterpret_cast(address); reset(start, bytes); for (auto cursor = start; cursor < start + bytes; cursor += pageBytes) { split(cursor, pageBytes); if (!map(zeroSection, GetCurrentProcess(), reinterpret_cast(cursor), 0, pageBytes, MEM_REPLACE_PLACEHOLDER, PAGE_READONLY, nullptr, 0)) fail("map the read-only zero guest page"); } } void Map(void* address, std::size_t bytes, HANDLE section, std::uint64_t offset, DWORD protection, bool watched = false, bool resident = false, DWORD viewProtection = PAGE_EXECUTE_READWRITE, std::size_t sectionBytes = SIZE_MAX, std::vector>* createdPrivate = nullptr) { if (sectionBytes < bytes && (resident || sectionBytes == 0 || bytes - sectionBytes >= pageBytes)) throw std::runtime_error("shared guest mapping extends a whole page past its section"); std::lock_guard lock(mutex); collectableRanges.clear(); auto cursor = reinterpret_cast(address); if (createdPrivate != nullptr) createdPrivate->reserve(createdPrivate->size() + bytes / pageBytes); reset(cursor, bytes); if (resident) watchResident = watched; HANDLE duplicate = nullptr; if (!DuplicateHandle(GetCurrentProcess(), section, GetCurrentProcess(), &duplicate, 0, FALSE, DUPLICATE_SAME_ACCESS)) fail("keep shared guest section"); const auto owned = std::make_shared
(duplicate); const auto key = reinterpret_cast(section); const auto slotOf = [&](std::size_t done) -> const std::shared_ptr& { auto& slot = physical[std::make_pair(key, offset + done)]; if (!slot) slot = std::make_shared(); return slot; }; const auto pageOf = [](Physical& slot) { auto shared = slot.page.lock(); if (!shared) { shared = std::make_shared(); shared->comparedWhenShared = slot.comparedWhenShared; slot.page = shared; } return shared; }; const auto single = [&](std::size_t done) { if (!resident || residentRun(key, offset + done) != residentRuns.end()) return false; const auto found = physical.find(std::make_pair(key, offset + done)); if (found == physical.end()) return true; const auto shared = found->second->page.lock(); return !found->second->stored && (!shared || shared->aliases.empty()); }; const bool perPage = !resident && sectionBytes == SIZE_MAX; if (perPage) commitSection(section, offset, bytes); for (std::size_t done = 0; done < bytes;) { const auto base = cursor + done; if (single(done)) { auto runBytes = pageBytes; while (done + runBytes < bytes && (base + runBytes) % chunkBytes != 0 && single(done + runBytes)) runBytes += pageBytes; split(base, runBytes); commitResident(base, runBytes); if (createdPrivate != nullptr) { if (!createdPrivate->empty() && createdPrivate->back().first + createdPrivate->back().second == base) createdPrivate->back().second += runBytes; else createdPrivate->emplace_back(base, runBytes); } const auto run = residentRuns.emplace(base, Run{base + runBytes, {}, static_cast(runBytes >> 12), key, offset + done}).first; run->second.watched = watchResident; run->second.hasNoAccess = protection == PAGE_NOACCESS; residentIndex.emplace(std::make_pair(key, offset + done), run); for (std::size_t at = 0; at < runBytes; at += pageBytes) { bool compared = false; if (const auto found = physical.find(std::make_pair(key, offset + done + at)); found != physical.end()) { const auto& slot = *found->second; if (slot.saved) { std::memcpy(reinterpret_cast(base + at), slot.saved->bytes + slot.savedOffset, pageBytes); forgetZero(base + at, base + at + pageBytes); } compared = slot.comparedWhenShared; physical.erase(found); } views.emplace(base + at, View{nullptr, protection, {}, 0, compared, 0, owned, offset + done + at, 0, 0, true}); } forgetClean(base, base + runBytes); remember(freshRanges, base, base + runBytes); DWORD previous; if (protection != PAGE_READWRITE && !VirtualProtect(reinterpret_cast(base), runBytes, protection, &previous)) fail("protect resident guest pages"); done += runBytes; continue; } if (sectionBytes != SIZE_MAX) { if (const auto run = residentRun(key, offset + done); run != residentRuns.end()) demote(run->first); const auto slot = slotOf(done); const auto shared = pageOf(*slot); for (const auto alias : shared->aliases) views.at(alias).aliasDemoted = false; const auto viewBytes = std::min(pageBytes, sectionBytes - done); split(base, pageBytes); mapShared(base, section, offset + done, protection, viewProtection, viewBytes); slot->stored = true; shared->aliases.push_back(base); const auto created = views.emplace(base, View{shared, protection, {}, 0, false, 0, owned, offset + done, 0, 0, false, slot, hostPages(viewBytes)}).first; if (shared->comparedWhenShared) created->second.unreported = allSubpages; remember(freshRanges, base, base + pageBytes); invalidate(*shared); done += pageBytes; continue; } std::vector, std::shared_ptr>> pages; pages.reserve((bytes - done) / pageBytes); auto runBytes = std::size_t{0}; do { if (const auto run = residentRun(key, offset + done + runBytes); run != residentRuns.end()) demote(run->first); const auto slot = slotOf(done + runBytes); const auto shared = pageOf(*slot); for (const auto alias : shared->aliases) views.at(alias).aliasDemoted = false; pages.emplace_back(slot, shared); runBytes += pageBytes; } while (done + runBytes < bytes && !single(done + runBytes)); if (!perPage) commitSection(section, offset + done, runBytes); split(base, runBytes); mapRun(base, runBytes, section, offset + done); DWORD previous; if (!VirtualProtect(reinterpret_cast(base), runBytes, protection, &previous)) fail("protect shared guest pages"); collectableRanges.clear(); for (std::size_t at = 0; at < runBytes; at += pageBytes) { auto& [slot, shared] = pages[at / pageBytes]; slot->stored = true; shared->aliases.push_back(base + at); invalidate(*shared); const auto created = views.emplace(base + at, View{std::move(shared), protection, {}, 0, false, 0, owned, offset + done + at, 0, 0, false, std::move(slot)}).first; if (created->second.page->comparedWhenShared) created->second.unreported = allSubpages; } remember(freshRanges, base, base + runBytes); done += runBytes; } } void SetProtection(std::uintptr_t address, std::size_t bytes, DWORD protection) { std::lock_guard lock(mutex); disown(address, address + bytes); collectableRanges.clear(); for (auto it = views.lower_bound(address); it != views.end() && it->first < address + bytes; ++it) { it->second.protection = protection; it->second.armed = 0; invalidate(it->first, it->second); } updateResidentNoAccess(address, address + bytes, protection); } void Pin(std::uintptr_t address, std::size_t bytes) { std::lock_guard lock(mutex); disown(address, address + bytes); ownedPins.emplace(address, address + bytes); for (auto it = views.lower_bound(address & ~(pageBytes - 1)); it != views.end() && it->first < address + bytes; ++it) { if (it->second.resident) { ++it->second.pins; invalidate(it->first, it->second); continue; } auto& page = *it->second.page; ++page.pins; for (const auto alias : page.aliases) { auto& view = views.at(alias); if (view.armed == 0) continue; protectSubpages(alias, view.armed, view.protection, "pin shared guest page writable", view.viewBytes); view.armed = 0; } invalidate(page); } } void Unpin(std::uintptr_t address, std::size_t bytes) { std::lock_guard lock(mutex); disown(address, address + bytes); eraseOwnedRange(ownedPins, address, address + bytes); for (auto it = views.lower_bound(address & ~(pageBytes - 1)); it != views.end() && it->first < address + bytes; ++it) { auto& pins = it->second.resident ? it->second.pins : it->second.page->pins; if (pins != 0) --pins; invalidate(it->first, it->second); } } void CompareWhenShared(std::uintptr_t address, std::size_t bytes, bool residentOnly = false) { std::lock_guard lock(mutex); collectableRanges.clear(); for (auto it = views.lower_bound(address & ~(pageBytes - 1)); it != views.end() && it->first < address + bytes; ++it) { if (residentOnly && !it->second.resident && !it->second.aliasDemoted) continue; if (it->second.resident) { it->second.comparedWhenShared = true; continue; } auto& page = *it->second.page; const bool marked = page.comparedWhenShared; page.comparedWhenShared = true; it->second.slot->comparedWhenShared = true; for (const auto alias : page.aliases) { auto& view = views.at(alias); if (view.resident) continue; if (!marked) view.unreported = allSubpages; if (view.armed == 0) continue; protectSubpages(alias, view.armed, view.protection, "stop arming a compared shared page", view.viewBytes); view.armed = 0; } } } void ComparedPages(std::uintptr_t address, std::size_t bytes, void** pages, std::size_t* count, bool unreported) { std::lock_guard lock(mutex); const auto capacity = *count; *count = 0; const auto end = address + bytes; for (auto it = views.lower_bound(address & ~(pageBytes - 1)); it != views.end() && it->first < end; ++it) { auto& view = it->second; if (view.resident || !view.page->comparedWhenShared) continue; const auto listed = static_cast(subpagesOf(it->first, address, end) & (unreported ? view.unreported : allSubpages)); for (std::size_t sub = 0; sub < subpages; ++sub) { const auto bit = static_cast(1u << sub); if ((listed & bit) == 0) continue; if (*count == capacity) return; pages[(*count)++] = reinterpret_cast(it->first + sub * subpageBytes); if (unreported) view.unreported &= static_cast(~bit); } } } bool HandleWrite(std::uintptr_t address) { std::lock_guard lock(mutex); const auto base = address & ~(pageBytes - 1); const auto found = views.find(base); if (found == views.end() || !writable(found->second.protection)) return false; auto& view = found->second; if (view.resident) { const auto memory = query(address); return memory.State == MEM_COMMIT && writable(memory.Protect & 0xffu); } const auto written = subpagesOf(base, address, address + 1); invalidate(*view.page, written); protectSubpages(base, written, view.protection, "resume shared memory write", view.viewBytes); view.armed &= static_cast(~written); return true; } bool HandleRead(std::uintptr_t address) { std::lock_guard lock(mutex); if (!views.contains(address & ~(pageBytes - 1))) return false; const auto memory = query(address); return memory.State == MEM_COMMIT && (memory.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0; } bool ResidentSpan(std::uintptr_t address, std::size_t bytes, std::uintptr_t* start, std::uintptr_t* end) { std::lock_guard lock(mutex); auto run = residentRuns.upper_bound(address); if (run != residentRuns.begin() && std::prev(run)->second.end > address) --run; if (run == residentRuns.end() || run->first >= address + bytes) return false; *start = run->first; for (; run != residentRuns.end() && run->first < address + bytes; ++run) *end = run->second.end; return true; } bool ForgetSection(HANDLE section) { std::lock_guard lock(mutex); const auto key = reinterpret_cast(section); const auto first = physical.lower_bound(std::make_pair(key, std::uint64_t{0})); const auto last = physical.lower_bound(std::make_pair(key + 1, std::uint64_t{0})); bool blank = std::none_of(first, last, [](const auto& entry) { return entry.second->stored || !entry.second->page.expired(); }); physical.erase(first, last); for (auto run = residentIndex.lower_bound(std::make_pair(key, std::uint64_t{0})); run != residentIndex.end() && run->first.first == key; run = residentIndex.erase(run)) blank = false; return blank; } bool BeginHostWrite(std::uintptr_t address, std::size_t bytes, bool store = true) { std::lock_guard lock(mutex); const auto first = views.lower_bound(address & ~(pageBytes - 1)); const auto end = address + bytes; for (auto it = first; it != views.end() && it->first < end; ++it) { if (!writable(it->second.protection)) return false; } disown(address, end); forgetZero(address, end); ownedHostAccess.emplace(address, end); if (store) ownedHostStores.emplace(address, end); for (auto it = first; it != views.end() && it->first < end; ++it) { auto& view = it->second; if (store) ++view.hostWrites; else ++view.hostImports; const auto written = subpagesOf(it->first, address, end); if (store) invalidate(it->first, view, written); else if (view.resident) { forgetClean(it->first, it->first + pageBytes); markImported(it->first); } const auto opened = static_cast((store || view.resident) ? view.armed & written : 0); if (opened == 0) continue; protectSubpages(it->first, opened, view.protection, "open shared memory to a host write", view.viewBytes); view.armed &= static_cast(~opened); } return true; } void EndHostWrite(std::uintptr_t address, std::size_t bytes, bool store = true) { std::lock_guard lock(mutex); const auto end = address + bytes; disown(address, end); eraseOwnedRange(ownedHostAccess, address, end); if (store) eraseOwnedRange(ownedHostStores, address, end); for (auto it = views.lower_bound(address & ~(pageBytes - 1)); it != views.end() && it->first < end; ++it) { if (store) --it->second.hostWrites; else --it->second.hostImports; if (store) invalidate(it->first, it->second, subpagesOf(it->first, address, end)); else if (it->second.resident) forgetClean(it->first, it->first + pageBytes); } } static std::vector TouchedPages(std::uintptr_t start, std::size_t pages, void* const* written, std::size_t count) { std::vector touched(pages); for (std::size_t index = 0; index < count; ++index) { const auto page = (reinterpret_cast(written[index]) - start) / pageBytes; if (page < pages) touched[page] = true; } return touched; } void markImported(std::uintptr_t page) { const auto next = residentRuns.upper_bound(page); if (next == residentRuns.begin()) return; const auto run = std::prev(next); if (page < run->second.end) run->second.imported = true; } void* MapAlias(std::uintptr_t address, std::size_t bytes, bool* boundsRefused = nullptr) { std::lock_guard lock(mutex); if (boundsRefused != nullptr) *boundsRefused = false; const auto refuse = [&](const char* reason) { char text[192]; std::snprintf(text, sizeof(text), "read-write alias of shared guest memory 0x%llx+0x%llx: %s", static_cast(address), static_cast(bytes), reason); return std::runtime_error(text); }; if (address % pageBytes != 0 || bytes % pageBytes != 0 || bytes == 0) throw refuse("the range is not made of whole shared pages"); for (std::size_t done = 0; done < bytes; done += pageBytes) { const auto found = views.find(address + done); if (found == views.end() || !found->second.resident) continue; const auto run = std::prev(residentRuns.upper_bound(address + done)); if (run->first < address || run->second.end > address + bytes) { if (boundsRefused != nullptr) *boundsRefused = true; throw refuse("a resident run of direct memory extends outside the range"); } for (auto page = views.find(run->first); page != views.end() && page->first < run->second.end; ++page) { if (page->second.hostWrites != 0) return nullptr; } } for (std::size_t done = 0; done < bytes; done += pageBytes) { const auto found = views.find(address + done); if (found != views.end() && found->second.resident) demote(address + done, true); } auto view = views.find(address); if (view == views.end()) throw refuse("the range does not start at a shared view"); const auto section = view->second.section; const auto offset = view->second.offset; SYSTEM_INFO system{}; GetSystemInfo(&system); bool contiguous = true; for (std::size_t done = 0; done < bytes; done += pageBytes) { const auto page = views.find(address + done); if (page == views.end()) throw refuse("the range is not a run of shared views"); if (page->second.viewBytes != pageBytes) throw refuse("a page extends past the end of its file"); if (page->second.offset != offset + done || (page->second.section != section && !sameSection(page->second.section->handle, section->handle))) contiguous = false; } if (!contiguous) return mapAliasRuns(address, bytes); const auto lead = offset % system.dwAllocationGranularity; void* alias = map(section->handle, GetCurrentProcess(), nullptr, offset - lead, lead + bytes, 0, PAGE_READWRITE, nullptr, 0); if (alias == nullptr) { char text[160]; std::snprintf(text, sizeof(text), "MapViewOfFile3 of a read-write alias of shared guest memory 0x%llx+0x%llx", static_cast(address), static_cast(bytes)); throw std::system_error(static_cast(GetLastError()), std::system_category(), text); } return static_cast(alias) + lead; } void UnmapAlias(void* alias) { if (alias == nullptr) return; { std::lock_guard lock(mutex); if (const auto found = splitAliases.find(reinterpret_cast(alias)); found != splitAliases.end()) { const auto error = releaseAlias(found->first, found->second); splitAliases.erase(found); if (error != ERROR_SUCCESS) throw std::system_error(static_cast(error), std::system_category(), "unmap a run of a shared guest alias"); return; } } SYSTEM_INFO system{}; GetSystemInfo(&system); const auto base = reinterpret_cast(alias) & ~(static_cast(system.dwAllocationGranularity) - 1); if (!unmap(GetCurrentProcess(), reinterpret_cast(base), 0)) fail("unmap shared guest alias"); } bool ProtectsItself(std::uintptr_t address, std::size_t bytes) { std::lock_guard lock(mutex); for (auto it = views.lower_bound(address & ~(pageBytes - 1)); it != views.end() && it->first < address + bytes; ++it) { if (!it->second.resident || it->second.aliasDemoted) return true; } return false; } bool Protection(std::uintptr_t address, std::uint32_t* protection) { std::lock_guard lock(mutex); const auto found = views.find(address & ~(pageBytes - 1)); if (found == views.end()) return false; *protection = found->second.protection; return true; } #ifdef APS5_COUNT_MAPPING_QUERIES void CollectWork(std::uint64_t* systemCalls, std::uint64_t* pieces) { std::lock_guard lock(mutex); *systemCalls = collectSystemCalls; *pieces = collectPieces; } #endif static constexpr std::size_t ownedBlockBytes = 0x10000; #ifdef GUEST_OWNED_LIMIT_TEST static constexpr std::size_t ownedEntryLimit = 8; #else static constexpr std::size_t ownedEntryLimit = 65536; #endif static constexpr unsigned OwnedPrivate = 1; bool ArmOwned(std::uintptr_t address, std::size_t bytes, std::uint64_t* words, std::size_t count, unsigned flags = 0) { std::lock_guard lock(mutex); if (words == nullptr || (flags & ~OwnedPrivate) != 0 || !ownedRange(address, bytes, count)) return false; if (nextOwned == 0 || count > UINT64_MAX - nextOwned + 1) return false; const auto first = address & ~(ownedBlockBytes - 1); const auto end = (address + bytes - 1) | (ownedBlockBytes - 1); if (count > ownedEntryLimit) return false; std::size_t alreadyPending = 0; for (auto it = ownedPending.lower_bound(first); it != ownedPending.end() && it->first <= end; ++it) ++alreadyPending; if (count - alreadyPending > ownedEntryLimit - ownedPending.size()) return false; for (auto block = first; block < end; block += ownedBlockBytes) { if (!ownable(block, flags)) return false; } disown(first, end + 1); while (ownedWords.size() > ownedEntryLimit - count) ownedWords.erase(ownedWords.begin()); for (auto block = first; block < end; block += ownedBlockBytes) { auto& pending = ownedPending[block]; auto run = residentRuns.upper_bound(block); if (run != residentRuns.begin() && std::prev(run)->second.end > block) --run; for (; run != residentRuns.end() && run->first < block + ownedBlockBytes; ++run) run->second.reset = true; std::array written{}; ULONG_PTR reported = written.size(); DWORD granularity = 0; if (watchWrites(WRITE_WATCH_FLAG_RESET, reinterpret_cast(block), ownedBlockBytes, written.data(), &reported, &granularity) != 0) return false; for (ULONG_PTR index = 0; index < reported; ++index) pending |= std::uint16_t{1} << ((reinterpret_cast(written[index]) - block) / 4096); if (pending == 0) ownedPending.erase(block); } for (auto block = first; block < end; block += ownedBlockBytes) { ownedWords[block] = nextOwned++; } for (auto block = first; block < end; block += ownedBlockBytes) words[(block - first) / ownedBlockBytes] = ownedWords.at(block); return true; } bool OwnedUnchanged(std::uintptr_t address, std::size_t bytes, const std::uint64_t* words, std::size_t count) { std::lock_guard lock(mutex); if (words == nullptr || !ownedRange(address, bytes, count)) return false; const auto first = address & ~(ownedBlockBytes - 1); const auto end = (address + bytes - 1) | (ownedBlockBytes - 1); for (auto block = first; block < end; block += ownedBlockBytes) { const auto found = ownedWords.find(block); if (found == ownedWords.end() || found->second != words[(block - first) / ownedBlockBytes]) return false; std::array written{}; ULONG_PTR reported = written.size(); DWORD granularity = 0; if (watchWrites(0, reinterpret_cast(block), ownedBlockBytes, written.data(), &reported, &granularity) != 0 || reported != 0) { ownedWords.erase(found); return false; } } return true; } void ForgetKnownZero(std::uintptr_t address, std::size_t bytes) { if (bytes == 0 || bytes > UINTPTR_MAX - address) return; std::lock_guard lock(mutex); forgetZero(address, address + bytes); } std::uint64_t KnownZeroMarks() const { return zeroMarks.load(std::memory_order_acquire); } void KnownZero(std::uintptr_t address, std::size_t bytes, void (*zero)(void* context, std::uintptr_t begin, std::uintptr_t end), void* context) { if (bytes == 0 || bytes > UINTPTR_MAX - address) return; const auto end = address + bytes; std::uintptr_t reportStart = 0; std::uintptr_t reportEnd = 0; std::vector> found; const auto report = [&](std::uintptr_t from, std::uintptr_t to) { from = std::max(from, address); to = std::min(to, end); if (from >= to) return; if (!found.empty() && found.back().second == from) found.back().second = to; else found.emplace_back(from, to); }; const auto deliver = [&] { for (const auto& [from, to] : found) { if (reportEnd == from) { reportEnd = to; continue; } if (reportEnd > reportStart) zero(context, reportStart, reportEnd); reportStart = from; reportEnd = to; } found.clear(); }; for (auto cursor = address & ~std::uintptr_t{4095}; cursor < end;) { const auto chunk = cursor & ~(chunkBytes - 1); const auto chunkEnd = std::min(end, chunk + chunkBytes); std::unique_lock lock(mutex); if (zeroPages.empty()) break; if (zeroPages.find(chunk) == zeroPages.end()) { cursor = chunkEnd; continue; } while (cursor < chunkEnd) { const auto limit = zeroSpanEnd(cursor); const auto stop = limit == 0 ? std::min(chunkEnd, (cursor & ~(pageBytes - 1)) + pageBytes) : std::min(chunkEnd, limit); if (limit == 0) forgetZero(cursor, stop); else harvestZero(cursor, stop); if (const auto bits = zeroPages.find(chunk); bits != zeroPages.end()) { for (auto page = cursor; page < stop; page += 4096) { const auto bit = (page - chunk) >> 12; if ((bits->second[bit >> 6] >> (bit & 63) & 1) != 0) report(page, page + 4096); } } cursor = stop; } lock.unlock(); deliver(); } deliver(); if (reportEnd > reportStart) zero(context, reportStart, reportEnd); } bool Collect(std::uintptr_t address, std::size_t bytes, void** pages, std::size_t* count, bool clear, Collection collection = Collection::All) { std::lock_guard lock(mutex); const auto capacity = *count; if (!collect(address, bytes, pages, count, clear, collection)) return false; addHostWrites(address, address + bytes, pages, count, capacity); return true; } private: void addHostWrites(std::uintptr_t address, std::uintptr_t end, void** pages, std::size_t* count, std::size_t capacity) const { if (ownedHostStores.empty() || !overlapsOwnedRange(ownedHostStores, address, end)) return; std::vector merged; merged.reserve(*count); for (std::size_t index = 0; index < *count; ++index) merged.push_back(reinterpret_cast(pages[index])); const auto collected = merged.size(); for (const auto& [first, last] : ownedHostStores) { const auto from = std::max(first, address) & ~std::uintptr_t{4095}; const auto to = std::min(last, end); for (auto page = from; page < to; page += 4096) merged.push_back(std::max(page, address)); } if (merged.size() == collected) return; std::sort(merged.begin(), merged.end()); merged.erase(std::unique(merged.begin(), merged.end()), merged.end()); *count = std::min(merged.size(), capacity); for (std::size_t index = 0; index < *count; ++index) pages[index] = reinterpret_cast(merged[index]); } bool collect(std::uintptr_t address, std::size_t bytes, void** pages, std::size_t* count, bool clear, Collection collection) { const auto capacity = *count; *count = 0; const auto end = address + bytes; if (clear) disown(address, end); auto resIt = residentRuns.upper_bound(address); if (resIt != residentRuns.begin() && std::prev(resIt)->second.end > address) --resIt; if (collection == Collection::Fresh) { const auto fresh = freshRanges.upper_bound(address); if ((fresh == freshRanges.begin() || std::prev(fresh)->second <= address) && (fresh == freshRanges.end() || fresh->first >= end)) return true; auto checkRun = resIt; for (auto checkAt = address & ~(pageBytes - 1); checkAt < end;) { while (checkRun != residentRuns.end() && checkRun->second.end <= checkAt) ++checkRun; if (checkRun != residentRuns.end() && checkRun->first <= checkAt) { if (!watchResident) return false; checkAt = checkRun->second.end; continue; } const auto stopAt = checkRun == residentRuns.end() ? end : std::min(end, checkRun->first); for (auto it = views.lower_bound(checkAt); it != views.end() && it->first < stopAt; ++it) { if (it->second.resident) { if (!watchResident) return false; continue; } if (it->second.page->comparedWhenShared) return false; if (it->second.protection != PAGE_NOACCESS) continue; for (auto at = std::max(address, it->first); at < std::min(end, it->first + pageBytes); at += 4096) { if ((it->second.collected & (1u << ((at - it->first) / 4096))) == 0) return false; } } checkAt = stopAt; } } else if (clear && !collectable(address, end)) return false; bool viewsReady = false; Views::iterator position = views.end(); std::uintptr_t cleanStart = 0; std::uintptr_t cleanEnd = 0; const auto flushClean = [&] { if (cleanEnd > cleanStart) rememberClean(cleanStart, cleanEnd); cleanStart = cleanEnd = 0; }; for (auto cursor = address; cursor < end;) { auto cleanLimit = end; if (!cleanRanges.empty()) { const auto nextClean = cleanRanges.upper_bound(cursor); if (nextClean != cleanRanges.begin()) { const auto clean = std::prev(nextClean); if (cursor < clean->second) { cursor = std::min(end, clean->second); continue; } } if (nextClean != cleanRanges.end() && nextClean->first < cleanLimit) cleanLimit = nextClean->first; } while (resIt != residentRuns.end() && resIt->second.end <= cursor) ++resIt; if (resIt != residentRuns.end() && resIt->first <= cursor) { flushClean(); if (!watchResident) return false; const auto available = capacity - *count; if (available == 0) return true; const auto stop = std::min({cleanLimit, resIt->second.end, (cursor & ~std::uintptr_t{4095}) + available * 4096}); collectResident(resIt->first, resIt->second, cursor, stop, pages, count, clear, collection); if (*count == capacity) return true; cursor = stop; continue; } const auto base = cursor & ~(pageBytes - 1); if (!viewsReady) { position = views.lower_bound(base); viewsReady = true; } const auto found = viewAt(base, position); if (found != views.end()) { auto& view = found->second; auto stop = std::min(cleanLimit, base + pageBytes); if (collection != Collection::All) { const auto selected = [&](std::uintptr_t at) { const bool collected = (view.collected & (1u << ((at - base) / 4096))) != 0; return collection == Collection::Armed ? collected : !collected; }; while (cursor < stop && !selected(cursor)) cursor = std::min(stop, cursor + 4096); if (cursor == stop) continue; for (auto at = cursor + 4096; at < stop; at += 4096) { if (!selected(at)) { stop = at; break; } } } if (view.protection == PAGE_NOACCESS) { flushClean(); return false; } const bool pinned = view.page->pins != 0; std::uint8_t settled = 0; auto settledEnd = cursor; bool full = false; for (std::size_t sub = 0; sub < subpages; ++sub) { const auto from = std::max(cursor, base + sub * subpageBytes); const auto to = std::min(stop, base + (sub + 1) * subpageBytes); if (from >= to) continue; if (collection == Collection::Fresh || pinned || view.seen[sub] != view.page->generation[sub]) { if (*count == capacity) { full = true; break; } pages[(*count)++] = reinterpret_cast(from); } settled |= static_cast(1u << sub); settledEnd = to; } if (clear) { for (std::size_t sub = 0; sub < subpages; ++sub) { const auto bit = static_cast(1u << sub); if ((settled & bit) == 0 || (view.collected & bit) != 0) continue; view.collected |= bit; forget(freshRanges, base + sub * subpageBytes, base + (sub + 1) * subpageBytes); } } if (clear && !pinned && settled != 0) { std::uint8_t untracked = 0; for (const auto alias : view.page->aliases) { auto& other = views.at(alias); if (other.resident) continue; const auto arming = static_cast(settled & ~other.armed); if (!writable(other.protection) || arming == 0) continue; if (other.hostWrites != 0) { untracked |= arming; continue; } const DWORD protection = other.protection == PAGE_EXECUTE_READWRITE ? PAGE_EXECUTE_READ : PAGE_READONLY; protectSubpages(alias, arming, protection, "arm shared memory write tracking", other.viewBytes); other.armed |= arming; } const auto tracked = static_cast(settled & ~untracked); for (std::size_t sub = 0; sub < subpages; ++sub) { if ((tracked & (1u << sub)) == 0) continue; const auto from = std::max(cursor, base + sub * subpageBytes); const auto to = std::min(settledEnd, base + (sub + 1) * subpageBytes); if (from == base + sub * subpageBytes && to == base + (sub + 1) * subpageBytes) view.seen[sub] = view.page->generation[sub]; if (from != cleanEnd) { flushClean(); cleanStart = from; } cleanEnd = to; } } if (full) { flushClean(); return true; } cursor = stop; } else { flushClean(); if (collection == Collection::Fresh) { const auto next = views.lower_bound(cursor); cursor = next == views.end() ? end : std::min(end, next->first); continue; } const auto allocationEnd = privateAllocationEnd(cursor); if (allocationEnd == 0) return false; if (capacity == *count) return true; const auto stop = ownedPending.empty() ? std::min(end, allocationEnd) : std::min({end, allocationEnd, (cursor & ~std::uintptr_t{4095}) + (capacity - *count) * 4096}); const auto touched = (((stop + 4095) & ~static_cast(4095)) - (cursor & ~static_cast(4095))) / 4096; ULONG_PTR available = std::min(capacity - *count, touched); DWORD granularity = 0; #ifdef APS5_COUNT_MAPPING_QUERIES ++collectSystemCalls; collectPieces += (stop + pageBytes - 1) / pageBytes - cursor / pageBytes; #endif const bool committed = !verifyDirect() || committedPrivate(cursor, stop); if (collectOwnedWrites(clear ? WRITE_WATCH_FLAG_RESET : 0, reinterpret_cast(cursor), stop - cursor, pages + *count, &available, &granularity) != 0) { const auto memory = query(cursor); if (memory.State != MEM_COMMIT || memory.Type != MEM_PRIVATE) return false; fail("collect private guest writes"); } if (!committed) staleProof(cursor, stop); *count += available; if (*count == capacity) return true; cursor = stop; } } flushClean(); return true; } private: using OwnedRanges = std::multimap; class Lock { public: Lock() : pthread(std::getenv("APS5_MAPPINGS_PTHREAD_LOCK") != nullptr) {} Lock(const Lock&) = delete; Lock& operator=(const Lock&) = delete; void lock() { if (pthread) fallback.lock(); else AcquireSRWLockExclusive(&native); } bool try_lock() { return pthread ? fallback.try_lock() : TryAcquireSRWLockExclusive(&native) != 0; } void unlock() { if (pthread) fallback.unlock(); else ReleaseSRWLockExclusive(&native); } private: SRWLOCK native = SRWLOCK_INIT; std::mutex fallback; bool pthread; }; static bool ownedRange(std::uintptr_t address, std::size_t bytes, std::size_t count) { if (address == 0 || bytes == 0 || address >= (std::uintptr_t{1} << 47) || bytes > (std::uintptr_t{1} << 47) - address) return false; return count == ((address + bytes - 1) / ownedBlockBytes - address / ownedBlockBytes + 1); } static bool overlapsOwnedRange(const OwnedRanges& ranges, std::uintptr_t first, std::uintptr_t end) { for (auto it = ranges.begin(); it != ranges.end() && it->first < end; ++it) { if (it->second > first) return true; } return false; } static void eraseOwnedRange(OwnedRanges& ranges, std::uintptr_t first, std::uintptr_t end) { const auto [begin, stop] = ranges.equal_range(first); for (auto it = begin; it != stop; ++it) { if (it->second == end) { ranges.erase(it); return; } } } void disown(std::uintptr_t first, std::uintptr_t end) { if (ownedWords.empty() || end <= first) return; ownedWords.erase(ownedWords.lower_bound(first & ~(ownedBlockBytes - 1)), ownedWords.lower_bound(end)); } bool ownable(std::uintptr_t block, unsigned flags) { const auto end = block + ownedBlockBytes; if (overlapsOwnedRange(ownedPins, block, end) || overlapsOwnedRange(ownedHostAccess, block, end)) return false; for (auto cursor = block; cursor < end;) { const auto memory = query(cursor); if (memory.State != MEM_COMMIT || memory.Type != MEM_PRIVATE || (memory.Protect != PAGE_READWRITE && memory.Protect != PAGE_EXECUTE_READWRITE)) return false; const auto found = views.find(cursor & ~(pageBytes - 1)); if (found != views.end()) { const auto& view = found->second; if (!view.resident || view.pins != 0 || view.hostWrites != 0 || view.hostImports != 0 || !writable(view.protection)) return false; const auto next = residentRuns.upper_bound(cursor); if (next == residentRuns.begin() || cursor >= std::prev(next)->second.end || !std::prev(next)->second.watched) return false; } else if ((flags & OwnedPrivate) == 0 || privateAllocationEnd(cursor) == 0) return false; cursor = std::min({end, (cursor & ~(pageBytes - 1)) + pageBytes, reinterpret_cast(memory.BaseAddress) + memory.RegionSize}); } std::array written{}; ULONG_PTR reported = written.size(); DWORD granularity = 0; return watchWrites(0, reinterpret_cast(block), ownedBlockBytes, written.data(), &reported, &granularity) == 0; } void forgetOwnedPending(std::uintptr_t first, std::uintptr_t end) { for (auto it = ownedPending.lower_bound(first & ~(ownedBlockBytes - 1)); it != ownedPending.end() && it->first < end;) { for (unsigned bit = 0; bit < ownedBlockBytes / 4096; ++bit) { const auto page = it->first + bit * 4096; if (page < end && page + 4096 > first) it->second &= ~(std::uint16_t{1} << bit); } if (it->second == 0) it = ownedPending.erase(it); else ++it; } } void markZero(std::uintptr_t start, std::uintptr_t end) { start = (start + 4095) & ~std::uintptr_t{4095}; end &= ~std::uintptr_t{4095}; if (start >= end) return; while (start < end) { const auto chunk = start & ~(chunkBytes - 1); const auto stop = std::min(end, chunk + chunkBytes); auto& bits = zeroPages[chunk]; for (auto bit = (start - chunk) >> 12; bit < (stop - chunk) >> 12; ++bit) bits[bit >> 6] |= std::uint64_t{1} << (bit & 63); start = stop; } zeroMarks.fetch_add(1, std::memory_order_release); } static void clearZeroBits(auto& bits, std::uintptr_t chunk, std::uintptr_t from, std::uintptr_t to) { for (auto bit = (from - chunk) >> 12; bit < (to - chunk) >> 12; ++bit) bits[bit >> 6] &= ~(std::uint64_t{1} << (bit & 63)); } static bool noZeroBits(const auto& bits) { return std::all_of(bits.begin(), bits.end(), [](std::uint64_t word) { return word == 0; }); } void forgetZero(std::uintptr_t start, std::uintptr_t end) { if (zeroPages.empty() || end <= start) return; start &= ~std::uintptr_t{4095}; end = (end + 4095) & ~std::uintptr_t{4095}; if ((end - start) / chunkBytes > zeroPages.size()) { for (auto it = zeroPages.begin(); it != zeroPages.end();) { const auto chunk = it->first; if (chunk + chunkBytes <= start || chunk >= end) { ++it; continue; } clearZeroBits(it->second, chunk, std::max(start, chunk), std::min(end, chunk + chunkBytes)); if (noZeroBits(it->second)) it = zeroPages.erase(it); else ++it; } return; } while (start < end) { const auto chunk = start & ~(chunkBytes - 1); const auto stop = std::min(end, chunk + chunkBytes); if (const auto found = zeroPages.find(chunk); found != zeroPages.end()) { clearZeroBits(found->second, chunk, start, stop); if (noZeroBits(found->second)) zeroPages.erase(found); } start = stop; } } bool anyZero(std::uintptr_t start, std::uintptr_t end) const { if (zeroPages.empty()) return false; start &= ~std::uintptr_t{4095}; end = (end + 4095) & ~std::uintptr_t{4095}; while (start < end) { const auto chunk = start & ~(chunkBytes - 1); const auto stop = std::min(end, chunk + chunkBytes); if (const auto found = zeroPages.find(chunk); found != zeroPages.end()) { for (auto bit = (start - chunk) >> 12; bit < (stop - chunk) >> 12; ++bit) { if ((found->second[bit >> 6] >> (bit & 63) & 1) != 0) return true; } } start = stop; } return false; } bool stillZero(std::uintptr_t page) const { const auto found = zeroPages.find(page & ~(chunkBytes - 1)); if (found == zeroPages.end()) return false; const auto bit = (page & (chunkBytes - 1)) >> 12; if ((found->second[bit >> 6] >> (bit & 63) & 1) == 0) return false; thread_local std::array bytes{}; SIZE_T read = 0; if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(page), bytes.data(), sizeof(bytes), &read) || read != sizeof(bytes)) return false; return std::all_of(bytes.begin(), bytes.end(), [](std::uint64_t word) { return word == 0; }); } UINT watchWrites(DWORD flags, void* address, std::size_t bytes, void** pages, ULONG_PTR* count, DWORD* granularity, bool dropZero = false) { const auto capacity = *count; const auto result = GetWriteWatch(flags, address, bytes, pages, count, granularity); if (result != 0 || zeroPages.empty()) return result; const auto first = reinterpret_cast(address) & ~std::uintptr_t{4095}; const auto last = (reinterpret_cast(address) + bytes + 4095) & ~std::uintptr_t{4095}; const bool complete = dropZero && (*count < capacity || capacity >= (last - first) / 4096); ULONG_PTR kept = 0; for (ULONG_PTR index = 0; index < *count; ++index) { const auto page = reinterpret_cast(pages[index]) & ~std::uintptr_t{4095}; if (complete && stillZero(page)) continue; forgetZero(page, page + 4096); pages[kept++] = pages[index]; } *count = kept; return result; } void harvestZero(std::uintptr_t start, std::uintptr_t end) { start &= ~std::uintptr_t{4095}; end = (end + 4095) & ~std::uintptr_t{4095}; if (!anyZero(start, end)) return; std::vector written((end - start) / 4096); ULONG_PTR reported = written.size(); DWORD granularity = 0; if (watchWrites(0, reinterpret_cast(start), end - start, written.data(), &reported, &granularity, true) != 0 || reported == written.size()) forgetZero(start, end); } bool resetWrites(std::uintptr_t start, std::uintptr_t end) { if (!anyZero(start, end)) return ResetWriteWatch(reinterpret_cast(start), end - start) == 0; std::vector written(((end + 4095) & ~std::uintptr_t{4095}) / 4096 - (start & ~std::uintptr_t{4095}) / 4096); ULONG_PTR reported = written.size(); DWORD granularity = 0; if (watchWrites(WRITE_WATCH_FLAG_RESET, reinterpret_cast(start), end - start, written.data(), &reported, &granularity, true) != 0) { forgetZero(start, end); return false; } return true; } std::uintptr_t zeroSpanEnd(std::uintptr_t at) { const auto run = residentRuns.upper_bound(at); if (run != residentRuns.begin() && std::prev(run)->second.end > at) { const auto& resident = std::prev(run)->second; return resident.watched && !resident.imported ? resident.end : 0; } if (views.find(at & ~(pageBytes - 1)) != views.end()) return 0; return privateAllocationEnd(at); } UINT collectOwnedWrites(DWORD flags, void* address, std::size_t bytes, void** pages, ULONG_PTR* count, DWORD* granularity) { const auto capacity = *count; const auto result = watchWrites(flags, address, bytes, pages, count, granularity); if (result != 0 || ownedPending.empty()) return result; std::sort(pages, pages + *count); const auto reported = *count; const auto first = reinterpret_cast(address); const auto end = first + bytes; for (auto it = ownedPending.lower_bound(first & ~(ownedBlockBytes - 1)); it != ownedPending.end() && it->first < end; ++it) { for (unsigned bit = 0; bit < ownedBlockBytes / 4096; ++bit) { const auto page = it->first + bit * 4096; if ((it->second & (std::uint16_t{1} << bit)) == 0 || page >= end || page + 4096 <= first) continue; auto* pointer = reinterpret_cast(page); if (!std::binary_search(pages, pages + reported, pointer)) { if (*count == capacity) throw std::runtime_error("owned write collection exceeds its page buffer"); pages[(*count)++] = pointer; } } } std::sort(pages, pages + *count); if ((flags & WRITE_WATCH_FLAG_RESET) != 0) forgetOwnedPending(first, end); return result; } void updateResidentNoAccess(std::uintptr_t start, std::uintptr_t end, DWORD protection) { if (end <= start) return; auto run = residentRuns.upper_bound(start); if (run != residentRuns.begin() && std::prev(run)->second.end > start) --run; for (; run != residentRuns.end() && run->first < end; ++run) { if (protection == PAGE_NOACCESS) { run->second.hasNoAccess = true; } else if (run->second.hasNoAccess) { if (start <= run->first && end >= run->second.end) { run->second.hasNoAccess = false; } else { bool anyNoAccess = false; for (auto it = views.lower_bound(run->first); it != views.end() && it->first < run->second.end; ++it) { if (it->second.protection == PAGE_NOACCESS) { anyNoAccess = true; break; } } run->second.hasNoAccess = anyNoAccess; } } } } bool collectable(std::uintptr_t address, std::uintptr_t end) { const auto proven = collectableRanges.upper_bound(address); if (proven != collectableRanges.begin() && std::prev(proven)->second >= end) return true; auto resIt = residentRuns.upper_bound(address); if (resIt != residentRuns.begin() && std::prev(resIt)->second.end > address) --resIt; bool viewsReady = false; Views::iterator position = views.end(); for (auto cursor = address; cursor < end;) { while (resIt != residentRuns.end() && resIt->second.end <= cursor) ++resIt; if (resIt != residentRuns.end() && resIt->first <= cursor && !resIt->second.hasNoAccess) { if (!watchResident) return false; cursor = std::min(end, resIt->second.end); continue; } const auto base = cursor & ~(pageBytes - 1); if (!viewsReady) { position = views.lower_bound(base); viewsReady = true; } if (const auto found = viewAt(base, position); found != views.end()) { if (found->second.protection == PAGE_NOACCESS || (found->second.resident ? !watchResident : found->second.page->comparedWhenShared)) return false; cursor = std::min(end, base + pageBytes); continue; } const auto allocationEnd = privateAllocationEnd(cursor); if (allocationEnd == 0) return false; cursor = std::min(end, allocationEnd); } remember(collectableRanges, address, end); return true; } static bool verifyDirect() { static const bool verify = std::getenv("APS5_VERIFY_DIRECT_COLLECT") != nullptr; return verify; } static bool committedPrivate(std::uintptr_t address, std::uintptr_t end) { for (auto cursor = address; cursor < end;) { const auto memory = query(cursor); if (memory.State != MEM_COMMIT || memory.Type != MEM_PRIVATE) return false; cursor = reinterpret_cast(memory.BaseAddress) + memory.RegionSize; } return true; } [[noreturn]] static void staleProof(std::uintptr_t address, std::uintptr_t end) { char text[192]; std::snprintf(text, sizeof(text), "a private collect of guest writes succeeded over 0x%llx+0x%llx, which is no longer committed private memory (APS5_VERIFY_DIRECT_COLLECT)", static_cast(address), static_cast(end - address)); throw std::runtime_error(text); } std::uintptr_t privateAllocationEnd(std::uintptr_t address) const { const auto next = privateAllocations.upper_bound(address); if (next == privateAllocations.begin()) return 0; const auto allocation = std::prev(next); return address < allocation->second ? allocation->second : 0; } static constexpr std::size_t pageBytes = 0x4000; static constexpr std::size_t subpageBytes = 0x1000; static_assert(subpageBytes == 4096, "Collect reports one page per subpage"); static constexpr std::size_t subpages = pageBytes / subpageBytes; static constexpr std::uint8_t allSubpages = (1u << subpages) - 1; static constexpr std::size_t chunkBytes = 0x200000; struct SharedPage { std::array generation = [] { std::array initial{}; initial.fill(1); return initial; }(); std::vector aliases; std::uint32_t pins = 0; bool comparedWhenShared = false; }; struct Section { HANDLE handle; explicit Section(HANDLE handle) : handle(handle) {} Section(const Section&) = delete; Section& operator=(const Section&) = delete; ~Section() { CloseHandle(handle); } }; struct Saved { unsigned char* bytes = nullptr; std::size_t length; std::array committed{}; explicit Saved(std::size_t length) : length(length) { bytes = static_cast(VirtualAlloc(nullptr, length, MEM_RESERVE, PAGE_READWRITE)); if (bytes == nullptr) fail("reserve unmapped direct memory"); } Saved(const Saved&) = delete; Saved& operator=(const Saved&) = delete; ~Saved() { VirtualFree(bytes, 0, MEM_RELEASE); } void Commit(std::size_t offset) { const auto page = offset / pageBytes; const auto bit = std::uint64_t{1} << (page & 63); if ((committed[page >> 6] & bit) != 0) return; if (!VirtualAlloc(bytes + offset, pageBytes, MEM_COMMIT, PAGE_READWRITE)) fail("keep unmapped direct memory"); committed[page >> 6] |= bit; } }; struct Physical { std::weak_ptr page; bool stored = false; bool comparedWhenShared = false; std::shared_ptr saved; std::size_t savedOffset = 0; }; struct View { std::shared_ptr page; DWORD protection; std::array seen; std::uint8_t armed; bool comparedWhenShared = false; std::uint32_t pins = 0; std::shared_ptr
section; std::uint64_t offset; std::uint32_t hostWrites; std::uint8_t collected = 0; bool resident = false; std::shared_ptr slot; std::size_t viewBytes = pageBytes; std::uint32_t hostImports = 0; bool aliasDemoted = false; std::uint8_t unreported = 0; }; struct Run { std::uintptr_t end; std::array collected; std::uint32_t fresh; std::uintptr_t key; std::uint64_t offset; bool watched = false; bool reset = false; bool imported = false; bool hasNoAccess = false; }; struct Window { void* view = nullptr; unsigned char* bytes = nullptr; }; using Ranges = std::map; static bool runCollected(const Run& run, std::size_t bit) { return (run.collected[bit >> 6] >> (bit & 63) & 1) != 0; } void collectResident(std::uintptr_t start, Run& run, std::uintptr_t from, std::uintptr_t stop, void** pages, std::size_t* count, bool clear, Collection collection) { if (clear) run.reset = true; const auto first = from & ~std::uintptr_t{4095}; if (run.fresh == 0) { if (collection == Collection::Fresh) return; ULONG_PTR reported = (stop - first + 4095) / 4096; DWORD granularity = 0; if (collectOwnedWrites(clear ? WRITE_WATCH_FLAG_RESET : 0, reinterpret_cast(first), stop - first, pages + *count, &reported, &granularity) != 0) fail("collect resident guest writes"); if (from != first) { for (ULONG_PTR index = 0; index < reported; ++index) pages[*count + index] = reinterpret_cast(std::max(from, reinterpret_cast(pages[*count + index]))); } *count += reported; return; } std::vector written; if (collection != Collection::Fresh) { std::vector found((stop - first + 4095) / 4096); ULONG_PTR reported = found.size(); DWORD granularity = 0; if (collectOwnedWrites(clear ? WRITE_WATCH_FLAG_RESET : 0, reinterpret_cast(first), stop - first, found.data(), &reported, &granularity) != 0) fail("collect resident guest writes"); for (ULONG_PTR index = 0; index < reported; ++index) written.push_back(reinterpret_cast(found[index])); } auto next = written.begin(); std::uintptr_t resetFrom = 0; const auto flushReset = [&](std::uintptr_t to) { if (resetFrom != 0) forgetOwnedPending(resetFrom, to); if (resetFrom != 0 && !resetWrites(resetFrom, to)) fail("reset resident guest writes"); resetFrom = 0; }; for (auto at = first; at < stop; at += 4096) { const auto bit = (at - start) >> 12; const bool fresh = !runCollected(run, bit); bool wrote = false; while (next != written.end() && *next < at) ++next; if (next != written.end() && *next == at) wrote = true; const bool report = collection == Collection::Fresh ? fresh : collection == Collection::Armed ? !fresh && wrote : fresh || wrote; if (report) pages[(*count)++] = reinterpret_cast(std::max(at, from)); const bool settle = clear && fresh && collection != Collection::Armed; if (settle) { run.collected[bit >> 6] |= 1ull << (bit & 63); --run.fresh; forget(freshRanges, at, at + 4096); if (collection == Collection::Fresh && resetFrom == 0) resetFrom = at; } else if (collection == Collection::Fresh) { flushReset(at); } } if (collection == Collection::Fresh) flushReset(stop); } Window open(HANDLE section, std::uint64_t offset, std::size_t bytes) { const auto lead = offset % granularity; Window window; window.view = map(section, GetCurrentProcess(), nullptr, offset - lead, lead + bytes, 0, PAGE_READWRITE, nullptr, 0); if (window.view == nullptr) fail("open a window on direct memory"); window.bytes = static_cast(window.view) + lead; return window; } void close(Window& window) { if (window.view != nullptr && !unmap(GetCurrentProcess(), window.view, 0)) fail("close a window on direct memory"); window = {}; } void commitResident(std::uintptr_t base, std::size_t bytes) { const DWORD flags = MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER | (watchResident ? MEM_WRITE_WATCH : 0); if (!allocate(GetCurrentProcess(), reinterpret_cast(base), bytes, flags, PAGE_READWRITE, nullptr, 0)) fail("replace guest placeholder with resident direct memory"); if (watchResident) markZero(base, base + bytes); } static std::size_t hostPages(std::size_t bytes) { return (bytes + subpageBytes - 1) & ~(subpageBytes - 1); } void commitSection(HANDLE section, std::uint64_t offset, std::size_t bytes) { auto window = open(section, offset, bytes); const auto memory = query(reinterpret_cast(window.bytes)); if ((memory.State != MEM_COMMIT || memory.RegionSize < bytes) && !VirtualAlloc(window.bytes, bytes, MEM_COMMIT, PAGE_READWRITE)) { const auto error = GetLastError(); close(window); throw std::system_error(static_cast(error), std::system_category(), "commit direct memory pages"); } close(window); } void mapShared(std::uintptr_t base, HANDLE section, std::uint64_t offset, DWORD protection, DWORD viewProtection = PAGE_EXECUTE_READWRITE, std::size_t sectionBytes = pageBytes, bool committed = false) { void* page = reinterpret_cast(base); const auto viewBytes = hostPages(sectionBytes); if (viewBytes != pageBytes) split(base, viewBytes); if (!map(section, GetCurrentProcess(), page, offset, sectionBytes, MEM_REPLACE_PLACEHOLDER, viewProtection, nullptr, 0)) fail("map shared guest page"); if (!committed && query(base).State == MEM_RESERVE && !VirtualAlloc(page, viewBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE)) fail("commit shared guest page"); DWORD previous; if (!VirtualProtect(page, viewBytes, protection, &previous)) fail("protect shared guest page"); if (viewBytes == pageBytes) return; void* zeros = reinterpret_cast(base + viewBytes); if (!allocate(GetCurrentProcess(), zeros, pageBytes - viewBytes, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) fail("replace guest placeholder past the end of a file with zero pages"); if (!VirtualProtect(zeros, pageBytes - viewBytes, protection, &previous)) fail("protect guest pages past the end of a file"); } void mapRun(std::uintptr_t base, std::size_t bytes, HANDLE section, std::uint64_t offset) { if (!map(section, GetCurrentProcess(), reinterpret_cast(base), offset, bytes, MEM_REPLACE_PLACEHOLDER, PAGE_EXECUTE_READWRITE, nullptr, 0)) fail("map a run of shared guest pages"); } void breakView(std::uintptr_t at) { const auto memory = query(at); if (memory.State == MEM_FREE || memory.Type != MEM_MAPPED) return; const auto start = reinterpret_cast(memory.AllocationBase); if (start == at) return; const auto first = views.find(start); if (first == views.end()) return; struct Part { std::uintptr_t base; std::uintptr_t end; DWORD protection; bool committed; }; std::vector parts; auto stop = start; for (;;) { const auto part = query(stop); if (part.AllocationBase != memory.AllocationBase) break; const auto partEnd = reinterpret_cast(part.BaseAddress) + part.RegionSize; parts.push_back({stop, partEnd, part.Protect, part.State == MEM_COMMIT}); stop = partEnd; } const auto section = first->second.section; const auto offset = first->second.offset; std::vector saved; for (auto it = views.lower_bound(start); it != views.end() && it->first < stop; ++it) { for (std::size_t sub = 0; sub < subpages; ++sub) { const auto* bytes = reinterpret_cast(it->first + sub * subpageBytes); if ((it->second.armed & (1u << sub)) != 0) saved.insert(saved.end(), bytes, bytes + subpageBytes); } } if (!unmap(GetCurrentProcess(), reinterpret_cast(start), MEM_PRESERVE_PLACEHOLDER)) fail("unmap a run of shared guest pages to split it"); split(start, at - start); mapRun(start, at - start, section->handle, offset); mapRun(at, stop - at, section->handle, offset + (at - start)); for (const auto& part : parts) { if (!part.committed) continue; for (const auto [from, to] : {std::pair{part.base, std::min(part.end, at)}, std::pair{std::max(part.base, at), part.end}}) { DWORD previous; if (from < to && !VirtualProtect(reinterpret_cast(from), to - from, part.protection, &previous)) fail("protect a split run of shared guest pages"); } } const auto* before = saved.data(); for (auto it = views.lower_bound(start); it != views.end() && it->first < stop; ++it) { std::uint8_t written = 0; for (std::size_t sub = 0; sub < subpages; ++sub) { if ((it->second.armed & (1u << sub)) == 0) continue; if (std::memcmp(reinterpret_cast(it->first + sub * subpageBytes), before, subpageBytes) != 0) written |= static_cast(1u << sub); before += subpageBytes; } if (written != 0) invalidate(*it->second.page, written); } } static bool blank(std::uintptr_t page) { const auto* words = reinterpret_cast(page); for (std::size_t i = 0; i < pageBytes / sizeof(std::uint64_t); ++i) { if (words[i] != 0) return false; } return true; } std::map::iterator residentRun(std::uintptr_t key, std::uint64_t offset) { const auto next = residentIndex.upper_bound(std::make_pair(key, offset)); if (next == residentIndex.begin()) return residentRuns.end(); const auto& [first, run] = *std::prev(next); return first.first == key && offset - first.second < run->second.end - run->first ? run : residentRuns.end(); } std::map, std::map::iterator>::iterator indexEntry(std::map::iterator run) { const auto found = residentIndex.find(std::make_pair(run->second.key, run->second.offset)); return found != residentIndex.end() && found->second == run ? found : residentIndex.end(); } void demote(std::uintptr_t address, bool alias = false) { const auto run = std::prev(residentRuns.upper_bound(address)); const auto start = run->first; const auto stop = run->second.end; disown(start, stop); forgetOwnedPending(start, stop); forgetZero(start, stop); const auto entry = indexEntry(run); const bool indexed = entry != residentIndex.end(); std::vector, std::shared_ptr>> created; created.reserve((stop - start) / pageBytes); std::map, std::shared_ptr> staged; for (auto page = start; page < stop; page += pageBytes) { const auto& view = views.at(page); auto shared = std::make_shared(); shared->aliases.push_back(page); shared->pins = view.pins; shared->comparedWhenShared = view.comparedWhenShared; auto slot = std::make_shared(); slot->page = shared; slot->comparedWhenShared = view.comparedWhenShared; if (indexed) staged.emplace(std::make_pair(run->second.key, view.offset), slot); created.emplace_back(std::move(shared), std::move(slot)); } DWORD previous; if (!VirtualProtect(reinterpret_cast(start), stop - start, PAGE_READONLY, &previous)) fail("fence resident guest pages"); const auto section = views.at(start).section; auto window = open(section->handle, views.at(start).offset, stop - start); if (query(reinterpret_cast(window.bytes)).State == MEM_RESERVE && !VirtualAlloc(window.bytes, stop - start, MEM_COMMIT, PAGE_READWRITE)) fail("commit direct memory pages"); std::memcpy(window.bytes, reinterpret_cast(start), stop - start); close(window); if (!VirtualFree(reinterpret_cast(start), stop - start, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("release resident guest pages"); physical.merge(staged); for (auto& [key, slot] : staged) physical.find(key)->second = std::move(slot); for (auto page = start; page < stop; page += pageBytes) { auto& view = views.at(page); split(page, pageBytes); mapShared(page, view.section->handle, view.offset, view.protection); auto& [shared, slot] = created[(page - start) / pageBytes]; view.page = std::move(shared); view.slot = std::move(slot); view.slot->stored = true; view.resident = false; view.aliasDemoted = alias; view.unreported = view.page->comparedWhenShared ? allSubpages : std::uint8_t{0}; view.seen.fill(0); view.armed = 0; view.collected = 0; for (std::size_t sub = 0; sub < subpages; ++sub) { if (runCollected(run->second, ((page - start) >> 12) + sub)) view.collected |= static_cast(1u << sub); } invalidate(*view.page); } if (indexed) residentIndex.erase(entry); residentRuns.erase(run); } void breakRun(std::uintptr_t at) { const auto next = residentRuns.upper_bound(at); if (next == residentRuns.begin()) return; const auto run = std::prev(next); if (at > run->first && at < run->second.end) demote(at); } void evict(std::map::iterator run) { const auto start = run->first; const auto stop = run->second.end; disown(start, stop); forgetOwnedPending(start, stop); forgetZero(start, stop); DWORD previous; if (!VirtualProtect(reinterpret_cast(start), stop - start, PAGE_READONLY, &previous)) fail("open resident guest pages"); const auto entry = indexEntry(run); const bool indexed = entry != residentIndex.end(); std::vector dirty; std::vector touched; bool filtered = false; if (indexed && run->second.watched && !run->second.reset && !run->second.imported) { dirty.resize((stop - start) / subpageBytes); ULONG_PTR reported = dirty.size(); DWORD granularity = 0; if (watchWrites(0, reinterpret_cast(start), stop - start, dirty.data(), &reported, &granularity) == 0) { touched = TouchedPages(start, (stop - start) / pageBytes, dirty.data(), reported); filtered = true; } } std::shared_ptr saved; for (auto page = start; page < stop; page += pageBytes) { const auto found = views.find(page); const auto& view = found->second; const bool written = indexed && (!filtered || touched[(page - start) / pageBytes]) && !blank(page); if (written || (indexed && view.comparedWhenShared)) { auto& slot = physical[std::make_pair(run->second.key, view.offset)]; if (!slot) slot = std::make_shared(); slot->comparedWhenShared = view.comparedWhenShared; if (written) { if (!saved) saved = savedMemory(stop - start); saved->Commit(page - start); std::memcpy(saved->bytes + (page - start), reinterpret_cast(page), pageBytes); slot->saved = saved; slot->savedOffset = page - start; } } views.erase(found); } if (indexed) residentIndex.erase(entry); forget(freshRanges, start, stop); residentRuns.erase(run); } std::shared_ptr savedMemory(std::size_t bytes) { for (const auto& saved : savedPool) { if (saved.use_count() == 1 && saved->length == bytes) return saved; } constexpr std::size_t limit = 32u * 1024u * 1024u; const auto reserved = (bytes + granularity - 1) / granularity * granularity; for (auto it = savedPool.begin(); reserved <= limit && savedPoolBytes > limit - reserved && it != savedPool.end();) { if (it->use_count() != 1) { ++it; continue; } savedPoolBytes -= ((*it)->length + granularity - 1) / granularity * granularity; it = savedPool.erase(it); } auto saved = std::make_shared(bytes); if (reserved <= limit && savedPoolBytes <= limit - reserved) { savedPool.push_back(saved); savedPoolBytes += reserved; } return saved; } static void forget(Ranges& ranges, std::uintptr_t start, std::uintptr_t end) { auto it = ranges.lower_bound(start); if (it != ranges.begin() && std::prev(it)->second > start) --it; while (it != ranges.end() && it->first < end) { const auto first = it->first; const auto last = it->second; it = ranges.erase(it); if (first < start) ranges.emplace(first, start); if (last > end) it = ranges.emplace(end, last).first; } } static void remember(Ranges& ranges, std::uintptr_t start, std::uintptr_t end) { auto it = ranges.lower_bound(start); if (it != ranges.begin() && std::prev(it)->second >= start) --it; while (it != ranges.end() && it->first <= end) { start = std::min(start, it->first); end = std::max(end, it->second); it = ranges.erase(it); } ranges.emplace(start, end); } void forgetClean(std::uintptr_t start, std::uintptr_t end) { forget(cleanRanges, start, end); } void rememberClean(std::uintptr_t start, std::uintptr_t end) { remember(cleanRanges, start, end); } void invalidate(SharedPage& page, std::uint8_t mask = allSubpages) { for (std::size_t sub = 0; sub < subpages; ++sub) { if ((mask & (1u << sub)) == 0) continue; ++page.generation[sub]; for (const auto alias : page.aliases) forgetClean(alias + sub * subpageBytes, alias + (sub + 1) * subpageBytes); } } void invalidate(std::uintptr_t base, const View& view, std::uint8_t mask = allSubpages) { if (view.page) { invalidate(*view.page, mask); return; } for (std::size_t sub = 0; sub < subpages; ++sub) { if ((mask & (1u << sub)) != 0) forgetClean(base + sub * subpageBytes, base + (sub + 1) * subpageBytes); } } static std::uint8_t subpagesOf(std::uintptr_t base, std::uintptr_t address, std::uintptr_t end) { const auto from = std::max(address, base); const auto to = std::min(end, base + pageBytes); if (to <= from) return 0; const auto first = (from - base) / subpageBytes; const auto last = (to - 1 - base) / subpageBytes; return static_cast(((1u << (last + 1)) - 1) & ~((1u << first) - 1)); } static void protectSubpages(std::uintptr_t base, std::uint8_t mask, DWORD protection, const char* operation, std::size_t viewBytes = pageBytes) { for (std::size_t sub = 0; sub < subpages;) { if ((mask & (1u << sub)) == 0) { ++sub; continue; } auto stop = sub + 1; while (stop < subpages && (mask & (1u << stop)) != 0 && stop * subpageBytes != viewBytes) ++stop; DWORD previous; if (!VirtualProtect(reinterpret_cast(base + sub * subpageBytes), (stop - sub) * subpageBytes, protection, &previous)) fail(operation); sub = stop; } } bool sameSection(HANDLE first, HANDLE second) const { return compare != nullptr && compare(first, second); } static bool writable(DWORD protection) { return protection == PAGE_READWRITE || protection == PAGE_EXECUTE_READWRITE; } using AllocateFunction = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); using MapFunction = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); using UnmapFunction = BOOL (WINAPI*)(HANDLE, PVOID, ULONG); using CompareFunction = BOOL (WINAPI*)(HANDLE, HANDLE); WindowsMappings() { const auto module = GetModuleHandleW(L"KernelBase.dll"); if (!module) fail("load Windows memory API"); allocate = reinterpret_cast(GetProcAddress(module, "VirtualAlloc2")); map = reinterpret_cast(GetProcAddress(module, "MapViewOfFile3")); unmap = reinterpret_cast(GetProcAddress(module, "UnmapViewOfFile2")); if (!allocate || !map || !unmap) throw std::runtime_error("Windows placeholder memory APIs are required"); compare = reinterpret_cast(GetProcAddress(module, "CompareObjectHandles")); SYSTEM_INFO system{}; GetSystemInfo(&system); granularity = system.dwAllocationGranularity; } [[noreturn]] static void fail(const char* operation) { throw std::system_error(static_cast(GetLastError()), std::system_category(), operation); } static MEMORY_BASIC_INFORMATION query(std::uintptr_t address) { MEMORY_BASIC_INFORMATION memory{}; #ifdef APS5_COUNT_MAPPING_QUERIES queries.fetch_add(1, std::memory_order_relaxed); #endif if (VirtualQuery(reinterpret_cast(address), &memory, sizeof(memory)) != sizeof(memory)) fail("query guest memory"); return memory; } static std::uintptr_t split(std::uintptr_t address, std::size_t bytes) { auto memory = query(address); memory = query(reinterpret_cast(memory.AllocationBase)); if (memory.State != MEM_RESERVE) throw std::runtime_error("guest mapping requires a placeholder"); const auto base = reinterpret_cast(memory.BaseAddress); if (address != base) { if (!VirtualFree(reinterpret_cast(base), address - base, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("split guest placeholder prefix"); memory = query(address); } if (memory.RegionSize < bytes) throw std::runtime_error("guest placeholder is too small"); if (memory.RegionSize != bytes && !VirtualFree(reinterpret_cast(address), bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("split guest placeholder suffix"); return address + memory.RegionSize; } void reset(std::uintptr_t address, std::size_t bytes) { disown(address, address + bytes); forgetOwnedPending(address, address + bytes); forgetZero(address, address + bytes); collectableRanges.clear(); const auto end = address + bytes; privateAllocations.erase(privateAllocations.lower_bound(address), privateAllocations.lower_bound(end)); forgetClean(address, end); breakRun(address); breakRun(end); breakView(address); breakView(end); if (const auto run = residentRuns.find(address); run != residentRuns.end() && run->second.end == end) { const auto memory = query(address); if (reinterpret_cast(memory.AllocationBase) != address) throw std::runtime_error("cannot release part of a host allocation"); if (memory.Type != MEM_PRIVATE) throw std::runtime_error("resident guest mapping is not private memory"); auto allocationEnd = address; do { const auto part = query(allocationEnd); if (part.AllocationBase != memory.AllocationBase) break; allocationEnd = reinterpret_cast(part.BaseAddress) + part.RegionSize; } while (allocationEnd < end); if (allocationEnd != end || query(end).AllocationBase == memory.AllocationBase) throw std::runtime_error("guest release truncates a host allocation"); evict(run); if (!VirtualFree(reinterpret_cast(address), bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("release private guest memory"); return; } for (auto cursor = address; cursor < end;) { const auto memory = query(cursor); if (memory.State == MEM_RESERVE) { cursor = std::min(end, reinterpret_cast(memory.BaseAddress) + memory.RegionSize); continue; } if (reinterpret_cast(memory.AllocationBase) != cursor) throw std::runtime_error("cannot release part of a host allocation"); auto allocationEnd = cursor; do { const auto part = query(allocationEnd); if (part.AllocationBase != memory.AllocationBase) break; allocationEnd = reinterpret_cast(part.BaseAddress) + part.RegionSize; } while (allocationEnd < end); if (allocationEnd > end || query(allocationEnd).AllocationBase == memory.AllocationBase) throw std::runtime_error("guest release truncates a host allocation"); if (memory.Type == MEM_MAPPED) { if (!unmap(GetCurrentProcess(), reinterpret_cast(cursor), MEM_PRESERVE_PLACEHOLDER)) fail("unmap shared guest page"); for (auto found = views.lower_bound(cursor); found != views.end() && found->first < allocationEnd;) { if (found->second.page != nullptr) std::erase(found->second.page->aliases, found->first); found = views.erase(found); } forget(freshRanges, cursor, allocationEnd); } else if (memory.Type == MEM_PRIVATE) { if (const auto run = residentRuns.find(cursor); run != residentRuns.end()) evict(run); if (!VirtualFree(reinterpret_cast(cursor), allocationEnd - cursor, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) fail("release private guest memory"); } else { throw std::runtime_error("unsupported guest mapping type"); } cursor = allocationEnd; } const auto last = query(reinterpret_cast(query(end - 1).AllocationBase)); const auto lastBase = reinterpret_cast(last.BaseAddress); if (lastBase + last.RegionSize > end) split(lastBase, end - lastBase); const auto first = query(address); split(address, std::min(bytes, reinterpret_cast(first.BaseAddress) + first.RegionSize - address)); if (query(address).RegionSize != bytes && !VirtualFree(reinterpret_cast(address), bytes, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) fail("coalesce guest placeholders"); } void* mapAliasRuns(std::uintptr_t address, std::size_t bytes) { auto* reserved = allocate(GetCurrentProcess(), nullptr, bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0); if (reserved == nullptr) fail("reserve a read-write alias of shared guest memory"); const auto base = reinterpret_cast(reserved); try { for (std::size_t done = 0; done < bytes;) { const auto& first = views.at(address + done); auto run = pageBytes; while (done + run < bytes) { const auto& next = views.at(address + done + run); if (next.offset != first.offset + run || (next.section != first.section && !sameSection(next.section->handle, first.section->handle))) break; run += pageBytes; } split(base + done, run); if (!map(first.section->handle, GetCurrentProcess(), reinterpret_cast(base + done), first.offset, run, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) fail("map a run of a read-write alias of shared guest memory"); done += run; } } catch (...) { releaseAlias(base, bytes); throw; } splitAliases.emplace(base, bytes); return reserved; } DWORD releaseAlias(std::uintptr_t base, std::size_t bytes) { DWORD error = ERROR_SUCCESS; for (auto cursor = base; cursor < base + bytes;) { const auto memory = query(cursor); const auto released = memory.State == MEM_RESERVE ? VirtualFree(memory.BaseAddress, 0, MEM_RELEASE) : unmap(GetCurrentProcess(), memory.BaseAddress, 0); if (!released && error == ERROR_SUCCESS) error = GetLastError(); cursor = reinterpret_cast(memory.BaseAddress) + memory.RegionSize; } return error; } std::map ownedWords; std::map ownedPending; OwnedRanges ownedPins; OwnedRanges ownedHostAccess; OwnedRanges ownedHostStores; std::uint64_t nextOwned = 1; Ranges cleanRanges; Ranges collectableRanges; Ranges privateAllocations; #ifdef APS5_COUNT_MAPPING_QUERIES std::uint64_t collectSystemCalls = 0; std::uint64_t collectPieces = 0; #endif Ranges freshRanges; std::unordered_map> zeroPages; std::atomic zeroMarks{0}; std::map views; using Views = std::map; Views::iterator viewAt(std::uintptr_t base, Views::iterator& position) { if (position != views.end() && position->first < base) { ++position; if (position != views.end() && position->first < base) position = views.lower_bound(base); } return position != views.end() && position->first == base ? position : views.end(); } std::map, std::shared_ptr> physical; std::map residentRuns; std::map, std::map::iterator> residentIndex; std::vector> savedPool; std::size_t savedPoolBytes = 0; std::map splitAliases; std::size_t granularity = 0x10000; bool watchResident = false; #ifdef APS5_COUNT_MAPPING_QUERIES static inline std::atomic queries{0}; #endif Lock mutex; HANDLE zeroSection = nullptr; AllocateFunction allocate = nullptr; MapFunction map = nullptr; UnmapFunction unmap = nullptr; CompareFunction compare = nullptr; }; } #endif #endif