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
382 changes: 362 additions & 20 deletions CMakeLists.txt

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions src/era_heap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#define NOMINMAX
#endif
#include <windows.h>
#include "xmem_low.h"

namespace era_heap {
namespace {
Expand Down Expand Up @@ -52,7 +53,7 @@ void* allocate_pages(std::size_t bytes, std::size_t alignment) noexcept
const auto page = geometry().page;
const auto committed = (bytes + page - 1) & ~(page - 1);
for (int attempt = 0; attempt < 8; ++attempt) {
auto* probe = VirtualAlloc(nullptr, committed + alignment, MEM_RESERVE, PAGE_NOACCESS);
auto* probe = x2w_low::alloc(committed + alignment, MEM_RESERVE, PAGE_NOACCESS);
if (!probe) {
return nullptr;
}
Expand Down Expand Up @@ -117,7 +118,7 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept
return nullptr;
}
// Committed pages are zero-filled by the system.
return VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
return x2w_low::alloc(bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
}

// Physical memory types need title physical pages, which this experiment does not model.
Expand Down
7 changes: 6 additions & 1 deletion src/era_query.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,12 @@ std::size_t query(void* process, const void* address, void* buffer, std::size_t
// Desktop policy, not a Scarlett field: mark addresses in registered GPU-intended regions.
const bool registered = is_current_process(process) &&
is_registered(reinterpret_cast<std::uintptr_t>(address));
static_cast<unsigned char*>(buffer)[tail_offset] = registered ? tail_registered : 0;
static const bool readable_policy = GetEnvironmentVariableA("X2W_XMEM_QUERY_READABLE", nullptr, 0) != 0;
const DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
const bool cpu_readable = readable_policy && info.State == MEM_COMMIT && (info.Protect & readable) &&
!(info.Protect & (PAGE_GUARD | PAGE_NOACCESS));
static_cast<unsigned char*>(buffer)[tail_offset] = registered || cpu_readable ? tail_registered : 0;
}
return sizeof(info);
}
Expand Down
318 changes: 318 additions & 0 deletions src/startup_stubs/bcpack_bc6h.h

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions src/startup_stubs/bcpack_decoder.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

namespace x2w_bcpack {

// (The BC3/BC4/BC5 rank tables and dictionaries come from bcpack_tables.h, which includes bcpack_tables_bcn.inl.)

inline void model_forward(uint8_t eab, uint8_t q, uint16_t sym, uint32_t& f, uint32_t& cf) {
uint32_t s = sym;
unsigned long seg = 0;
Expand Down Expand Up @@ -1161,6 +1163,7 @@ inline bool decode_bc1_blocks(const std::vector<uint16_t>& symbols, size_t targe
return true;
}


inline constexpr uint8_t ALPHA_CODE[8] = { 0, 2, 3, 4, 5, 6, 7, 1 };
inline constexpr uint8_t COLOUR_CODE[4] = { 0, 2, 3, 1 };

Expand Down
76 changes: 76 additions & 0 deletions src/startup_stubs/buffer_address_index.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#pragma once
#include <array>
#include <cstdint>
#include <map>
#include <unordered_map>
#include <utility>

namespace x2w_startup {

template<class Key> class BufferAddressIndex {
public:
enum class Mutation { none, exact_start }; // exact_start: the test's negative control (ignores the window)
explicit BufferAddressIndex(Mutation m = Mutation::none) : mutation_(m) {}

void insert(Key key, std::uint64_t base, std::uint64_t width)
{
erase(key);
if (!width || width > ~std::uint64_t{} - base) return;
Group& g = groups_[class_of(width)];
g.by_start.emplace(base, Entry{key, width});
if (width > g.max_width) g.max_width = width;
where_[key] = {base, width};
}
bool erase(Key key)
{
const auto found = where_.find(key);
if (found == where_.end()) return false;
const auto [base, width] = found->second;
Group& g = groups_[class_of(width)];
const auto [first, last] = g.by_start.equal_range(base);
for (auto it = first; it != last; ++it)
if (it->second.key == key) {
g.by_start.erase(it);
break;
}
where_.erase(found);
return true;
}
// visit(key, base, width) for every range that contains [address, address + bytes) (bytes >= 1); visit returns
// false to stop. Order: by class, then by start.
template<class Visit> void containing(std::uint64_t address, std::uint64_t bytes, Visit&& visit) const
{
if (!bytes || bytes > ~std::uint64_t{} - address) return;
for (const Group& g : groups_) {
if (g.by_start.empty()) continue;
const std::uint64_t earliest = mutation_ == Mutation::exact_start ? address
: address >= g.max_width ? address - g.max_width + 1 : 0;
for (auto it = g.by_start.lower_bound(earliest); it != g.by_start.end() && it->first <= address; ++it) {
const std::uint64_t base = it->first, width = it->second.width;
if (address - base >= width || bytes > width - (address - base)) continue;
if (!visit(it->second.key, base, width)) return;
}
}
}
std::size_t size() const { return where_.size(); }

private:
struct Entry {
Key key;
std::uint64_t width;
};
struct Group {
std::multimap<std::uint64_t, Entry> by_start;
std::uint64_t max_width = 0;
};
static std::size_t class_of(std::uint64_t width)
{
return width <= (std::uint64_t{1} << 16) ? 0 : width <= (std::uint64_t{1} << 20) ? 1 : width <= (std::uint64_t{1} << 24) ? 2
: width <= (std::uint64_t{1} << 28) ? 3 : 4;
}
std::array<Group, 5> groups_;
std::unordered_map<Key, std::pair<std::uint64_t, std::uint64_t>> where_;
Mutation mutation_;
};

} // namespace x2w_startup
29 changes: 12 additions & 17 deletions src/startup_stubs/chad.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,27 +47,22 @@ long release_handle(const char* name, unsigned index, u64 rcx, u64 rdx, u64 r8,
}
} // namespace

// XDspActivate(connection, parameters, &state, &handle): the caller keeps both outputs next to each
// other in its effect object and later reads the state block (+0x4 compared with its own counter,
// +0xc tested for zero). Each activation gets its own zeroed 256-byte state block and a handle.
extern "C" __declspec(noinline) long XDspActivate(u64 rcx, u64 rdx, u64 r8, u64 r9)
{
static LONG calls;
accept("XDspActivate", 0, rcx, rdx, r8, r9, _ReturnAddress(), calls);
// XDspActivate(client, params, XDspStatus** status, XDspStreamHandle* stream). No XDSP device exists
// under this stand-in, so the call fails the way the documented code says instead of returning success
// with both outputs untouched: validate them, clear them, then report the failure.
auto** status_out = reinterpret_cast<void**>(static_cast<std::uintptr_t>(r8));
auto** stream_out = reinterpret_cast<void**>(static_cast<std::uintptr_t>(r9));
if (!status_out || !x2w_local::writable(status_out, sizeof(void*)) ||
!stream_out || !x2w_local::writable(stream_out, sizeof(void*))) {
x2w_local::logf("x2w-audio XDspActivate status_out=%p stream_out=%p -> E_POINTER",
static_cast<void*>(status_out), static_cast<void*>(stream_out));
return hr_pointer;
const long result = accept("XDspActivate", 0, rcx, rdx, r8, r9, _ReturnAddress(), calls);
static unsigned char* blocks = static_cast<unsigned char*>(VirtualAlloc(nullptr, 1u << 20, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
static LONG used;
const LONG index = InterlockedIncrement(&used) - 1;
if (blocks && index < 4096) {
void* state = blocks + static_cast<std::size_t>(index) * 256;
if (r8 && x2w_local::writable(reinterpret_cast<void*>(r8), sizeof(void*))) *reinterpret_cast<void**>(r8) = state;
if (r9 && x2w_local::writable(reinterpret_cast<void*>(r9), sizeof(u64))) *reinterpret_cast<u64*>(r9) = 0x58325344ull << 32 | (index + 1);
}
*status_out = nullptr;
*stream_out = nullptr;
x2w_local::logf("x2w-audio XDspActivate status_out=%p stream_out=%p -> 0x8AC810A2 "
"(XDSP_E_NO_DEVICE_RESOURCES)",
static_cast<void*>(status_out), static_cast<void*>(stream_out));
return hr_no_device_resources;
return result;
}

extern "C" __declspec(noinline) long XDspConnectWithMaximumStreamLimit(u64 rcx, u64 rdx, u64 r8, u64 r9, u64 flag, void** handle)
Expand Down
16 changes: 16 additions & 0 deletions src/startup_stubs/d3d12_capture.inl
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,19 @@ PlacementIndex& placement_group(u64 width)
return placement_index[width > D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT];
}

x2w_startup::BufferAddressIndex<const Wrapper*>& buffer_address_index()
{
static x2w_startup::BufferAddressIndex<const Wrapper*> index;
return index;
}
void index_buffer_record(const Wrapper* w, const ResourceInfo& info) // note_lock exclusive held
{
const u64 base = reinterpret_cast<u64>(w->own().title_memory);
if (info.placement == Placement::none && info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && base)
buffer_address_index().insert(w, base, info.console.Width);
else
buffer_address_index().erase(w);
}
// Resources by the title memory they start at (note_lock held), for the memory SRV lookups. An entry stays
// as long as the resource's record in resource_infos does (never pruned); every lookup applies its own
// live-reference filter, so a released resource is skipped there and found again if it is referenced again.
Expand Down Expand Up @@ -238,6 +251,7 @@ void note_resource(Wrapper* w, const D3D12_RESOURCE_DESC* console, u64 bytes)
// Record and index change together or not at all (store_indexed); mode 2 leaves the index out.
x2w_startup::store_indexed(resource_address_index(), resource_infos(), static_cast<const Wrapper*>(w),
resource_index_check_mode() == 2 ? 0 : reinterpret_cast<u64>(w->own().title_memory), resource_index_extent(info), info);
index_buffer_record(w, resource_infos().at(w));
}
void retire_placement(Wrapper* w)
{
Expand All @@ -254,6 +268,7 @@ void retire_placement(Wrapper* w)
}
}
found->second.placement = Placement::none;
index_buffer_record(w, found->second);
}
ReleaseSRWLockExclusive(&note_lock);
}
Expand Down Expand Up @@ -309,6 +324,7 @@ void note_heap(Wrapper* w, UINT type, UINT count, UINT logical_count, UINT incre
void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_t desc_bytes, u64 dest_title, u64 dest_desktop,
bool materialized = true)
{
if (const Wrapper* r = as_wrapper(reinterpret_cast<const void*>(resource)); r && r->own().refs <= 0) x2w_memcut::note_after_release(false);
ViewRecord record{};
record.slot = static_cast<std::uint32_t>(slot);
record.resource = resource;
Expand Down
70 changes: 70 additions & 0 deletions src/startup_stubs/d3d12_cold_texture.inl
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Residency hints only. The committed object and its descriptors keep their normal lifetime.
// A title that samples a persistent descriptor without a shim call can still use a low-priority texture.
enum { priority_untracked, priority_normal, priority_low };
SRWLOCK cold_texture_lock = SRWLOCK_INIT;
unsigned long long cold_texture_count, cold_texture_bytes, warmed_texture_count, warmed_texture_bytes, cold_texture_failures;

bool cold_textures_enabled()
{
static const bool on = x2w_local::env_on("X2W_D3D12_COLD_TEXTURE_PRIORITY") &&
!x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED") && !x2w_local::env_on("X2W_MEMCUT_RELEASE");
return on;
}

void update_texture_priority(Wrapper* wrapper, bool cool)
{
AcquireSRWLockExclusive(&cold_texture_lock);
auto& w = wrapper->own();
const LONG previous = cool ? priority_normal : priority_low;
const LONG state = ReadNoFence(&w.cold_texture_state);
if (!cool && state == priority_normal) {
// A bind at zero guest refs, or the AddRef from zero, reached this lock before the final
// Release could lower the priority. Keep the resource warm when that Release arrives.
InterlockedExchange(&w.cold_texture_state, priority_untracked);
} else if (state == previous &&
(!cool || InterlockedCompareExchange(&w.refs, 0, 0) == 0)) {
auto* resource = static_cast<ID3D12Resource*>(w.real);
ID3D12Device1* device = nullptr;
HRESULT hr = resource->GetDevice(IID_PPV_ARGS(&device));
unsigned long long bytes = 0;
if (SUCCEEDED(hr)) {
const auto desc = resource->GetDesc();
bytes = device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes;
const auto priority = cool ? D3D12_RESIDENCY_PRIORITY_LOW : D3D12_RESIDENCY_PRIORITY_NORMAL;
ID3D12Pageable* object = resource;
hr = device->SetResidencyPriority(1, &object, &priority);
device->Release();
}
if (SUCCEEDED(hr)) {
// Keep a texture warm permanently once we see its reuse, including a bind at zero guest refs.
InterlockedExchange(&w.cold_texture_state, cool ? priority_low : priority_untracked);
if (cool) {
++cold_texture_count;
cold_texture_bytes += bytes;
} else {
++warmed_texture_count;
warmed_texture_bytes += bytes;
}
} else {
++cold_texture_failures;
if (cool) InterlockedExchange(&w.cold_texture_state, priority_untracked);
if (cold_texture_failures <= 3) log("x2w-cold texture: %s failed 0x%08lx", cool ? "lowering priority" : "restoring priority", hr);
}
}
ReleaseSRWLockExclusive(&cold_texture_lock);
}

void warm_texture(Wrapper* wrapper, bool reacquired = false)
{
if (!wrapper) return;
const auto& w = wrapper->own();
const LONG state = ReadNoFence(&w.cold_texture_state);
if (state == priority_low || (state == priority_normal && (reacquired || !ReadNoFence(&w.refs))))
update_texture_priority(wrapper, false);
}

void cool_texture(Wrapper* wrapper)
{
if (ReadNoFence(&wrapper->own().cold_texture_state) == priority_normal)
update_texture_priority(wrapper, true);
}
Loading
Loading