using System.Security.Cryptography;
using System.Text.Json;
using XFESystem.NativeKernel;
internal static unsafe class Program
{
const ulong AddressMask = 0x000ffffffffff000, Present = 1, Writable = 2, Nx = 1UL << 63, Uc = 0x18;
static int assertions;
static readonly List<object> Results = [];
static string root = "";
static int Main()
{
root = FindRoot(); string source = Path.Combine(root, "Source/XFESystem.NativeKernel/VirtualMemory.cs");
string before = Hash(source);
var harness = HarnessHashes();
string output = Path.Combine(root, "build/Gpu/DeviceMappingChecks-" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "-" + Guid.NewGuid().ToString("N")[..8]);
if (Directory.Exists(output)) throw new IOException("Refusing to overwrite prior evidence.");
Directory.CreateDirectory(output);
Run("ReadOnlyUcNxPtesAndExactUnmap", () =>
{
ulong free = PhysicalMemory.AvailablePages;
ulong address = VirtualMemory.MapDeviceReadOnly(0xC0000000, 8192);
Check(address == VirtualMemory.Base, "first virtual reservation");
Check(PhysicalMemory.AllocatedPages == 3, "only three page-table pages allocated");
Check(*Leaf(address) == (0xC0000000 | Present | Nx | Uc), "first real PTE includes RO/NX/UC");
Check(*Leaf(address + 4096) == (0xC0001000 | Present | Nx | Uc), "second PTE physical progression");
ulong first = *Leaf(address), second = *Leaf(address + 4096);
Check(!VirtualMemory.UnmapDevice(address, 4096), "partial unmap rejected");
Check(!VirtualMemory.UnmapDevice(address + 4096, 4096), "interior unmap rejected");
Check(!VirtualMemory.UnmapDevice(address, 12288), "oversized unmap rejected");
Check(!VirtualMemory.UnmapDevice(address + 1, 8192), "unaligned unmap rejected");
Check(*Leaf(address) == first && *Leaf(address + 4096) == second, "rejected unmaps preserve both PTEs");
Check(VirtualMemory.UnmapDevice(address, 8192), "exact unmap accepted");
Check(Leaf(address) == null && RootSlot() == 0, "last unmap prunes actual PTE tables");
Check(!VirtualMemory.UnmapDevice(address, 8192), "duplicate unmap rejected");
Check(PhysicalMemory.AvailablePages == free && PhysicalMemory.AllocatedPages == 0, "table pages reclaimed");
Check(PhysicalMemory.Releases.All(item => item.Released), "only owned tables released");
});
Run("MmioCannotUseRamCommitDecommitProtectOrRelease", () =>
{
ulong address = VirtualMemory.MapDevice(0xC0000000, 8192), first = *Leaf(address);
Check((first & Writable) != 0, "writable device map has RW bit");
int releases = PhysicalMemory.Releases.Count;
Check(!VirtualMemory.Commit(address, 4096), "RAM commit cannot alias MMIO");
Check(!VirtualMemory.Decommit(address, 8192), "RAM decommit cannot free MMIO");
Check(!VirtualMemory.Release(address, 8192), "RAM release cannot free MMIO");
Check(!VirtualMemory.Protect(address, 8192, 1), "RAM protect cannot change MMIO cache policy");
Check(PhysicalMemory.Releases.Count == releases && *Leaf(address) == first, "rejections leave ownership and PTE unchanged");
Check(VirtualMemory.UnmapDevice(address, 8192), "correct device teardown remains available");
});
Run("DeviceUnmapNeverReleasesTheMappedLeafEvenWhenAllocatorOwned", () =>
{
ulong ram = PhysicalMemory.Allocate();
ulong address = VirtualMemory.MapDeviceReadOnly(ram, 4096);
Check(address != 0 && VirtualMemory.UnmapDevice(address, 4096), "owned-leaf alias can be removed as a device mapping");
Check(PhysicalMemory.Owns(ram), "mapped physical leaf remains owned by its original allocator client");
Check(!PhysicalMemory.Releases.Any(item => item.Physical == ram), "device teardown never called RAM release on leaf");
Check(PhysicalMemory.AllocatedPages == 1 && PhysicalMemory.Release(ram), "original RAM owner releases it exactly once");
});
foreach (int allowed in new[] { 0, 1, 2 })
{
int captured = allowed;
Run("IntermediateAllocationFailureRollback-" + allowed, () =>
{
PhysicalMemory.AllocationAllowance = captured;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "injected intermediate allocation failure returned unavailable");
Check(PhysicalMemory.SuccessfulAllocations == captured, "failure injection reached exact table depth");
Check(PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "all partial intermediate levels reclaimed");
Check(PhysicalMemory.Releases.All(item => item.Released), "rollback released only allocator tables");
PhysicalMemory.AllocationAllowance = int.MaxValue;
ulong retry = VirtualMemory.MapDevice(0xC0000000, 4096);
Check(retry == VirtualMemory.Base, "failed mapping released reservation/cursor for retry");
Check(VirtualMemory.UnmapDevice(retry, 4096), "retry lifecycle succeeds");
});
}
Run("Cross2MiBBoundaryUsesTwoRealLeafTables", () =>
{
ulong prefix = VirtualMemory.Reserve((1UL << 21) - 4096, 4096);
ulong address = VirtualMemory.MapDevice(0xC0000000, 8192);
Check(prefix == VirtualMemory.Base && address == prefix + (1UL << 21) - 4096, "reservation straddles 2MiB boundary");
Check(PhysicalMemory.AllocatedPages == 4, "two PTs plus PD/PDPT allocated");
Check(*Leaf(address) == (0xC0000000 | Present | Writable | Nx | Uc), "PTE before boundary");
Check(*Leaf(address + 4096) == (0xC0001000 | Present | Writable | Nx | Uc), "PTE after boundary");
Check(VirtualMemory.UnmapDevice(address, 8192) && RootSlot() == 0 && PhysicalMemory.AllocatedPages == 0, "both PTs reclaimed");
Check(VirtualMemory.Release(prefix, (1UL << 21) - 4096), "uncommitted RAM prefix remains independently releasable");
});
Run("Cross2MiBFailureReclaimsTheEarlierMappedLeafAndAllTables", () =>
{
_ = VirtualMemory.Reserve((1UL << 21) - 4096, 4096);
PhysicalMemory.AllocationAllowance = 3;
Check(VirtualMemory.MapDevice(0xC0000000, 8192) == 0, "failure creating second PT is reported");
Check(PhysicalMemory.SuccessfulAllocations == 3 && PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "already-published first leaf and table chain rolled back");
Check(PhysicalMemory.Releases.Count == 3 && PhysicalMemory.Releases.All(item => item.Released), "only three tables were released, no MMIO physical leaves");
});
Run("Cross1GiBFailurePrunesNewEmptyPdAndPreviouslyMappedPt", () =>
{
_ = VirtualMemory.Reserve((1UL << 30) - 4096, 4096);
PhysicalMemory.AllocationAllowance = 4;
Check(VirtualMemory.MapDevice(0xC0000000, 8192) == 0, "failure after allocating second PD is reported");
Check(PhysicalMemory.SuccessfulAllocations == 4 && PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "failed address's empty PD and earlier published PT chain fully reclaimed");
Check(PhysicalMemory.Releases.Count == 4 && PhysicalMemory.Releases.All(item => item.Released), "only owned table pages released across PDPT entries");
});
Run("UnmappingAdjacentRegionPreservesSharedPageTableAndOtherPte", () =>
{
ulong first = VirtualMemory.MapDeviceReadOnly(0xC0000000, 4096);
ulong second = VirtualMemory.MapDevice(0xD0000000, 4096);
ulong secondPte = *Leaf(second);
Check(second == first + 4096 && PhysicalMemory.AllocatedPages == 3, "adjacent regions share real PT/PD/PDPT pages");
Check(VirtualMemory.UnmapDevice(first, 4096), "first region teardown succeeds");
Check(*Leaf(first) == 0 && *Leaf(second) == secondPte && PhysicalMemory.AllocatedPages == 3, "sibling mapping and its table ownership are preserved");
Check(!VirtualMemory.UnmapDevice(first, 4096), "stale region cannot tear down sibling");
Check(VirtualMemory.UnmapDevice(second, 4096) && PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "last sibling removes entire now-empty chain");
});
Run("ForeignPageTablesAreNotReleased", () =>
{
ulong foreign = PhysicalMemory.ForeignTable();
((ulong*)Native.Root)[(VirtualMemory.Base >> 39) & 511] = foreign | Present | Writable;
ulong address = VirtualMemory.MapDeviceReadOnly(0xC0000000, 4096);
Check(address == VirtualMemory.Base && VirtualMemory.UnmapDevice(address, 4096), "device under controlled foreign parent maps/unmaps");
Check(RootSlot() == (foreign | Present | Writable), "foreign parent remains linked and is not reclaimed");
Check(PhysicalMemory.Releases.Count(item => item.Physical == foreign && !item.Released) == 1, "allocator ownership rejection stopped pruning");
Check(PhysicalMemory.AllocatedPages == 0, "owned child tables still reclaimed");
});
Run("BadPatAndUnsupportedCpuNeverPublishMappings", () =>
{
foreach (byte memoryType in new byte[] { 1, 4, 5, 6, 7, 255 })
{
Native.Pat = (Native.Pat & ~(255UL << 24)) | (ulong)memoryType << 24;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0 && RootSlot() == 0 && PhysicalMemory.AllocatedPages == 0, "non-UC PAT index3 refused");
}
Native.Pat = 0x0007040600070406; Native.PatSupported = false; Native.MsrReads.Clear();
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "CPU without PAT refused");
Check(!Native.MsrReads.Contains(0x277), "unsupported PAT MSR was not read");
});
Run("ActualMaxPhysicalAddressAndLastPageBoundary", () =>
{
foreach (uint bits in new uint[] { 32, 36, 48, 52 })
{
Native.PhysicalBits = bits; ulong lastPage = ((1UL << (int)bits) - 1) & ~4095UL;
ulong address = VirtualMemory.MapDeviceReadOnly(lastPage, 4096);
Check(address != 0 && (*Leaf(address) & AddressMask) == lastPage, "highest legal physical page accepted at " + bits + " bits");
Check(VirtualMemory.UnmapDevice(address, 4096), "last legal page unmaps");
Check(VirtualMemory.MapDevice(lastPage, 8192) == 0, "crossing actual CPU physical width rejected");
Check(VirtualMemory.MapDevice(1UL << (int)bits, 4096) == 0, "reserved physical address bit rejected");
}
foreach (uint bits in new uint[] { 0, 31, 53, 64, 255 })
{
Native.PhysicalBits = bits;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "invalid MAXPHYADDR refused");
}
Native.PhysicalBits = 52; Native.MaximumExtendedLeaf = 0x80000007;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "absent MAXPHYADDR leaf refused");
});
Run("InvalidRangesAndWrongRegionKindHaveNoSideEffects", () =>
{
foreach ((ulong physical, ulong bytes) in new[] { (0xC0000001UL, 4096UL), (0xC0000000UL, 0UL), (0xC0000000UL, VirtualMemory.Capacity + 1), (ulong.MaxValue & ~4095UL, 4096UL) })
Check(VirtualMemory.MapDevice(physical, bytes) == 0, "invalid physical geometry rejected");
Check(PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "invalid ranges allocate nothing");
ulong ram = VirtualMemory.Reserve(8192, 4096);
Check(!VirtualMemory.UnmapDevice(ram, 8192), "RAM reservation cannot use device teardown");
Check(VirtualMemory.Commit(ram, 8192), "RAM commit still works");
Check(VirtualMemory.Protect(ram, 8192, 1), "RAM permission path still works");
Check(VirtualMemory.Release(ram, 8192) && !VirtualMemory.Release(ram, 8192), "RAM release remains owned/idempotence-safe");
Check(PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "RAM regression leaves no tables/pages");
});
bool unchanged = Hash(source) == before;
bool harnessUnchanged = harness.OrderBy(item => item.Key).SequenceEqual(HarnessHashes().OrderBy(item => item.Key));
var receipt = new { Kind = "XfeControlledDeviceMappingChecks.V1", HostOnly = true, GuestExecution = false,
ActualCpuPageTablesChanged = false, ActualMmioAccessed = false, GpuExecutionVerified = false, CudaExecutionVerified = false,
ProductionSource = "Source/XFESystem.NativeKernel/VirtualMemory.cs", ProductionSourceSha256 = before,
ProductionSourceUnchanged = unchanged, HarnessSourceSha256 = harness, HarnessSourceUnchanged = harnessUnchanged,
ManagedAssemblySha256 = Hash(typeof(Program).Assembly.Location),
Passed = unchanged && harnessUnchanged && Results.All(item => ((CheckResult)item).Passed),
Checks = Results.Count, Assertions = assertions, Results, FinishedUtc = DateTime.UtcNow.ToString("O") };
Save(Path.Combine(output, "Result.json"), JsonSerializer.SerializeToUtf8Bytes(receipt, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine(JsonSerializer.Serialize(new { receipt.Passed, receipt.Checks, receipt.Assertions, Result = Path.Combine(output, "Result.json"), Meaning = "Linked production VM logic on controlled host memory; no GPU/MMIO hardware execution." }));
return receipt.Passed ? 0 : 1;
}
private sealed record CheckResult(string Name, bool Passed, int Assertions, string? Error);
static void Run(string name, Action test)
{
int before = assertions; string? error = null;
try { PhysicalMemory.Setup(); Check(VirtualMemory.Initialize(), "production VM initializes"); test(); }
catch (Exception failure) { error = failure.ToString(); }
finally { PhysicalMemory.Dispose(); }
Results.Add(new CheckResult(name, error is null, assertions - before, error));
}
static void Check(bool condition, string message) { assertions++; if (!condition) throw new InvalidOperationException(message); }
static ulong RootSlot() => ((ulong*)Native.Root)[(VirtualMemory.Base >> 39) & 511];
static ulong* Leaf(ulong address)
{
ulong* table = (ulong*)Native.Root;
for (int shift = 39; shift >= 21; shift -= 9)
{
ulong entry = table[(address >> shift) & 511];
if ((entry & Present) == 0 || (entry & 0x80) != 0) return null;
table = (ulong*)PhysicalMemory.ToVirtual(entry & AddressMask);
if (table == null) throw new InvalidOperationException("Production PTE references memory outside the controlled provider.");
}
return table + ((address >> 12) & 511);
}
static string FindRoot()
{
for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
if (File.Exists(Path.Combine(directory.FullName, "Source/XFESystem.NativeKernel/VirtualMemory.cs"))) return directory.FullName;
throw new DirectoryNotFoundException("Run under the repository build directory.");
}
static string Hash(string path) { using var stream = File.OpenRead(path); return Convert.ToHexStringLower(SHA256.HashData(stream)); }
static SortedDictionary<string, string> HarnessHashes()
{
var result = new SortedDictionary<string, string>(StringComparer.Ordinal);
foreach (string file in Directory.GetFiles(Path.Combine(root, "Tools/IndependentKernel/DeviceMappingChecks"), "*", SearchOption.TopDirectoryOnly))
result[Path.GetRelativePath(root, file).Replace('\\', '/')] = Hash(file);
return result;
}
static void Save(string path, byte[] data) { using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write); stream.Write(data); stream.Flush(true); }
}
using System.Security.Cryptography;
using System.Text.Json;
using XFESystem.NativeKernel;
internal static unsafe class Program
{
const ulong AddressMask = 0x000ffffffffff000, Present = 1, Writable = 2, Nx = 1UL << 63, Uc = 0x18;
static int assertions;
static readonly List<object> Results = [];
static string root = "";
static int Main()
{
root = FindRoot(); string source = Path.Combine(root, "Source/XFESystem.NativeKernel/VirtualMemory.cs");
string before = Hash(source);
var harness = HarnessHashes();
string output = Path.Combine(root, "build/Gpu/DeviceMappingChecks-" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "-" + Guid.NewGuid().ToString("N")[..8]);
if (Directory.Exists(output)) throw new IOException("Refusing to overwrite prior evidence.");
Directory.CreateDirectory(output);
Run("ReadOnlyUcNxPtesAndExactUnmap", () =>
{
ulong free = PhysicalMemory.AvailablePages;
ulong address = VirtualMemory.MapDeviceReadOnly(0xC0000000, 8192);
Check(address == VirtualMemory.Base, "first virtual reservation");
Check(PhysicalMemory.AllocatedPages == 3, "only three page-table pages allocated");
Check(*Leaf(address) == (0xC0000000 | Present | Nx | Uc), "first real PTE includes RO/NX/UC");
Check(*Leaf(address + 4096) == (0xC0001000 | Present | Nx | Uc), "second PTE physical progression");
ulong first = *Leaf(address), second = *Leaf(address + 4096);
Check(!VirtualMemory.UnmapDevice(address, 4096), "partial unmap rejected");
Check(!VirtualMemory.UnmapDevice(address + 4096, 4096), "interior unmap rejected");
Check(!VirtualMemory.UnmapDevice(address, 12288), "oversized unmap rejected");
Check(!VirtualMemory.UnmapDevice(address + 1, 8192), "unaligned unmap rejected");
Check(*Leaf(address) == first && *Leaf(address + 4096) == second, "rejected unmaps preserve both PTEs");
Check(VirtualMemory.UnmapDevice(address, 8192), "exact unmap accepted");
Check(Leaf(address) == null && RootSlot() == 0, "last unmap prunes actual PTE tables");
Check(!VirtualMemory.UnmapDevice(address, 8192), "duplicate unmap rejected");
Check(PhysicalMemory.AvailablePages == free && PhysicalMemory.AllocatedPages == 0, "table pages reclaimed");
Check(PhysicalMemory.Releases.All(item => item.Released), "only owned tables released");
});
Run("MmioCannotUseRamCommitDecommitProtectOrRelease", () =>
{
ulong address = VirtualMemory.MapDevice(0xC0000000, 8192), first = *Leaf(address);
Check((first & Writable) != 0, "writable device map has RW bit");
int releases = PhysicalMemory.Releases.Count;
Check(!VirtualMemory.Commit(address, 4096), "RAM commit cannot alias MMIO");
Check(!VirtualMemory.Decommit(address, 8192), "RAM decommit cannot free MMIO");
Check(!VirtualMemory.Release(address, 8192), "RAM release cannot free MMIO");
Check(!VirtualMemory.Protect(address, 8192, 1), "RAM protect cannot change MMIO cache policy");
Check(PhysicalMemory.Releases.Count == releases && *Leaf(address) == first, "rejections leave ownership and PTE unchanged");
Check(VirtualMemory.UnmapDevice(address, 8192), "correct device teardown remains available");
});
Run("DeviceUnmapNeverReleasesTheMappedLeafEvenWhenAllocatorOwned", () =>
{
ulong ram = PhysicalMemory.Allocate();
ulong address = VirtualMemory.MapDeviceReadOnly(ram, 4096);
Check(address != 0 && VirtualMemory.UnmapDevice(address, 4096), "owned-leaf alias can be removed as a device mapping");
Check(PhysicalMemory.Owns(ram), "mapped physical leaf remains owned by its original allocator client");
Check(!PhysicalMemory.Releases.Any(item => item.Physical == ram), "device teardown never called RAM release on leaf");
Check(PhysicalMemory.AllocatedPages == 1 && PhysicalMemory.Release(ram), "original RAM owner releases it exactly once");
});
foreach (int allowed in new[] { 0, 1, 2 })
{
int captured = allowed;
Run("IntermediateAllocationFailureRollback-" + allowed, () =>
{
PhysicalMemory.AllocationAllowance = captured;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "injected intermediate allocation failure returned unavailable");
Check(PhysicalMemory.SuccessfulAllocations == captured, "failure injection reached exact table depth");
Check(PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "all partial intermediate levels reclaimed");
Check(PhysicalMemory.Releases.All(item => item.Released), "rollback released only allocator tables");
PhysicalMemory.AllocationAllowance = int.MaxValue;
ulong retry = VirtualMemory.MapDevice(0xC0000000, 4096);
Check(retry == VirtualMemory.Base, "failed mapping released reservation/cursor for retry");
Check(VirtualMemory.UnmapDevice(retry, 4096), "retry lifecycle succeeds");
});
}
Run("Cross2MiBBoundaryUsesTwoRealLeafTables", () =>
{
ulong prefix = VirtualMemory.Reserve((1UL << 21) - 4096, 4096);
ulong address = VirtualMemory.MapDevice(0xC0000000, 8192);
Check(prefix == VirtualMemory.Base && address == prefix + (1UL << 21) - 4096, "reservation straddles 2MiB boundary");
Check(PhysicalMemory.AllocatedPages == 4, "two PTs plus PD/PDPT allocated");
Check(*Leaf(address) == (0xC0000000 | Present | Writable | Nx | Uc), "PTE before boundary");
Check(*Leaf(address + 4096) == (0xC0001000 | Present | Writable | Nx | Uc), "PTE after boundary");
Check(VirtualMemory.UnmapDevice(address, 8192) && RootSlot() == 0 && PhysicalMemory.AllocatedPages == 0, "both PTs reclaimed");
Check(VirtualMemory.Release(prefix, (1UL << 21) - 4096), "uncommitted RAM prefix remains independently releasable");
});
Run("Cross2MiBFailureReclaimsTheEarlierMappedLeafAndAllTables", () =>
{
_ = VirtualMemory.Reserve((1UL << 21) - 4096, 4096);
PhysicalMemory.AllocationAllowance = 3;
Check(VirtualMemory.MapDevice(0xC0000000, 8192) == 0, "failure creating second PT is reported");
Check(PhysicalMemory.SuccessfulAllocations == 3 && PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "already-published first leaf and table chain rolled back");
Check(PhysicalMemory.Releases.Count == 3 && PhysicalMemory.Releases.All(item => item.Released), "only three tables were released, no MMIO physical leaves");
});
Run("Cross1GiBFailurePrunesNewEmptyPdAndPreviouslyMappedPt", () =>
{
_ = VirtualMemory.Reserve((1UL << 30) - 4096, 4096);
PhysicalMemory.AllocationAllowance = 4;
Check(VirtualMemory.MapDevice(0xC0000000, 8192) == 0, "failure after allocating second PD is reported");
Check(PhysicalMemory.SuccessfulAllocations == 4 && PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "failed address's empty PD and earlier published PT chain fully reclaimed");
Check(PhysicalMemory.Releases.Count == 4 && PhysicalMemory.Releases.All(item => item.Released), "only owned table pages released across PDPT entries");
});
Run("UnmappingAdjacentRegionPreservesSharedPageTableAndOtherPte", () =>
{
ulong first = VirtualMemory.MapDeviceReadOnly(0xC0000000, 4096);
ulong second = VirtualMemory.MapDevice(0xD0000000, 4096);
ulong secondPte = *Leaf(second);
Check(second == first + 4096 && PhysicalMemory.AllocatedPages == 3, "adjacent regions share real PT/PD/PDPT pages");
Check(VirtualMemory.UnmapDevice(first, 4096), "first region teardown succeeds");
Check(*Leaf(first) == 0 && *Leaf(second) == secondPte && PhysicalMemory.AllocatedPages == 3, "sibling mapping and its table ownership are preserved");
Check(!VirtualMemory.UnmapDevice(first, 4096), "stale region cannot tear down sibling");
Check(VirtualMemory.UnmapDevice(second, 4096) && PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "last sibling removes entire now-empty chain");
});
Run("ForeignPageTablesAreNotReleased", () =>
{
ulong foreign = PhysicalMemory.ForeignTable();
((ulong*)Native.Root)[(VirtualMemory.Base >> 39) & 511] = foreign | Present | Writable;
ulong address = VirtualMemory.MapDeviceReadOnly(0xC0000000, 4096);
Check(address == VirtualMemory.Base && VirtualMemory.UnmapDevice(address, 4096), "device under controlled foreign parent maps/unmaps");
Check(RootSlot() == (foreign | Present | Writable), "foreign parent remains linked and is not reclaimed");
Check(PhysicalMemory.Releases.Count(item => item.Physical == foreign && !item.Released) == 1, "allocator ownership rejection stopped pruning");
Check(PhysicalMemory.AllocatedPages == 0, "owned child tables still reclaimed");
});
Run("BadPatAndUnsupportedCpuNeverPublishMappings", () =>
{
foreach (byte memoryType in new byte[] { 1, 4, 5, 6, 7, 255 })
{
Native.Pat = (Native.Pat & ~(255UL << 24)) | (ulong)memoryType << 24;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0 && RootSlot() == 0 && PhysicalMemory.AllocatedPages == 0, "non-UC PAT index3 refused");
}
Native.Pat = 0x0007040600070406; Native.PatSupported = false; Native.MsrReads.Clear();
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "CPU without PAT refused");
Check(!Native.MsrReads.Contains(0x277), "unsupported PAT MSR was not read");
});
Run("ActualMaxPhysicalAddressAndLastPageBoundary", () =>
{
foreach (uint bits in new uint[] { 32, 36, 48, 52 })
{
Native.PhysicalBits = bits; ulong lastPage = ((1UL << (int)bits) - 1) & ~4095UL;
ulong address = VirtualMemory.MapDeviceReadOnly(lastPage, 4096);
Check(address != 0 && (*Leaf(address) & AddressMask) == lastPage, "highest legal physical page accepted at " + bits + " bits");
Check(VirtualMemory.UnmapDevice(address, 4096), "last legal page unmaps");
Check(VirtualMemory.MapDevice(lastPage, 8192) == 0, "crossing actual CPU physical width rejected");
Check(VirtualMemory.MapDevice(1UL << (int)bits, 4096) == 0, "reserved physical address bit rejected");
}
foreach (uint bits in new uint[] { 0, 31, 53, 64, 255 })
{
Native.PhysicalBits = bits;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "invalid MAXPHYADDR refused");
}
Native.PhysicalBits = 52; Native.MaximumExtendedLeaf = 0x80000007;
Check(VirtualMemory.MapDevice(0xC0000000, 4096) == 0, "absent MAXPHYADDR leaf refused");
});
Run("InvalidRangesAndWrongRegionKindHaveNoSideEffects", () =>
{
foreach ((ulong physical, ulong bytes) in new[] { (0xC0000001UL, 4096UL), (0xC0000000UL, 0UL), (0xC0000000UL, VirtualMemory.Capacity + 1), (ulong.MaxValue & ~4095UL, 4096UL) })
Check(VirtualMemory.MapDevice(physical, bytes) == 0, "invalid physical geometry rejected");
Check(PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "invalid ranges allocate nothing");
ulong ram = VirtualMemory.Reserve(8192, 4096);
Check(!VirtualMemory.UnmapDevice(ram, 8192), "RAM reservation cannot use device teardown");
Check(VirtualMemory.Commit(ram, 8192), "RAM commit still works");
Check(VirtualMemory.Protect(ram, 8192, 1), "RAM permission path still works");
Check(VirtualMemory.Release(ram, 8192) && !VirtualMemory.Release(ram, 8192), "RAM release remains owned/idempotence-safe");
Check(PhysicalMemory.AllocatedPages == 0 && RootSlot() == 0, "RAM regression leaves no tables/pages");
});
bool unchanged = Hash(source) == before;
bool harnessUnchanged = harness.OrderBy(item => item.Key).SequenceEqual(HarnessHashes().OrderBy(item => item.Key));
var receipt = new { Kind = "XfeControlledDeviceMappingChecks.V1", HostOnly = true, GuestExecution = false,
ActualCpuPageTablesChanged = false, ActualMmioAccessed = false, GpuExecutionVerified = false, CudaExecutionVerified = false,
ProductionSource = "Source/XFESystem.NativeKernel/VirtualMemory.cs", ProductionSourceSha256 = before,
ProductionSourceUnchanged = unchanged, HarnessSourceSha256 = harness, HarnessSourceUnchanged = harnessUnchanged,
ManagedAssemblySha256 = Hash(typeof(Program).Assembly.Location),
Passed = unchanged && harnessUnchanged && Results.All(item => ((CheckResult)item).Passed),
Checks = Results.Count, Assertions = assertions, Results, FinishedUtc = DateTime.UtcNow.ToString("O") };
Save(Path.Combine(output, "Result.json"), JsonSerializer.SerializeToUtf8Bytes(receipt, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine(JsonSerializer.Serialize(new { receipt.Passed, receipt.Checks, receipt.Assertions, Result = Path.Combine(output, "Result.json"), Meaning = "Linked production VM logic on controlled host memory; no GPU/MMIO hardware execution." }));
return receipt.Passed ? 0 : 1;
}
private sealed record CheckResult(string Name, bool Passed, int Assertions, string? Error);
static void Run(string name, Action test)
{
int before = assertions; string? error = null;
try { PhysicalMemory.Setup(); Check(VirtualMemory.Initialize(), "production VM initializes"); test(); }
catch (Exception failure) { error = failure.ToString(); }
finally { PhysicalMemory.Dispose(); }
Results.Add(new CheckResult(name, error is null, assertions - before, error));
}
static void Check(bool condition, string message) { assertions++; if (!condition) throw new InvalidOperationException(message); }
static ulong RootSlot() => ((ulong*)Native.Root)[(VirtualMemory.Base >> 39) & 511];
static ulong* Leaf(ulong address)
{
ulong* table = (ulong*)Native.Root;
for (int shift = 39; shift >= 21; shift -= 9)
{
ulong entry = table[(address >> shift) & 511];
if ((entry & Present) == 0 || (entry & 0x80) != 0) return null;
table = (ulong*)PhysicalMemory.ToVirtual(entry & AddressMask);
if (table == null) throw new InvalidOperationException("Production PTE references memory outside the controlled provider.");
}
return table + ((address >> 12) & 511);
}
static string FindRoot()
{
for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
if (File.Exists(Path.Combine(directory.FullName, "Source/XFESystem.NativeKernel/VirtualMemory.cs"))) return directory.FullName;
throw new DirectoryNotFoundException("Run under the repository build directory.");
}
static string Hash(string path) { using var stream = File.OpenRead(path); return Convert.ToHexStringLower(SHA256.HashData(stream)); }
static SortedDictionary<string, string> HarnessHashes()
{
var result = new SortedDictionary<string, string>(StringComparer.Ordinal);
foreach (string file in Directory.GetFiles(Path.Combine(root, "Tools/IndependentKernel/DeviceMappingChecks"), "*", SearchOption.TopDirectoryOnly))
result[Path.GetRelativePath(root, file).Replace('\\', '/')] = Hash(file);
return result;
}
static void Save(string path, byte[] data) { using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write); stream.Write(data); stream.Flush(true); }
}