From 4f5cb86edf1a0e83f80f86faa4e20084ff8e8565 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 3 Dec 2026 02:43:42 +0000 Subject: [PATCH 1/2] [Memory] Hold the split arena's range from selection until its view maps it The split layout chose the guest allocator arena's address at startup (and told the GPU process) but mapped it only at the first guest allocation, so anything mapped in between (the malloc nano zone growing, dyld, a host library) could take it and leave the arena private. The chosen range is now held as a no-access reservation of the backing's owner, which the arena's view replaces; Clear holds it again at the same address. A hold that fails at selection probes again (up to 4 times) before the loud private-arena error. --- docs/macos/split-shared-memory.md | 9 ++- .../PhysicalVirtualMemory.SplitLayout.cs | 81 ++++++++++++++----- .../Memory/PhysicalVirtualMemory.cs | 12 ++- 3 files changed, 78 insertions(+), 24 deletions(-) diff --git a/docs/macos/split-shared-memory.md b/docs/macos/split-shared-memory.md index e52ff9eb..95ba905e 100644 --- a/docs/macos/split-shared-memory.md +++ b/docs/macos/split-shared-memory.md @@ -108,9 +108,12 @@ Only a backing the host made shareable (`SHARPEMU_GPU_PROCESS=1` or that address in every process started without `MallocNanoZone=0` (apps from Finder or the Dock, and shell launches unless the shell sets it), so the layout checks the address when it is selected and moves the arena to another free range if it is taken (a `[VMEM]` warning names the - new address). A sends the address to B in the split start, and B's replica covers it there. - If the arena still cannot be mapped at first use, it is private: an error line, and - `PhysicalVirtualMemory.SplitArenaMapFailures` counts it. + new address). The chosen range is held from then on (a no-access reservation, held again after + each `Clear`) until the arena's view replaces it at the first guest allocation, so nothing mapped + in between (the nano zone growing, dyld, a host library) can land there. A sends the address to B + in the split start, and B's replica covers it there. If no range could be held, or the arena still + cannot be mapped at first use, it is private: an error line, and + `PhysicalVirtualMemory.SplitArenaMapFailures` counts a map failure. - **HLE data.** `TryAllocateHleData` takes its memory from the backed arena (`IGuestMemoryAllocator.AllocatesFromBacking`). That covers AGC register-default blobs, AvPlayer frames and the VideoOut label fallback, with no mapping per allocation. The memory is zeroed as diff --git a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.SplitLayout.cs b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.SplitLayout.cs index b5dc8a87..ab175d8d 100644 --- a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.SplitLayout.cs +++ b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.SplitLayout.cs @@ -96,42 +96,84 @@ public bool AllocatesFromBacking // GuestMemoryLayout.AllocatorArenaAddress in every process started without MallocNanoZone=0 // (apps from Finder or the Dock, and a shell's children unless it sets that), and a private // arena would hide VideoOut labels and HLE data from the GPU process. Nothing guest-visible - // depends on the address: the arena is handed out only as pointers. + // depends on the address: the arena is handed out only as pointers. The chosen range is held + // (a no-access reservation the arena's view later replaces) from here on, so nothing mapped + // before the first guest allocation (the nano zone growing, dyld, a host library) can land there. private SplitBackingLayout PlaceSplitArena(SplitBackingLayout requested) { var preferred = requested.ArenaAddress; var bytes = requested.ArenaBytes; var limit = SplitBackingLayout.ArenaAddressLimit; - // The lowest free range at or above the preferred address: the address itself when it is free. - var found = _backedSpace!.FindUnmappedHostRange(preferred, bytes, Math.Max(limit, preferred + bytes)); - if (found == preferred || found == 0) + for (var attempt = 0; attempt < ArenaPlacementAttempts; attempt++) { - // Free, or the host cannot say: mapping it at first use answers (TryMapSplitArena, loud when it fails). - return requested; + // The lowest free range at or above the preferred address: the address itself when it is free. + var found = _backedSpace!.FindUnmappedHostRange(preferred, bytes, Math.Max(limit, preferred + bytes)); + var hostCannotSay = found == 0; + var candidate = found == preferred || hostCannotSay ? preferred : FindRelocatedArena(preferred, bytes, limit); + if (candidate == 0) + { + Log.Error($"Split layout: 0x{preferred:X16}+0x{bytes:X} is taken and no other free range was found below " + + $"0x{limit:X}; the guest allocator arena will be private, and the GPU process cannot see the VideoOut labels " + + "or HLE data in it."); + return requested; + } + + if (TryHoldRange(candidate, bytes)) + { + if (candidate != preferred) + { + Log.Warn($"Split layout: 0x{preferred:X16} is taken (under Rosetta the malloc nano zone sits there unless " + + $"MallocNanoZone=0); the guest allocator arena is at 0x{candidate:X16} instead, and the GPU process replicates it there."); + } + + return requested.WithArenaAddress(candidate); + } + + // Taken since the probe; the next probe sees it. A host that cannot say where mappings are has nothing else to try. + if (hostCannotSay) + { + break; + } } + Log.Error($"Split layout: no range for the guest allocator arena (0x{bytes:X} bytes, preferred 0x{preferred:X16}) " + + "could be held; mapping it at first use will be tried and is likely to fail, leaving it private, and the GPU process " + + "cannot see the VideoOut labels or HLE data in it then."); + return requested; + } + + // Probe-then-hold races with other mappings; each attempt probes again. + private const int ArenaPlacementAttempts = 4; + + // Another free range for an arena whose preferred address is taken: well above it (clear of the + // nano zone's upward growth), else below it; 0 when none is. + private ulong FindRelocatedArena(ulong preferred, ulong bytes, ulong limit) + { var relocated = 0UL; if (preferred <= ulong.MaxValue - SplitBackingLayout.ArenaRelocationGap) { relocated = FindFreeArenaRange(preferred + SplitBackingLayout.ArenaRelocationGap, bytes, limit); } - if (relocated == 0) + return relocated != 0 + ? relocated + : FindFreeArenaRange(SplitBackingLayout.ArenaAddressFloor, bytes, Math.Min(limit, preferred)); + } + + // Caller holds _gate for writing. Clear released every owned range, the arena's hold with them; + // the GPU process still expects the arena at the layout's address, so it is held again. + private void HoldSplitArenaAfterClear() + { + if (_splitLayout is not { } layout || !HasBackingOwner()) { - relocated = FindFreeArenaRange(SplitBackingLayout.ArenaAddressFloor, bytes, Math.Min(limit, preferred)); + return; } - if (relocated == 0) + if (!TryReserveBackingRange(layout.ArenaAddress, layout.ArenaBytes)) { - Log.Error($"Split layout: 0x{preferred:X16}+0x{bytes:X} is taken and no other free range was found below " + - $"0x{limit:X}; the guest allocator arena will be private, and the GPU process cannot see the VideoOut labels " + - "or HLE data in it."); - return requested; + Log.Error($"Split layout: the guest allocator arena's range 0x{layout.ArenaAddress:X16}+0x{layout.ArenaBytes:X} " + + "could not be held again after the address space was cleared; mapping it at first use may fail, leaving it private."); } - - Log.Warn($"Split layout: 0x{preferred:X16} is taken (under Rosetta the malloc nano zone sits there unless " + - $"MallocNanoZone=0); the guest allocator arena is at 0x{relocated:X16} instead, and the GPU process replicates it there."); - return requested.WithArenaAddress(relocated); } // A guest-page-aligned range of bytes with nothing mapped, in [start, limit); 0 when none is. @@ -159,8 +201,9 @@ private ulong FindFreeArenaRange(ulong start, ulong bytes, ulong limit) return 0; } - // The split layout's arena: one view of the backing at the layout's address. Caller holds - // _guestAllocationGate. False (nothing mapped) leaves the arena to the private path. + // The split layout's arena: one view of the backing at the layout's address, over the range + // PlaceSplitArena (or Clear) held. Caller holds _guestAllocationGate. False (nothing mapped) + // leaves the arena to the private path, loudly: the GPU process was told this address. private bool TryMapSplitArena(out ulong arenaBase, ref ulong arenaSize) { arenaBase = 0; diff --git a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs index 82e1bd8a..6b905c29 100644 --- a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs +++ b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs @@ -2134,7 +2134,10 @@ private static HostPageProtection ResolveProtection(GuestPageProtection protecti : HostPageProtection.NoAccess; } - public void Clear() + public void Clear() => Clear(holdSplitArena: true); + + // Dispose clears without holding the split arena again: the backing's owner goes next. + private void Clear(bool holdSplitArena) { lock (_guestAllocationGate) { @@ -2174,6 +2177,11 @@ public void Clear() if (_ownsStartupAddressReservations) _fixedGranuleReservationBases.Add(WindowsGuestAddressReservation.ImageStart); _backedSpace?.ReleaseAddressRanges(); + if (holdSplitArena) + { + HoldSplitArenaAfterClear(); + } + _regions.Clear(); _allocationGaps.Clear(); _pageProtections.Clear(); @@ -3763,7 +3771,7 @@ public void Dispose() { if (!_disposed) { - Clear(); + Clear(holdSplitArena: false); _backedSpace?.Dispose(); _backedSpace = null; if (_ownsStartupAddressReservations && !_hostMemory.Free(WindowsGuestAddressReservation.ImageStart)) From 679f6e80ea89eca1cb0afa9861f054fe7a7883a2 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 3 Dec 2026 02:43:42 +0000 Subject: [PATCH 2/2] [Tests] The split arena stays backed when its range is taken after selection --- .../GuestMemory/SplitGuestMemoryTests.cs | 41 +++++++++++++------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SplitGuestMemoryTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SplitGuestMemoryTests.cs index 2c14db78..061d9865 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SplitGuestMemoryTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/SplitGuestMemoryTests.cs @@ -250,25 +250,42 @@ public void AnArenaWhoseAddressIsTakenIsPlacedElsewhereStillBacked() } [Fact] - public void AnArenaThatCannotBeMappedAtFirstUseIsCountedAndPrivate() + public void AnArenaTakenBetweenSelectionAndFirstUseStaysBacked() { if (!_shareable) return; var host = HostViewMemory.Create(); var layout = Layout(ProbeGuestAddress(host, ArenaBytes)); using var memory = CreateMemory(host, layout); Assert.Same(layout, memory.SplitLayout); - // Taken after the layout was selected (and the GPU process told): the arena cannot move any more. - Assert.Equal(layout.ArenaAddress, host.ReserveHole(layout.ArenaAddress, ArenaBytes)); - try - { - Assert.True(memory.TryAllocateGuestMemory(0x100, 0x40, out var allocation)); - Assert.Equal(1, memory.SplitArenaMapFailures); - Assert.False(memory.AllocatesFromBacking); - Assert.False(memory.IsBackedRange(allocation, 0x100)); - } - finally + for (var load = 0; load < 2; load++) { - Assert.True(host.FreeHole(layout.ArenaAddress, ArenaBytes)); + if (load != 0) + { + // Clear (each load) releases every range; the arena's is held again at the same address. + memory.Clear(); + } + + // Something maps into the arena's range after the layout was selected (and the GPU process + // told) but before the first guest allocation, as the nano zone growing or a host library + // would: exact placement without overwriting, as mach_vm_allocate(VM_FLAGS_FIXED) does. The + // range is held from selection on, so it cannot land; before, it did and the arena went private. + var outsider = host.ReserveHole(layout.ArenaAddress, Page); + try + { + Assert.True(memory.TryAllocateGuestMemory(0x100, 0x40, out var allocation)); + Assert.Equal(0, memory.SplitArenaMapFailures); + Assert.True(memory.AllocatesFromBacking); + Assert.InRange(allocation, layout.ArenaAddress, layout.ArenaAddress + ArenaBytes - 0x100); + Assert.True(memory.IsBackedRange(layout.ArenaAddress, ArenaBytes)); + Assert.Equal(0UL, outsider); + } + finally + { + if (outsider != 0) + { + host.FreeHole(outsider, Page); + } + } } }