Skip to content
Merged
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
60 changes: 49 additions & 11 deletions Sources/GraphiteMemory/HeapZone.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,13 @@ public final class HeapZone {
try record { () throws(MacError) -> UInt32 in
guard size >= 0 else { throw .memorySize }
let handle = try takeMaster()
var address: UInt32?
do throws(MacError) {
let address = try allocate(Self.physical(size), owner: .handle(handle), logical: UInt32(size))
if clear { try memory.zero(address, count: Int(size)) }
try memory.store32(address, at: handle)
address = try allocate(Self.physical(size), owner: .handle(handle), logical: UInt32(size))
if clear { try memory.zero(address!, count: Int(size)) }
try memory.store32(address!, at: handle)
} catch {
if let address { removeBlock(at: address) }
releaseMaster(handle)
throw error
}
Expand All @@ -130,7 +132,12 @@ public final class HeapZone {
public func newEmptyHandle() throws(MacError) -> UInt32 {
try record { () throws(MacError) -> UInt32 in
let handle = try takeMaster()
try memory.store32(0, at: handle)
do throws(MacError) {
try memory.store32(0, at: handle)
} catch {
releaseMaster(handle)
throw error
}
return handle
}
}
Expand All @@ -140,9 +147,10 @@ public final class HeapZone {
try record { () throws(MacError) in
guard handle != 0 else { return }
let master = try live(handle)
// The guest's master pointer first: if its memory refuses, nothing has changed.
try memory.store32(0, at: handle)
if master.state.contains(.resource) { resourceDisposed?(HandleID(handle: handle, generation: master.generation)) }
if let index = index(of: .handle(handle)) { blocks.remove(at: index) }
try memory.store32(0, at: handle)
releaseMaster(handle)
}
}
Expand Down Expand Up @@ -174,11 +182,17 @@ public final class HeapZone {
let address = try allocate(physical, owner: .pointer, logical: UInt32(size), keeping: handle)
index = self.index(of: .handle(handle))!
let old = blocks[index]
try memory.move(from: old.address, to: address, count: Int(old.logical))
// Copy and repoint before letting the old block go, so a refused write leaves it.
do throws(MacError) {
try memory.move(from: old.address, to: address, count: Int(old.logical))
try memory.store32(address, at: handle)
} catch {
removeBlock(at: address)
throw error
}
blocks.remove(at: index)
let moved = self.index(at: address)!
blocks[moved].owner = .handle(handle)
try memory.store32(address, at: handle)
}
}

Expand All @@ -205,7 +219,13 @@ public final class HeapZone {
try freeBlock(at: index, of: handle)
}
let address = try allocate(Self.physical(size), owner: .handle(handle), logical: UInt32(size))
try memory.store32(address, at: handle)
do throws(MacError) {
try memory.store32(address, at: handle)
} catch {
// The old block is gone; the handle is left empty, its master pointer nil.
removeBlock(at: address)
throw error
}
}
}

Expand Down Expand Up @@ -261,7 +281,12 @@ public final class HeapZone {
try record { () throws(MacError) -> UInt32 in
guard size >= 0 else { throw .memorySize }
let address = try allocate(Self.physical(size), owner: .pointer, logical: UInt32(size))
if clear { try memory.zero(address, count: Int(size)) }
do throws(MacError) {
if clear { try memory.zero(address, count: Int(size)) }
} catch {
removeBlock(at: address)
throw error
}
return address
}
}
Expand Down Expand Up @@ -401,6 +426,8 @@ public final class HeapZone {
}
}

/// A fault partway through leaves every block recorded where its bytes are; a handle whose
/// master pointer couldn't be written may point at where its block was.
private func compactBlocks() throws(MacError) {
var cursor = range.lowerBound
for index in blocks.indices {
Expand Down Expand Up @@ -429,9 +456,15 @@ public final class HeapZone {

/// Frees a handle's block, and the state that went with it.
private func freeBlock(at index: Int, of handle: UInt32) throws(MacError) {
// The guest's master pointer first: if its memory refuses, nothing has changed.
try memory.store32(0, at: handle)
blocks.remove(at: index)
masters[handle]?.state = []
try memory.store32(0, at: handle)
}

/// Forgets a block just placed, after a write to it failed.
private func removeBlock(at address: UInt32) {
if let index = index(at: address) { blocks.remove(at: index) }
}

/// A handle's master, if the handle has a block: nilHandleErr if not.
Expand All @@ -454,7 +487,12 @@ public final class HeapZone {
if freeMasters.isEmpty {
let count = Self.mastersPerBlock
let address = try allocate(UInt32(count * 4), owner: .masters, logical: UInt32(count * 4))
try memory.zero(address, count: count * 4)
do throws(MacError) {
try memory.zero(address, count: count * 4)
} catch {
removeBlock(at: address)
throw error
}
for slot in (0 ..< count).reversed() {
let handle = address + UInt32(slot * 4)
masters[handle] = Master()
Expand Down
146 changes: 146 additions & 0 deletions Tests/GraphiteMemoryTests/HeapZoneTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,149 @@ import GraphiteMemory
#expect(try zone.pointerSize(zone.newPointer(0)) == 0)
}
}

/// Guest memory that refuses the writes a test picks, as a host's checked memory can.
private final class RefusingMemory: GuestMemory {
let bytes: ByteGuestMemory
var refuses: (UInt32, [UInt8]) -> Bool = { _, _ in false }

init(base: UInt32, count: Int) { bytes = ByteGuestMemory(base: base, count: count) }

func read(_ address: UInt32, count: Int) throws(MacError) -> [UInt8] {
try bytes.read(address, count: count)
}

func write(_ data: [UInt8], at address: UInt32) throws(MacError) {
guard !refuses(address, data) else { throw .memoryAddress }
try bytes.write(data, at: address)
}
}

/// A write the host refuses leaves the zone as it was: no block or master pointer lost, and
/// memAdrErr for the call.
@Suite struct HeapZoneFaultTests {

private func zone() -> (HeapZone, RefusingMemory) {
let memory = RefusingMemory(base: 0x1000, count: 4096)
return (HeapZone(memory: memory, range: 0x1000 ..< 0x2000), memory)
}

/// The zone's accounting, to compare before and after a refused write.
private func snapshot(_ zone: HeapZone) -> (UInt32, UInt32) { (zone.freeBytes, zone.largestBlock) }

@Test func newPointerClearRollsBack() throws {
let (zone, memory) = zone()
let before = snapshot(zone)
memory.refuses = { _, data in data.count == 40 }
#expect(throws: MacError.memoryAddress) { try zone.newPointer(40, clear: true) }
#expect(zone.memError == -110)
#expect(snapshot(zone) == before)
memory.refuses = { _, _ in false }
#expect(try zone.newPointer(40, clear: true) == 0x1000)
}

@Test func newHandleRollsBackItsBlockAndMasterPointer() throws {
let (zone, memory) = zone()
// The block of master pointers, made by a first handle, stays.
try zone.disposeHandle(zone.newHandle(0))
let before = snapshot(zone)
let next = try zone.newHandle(0)
try zone.disposeHandle(next)
for refused in [{ (_: UInt32, data: [UInt8]) in data.count == 40 }, // clearing the block
{ (address: UInt32, data: [UInt8]) in address == next && data.count == 4 }] { // the master pointer
memory.refuses = refused
#expect(throws: MacError.memoryAddress) { try zone.newHandle(40, clear: true) }
#expect(snapshot(zone) == before)
memory.refuses = { _, _ in false }
}
// The same master pointer comes next, as it would have.
#expect(try zone.newHandle(40, clear: true) == next)
}

@Test func refusedMasterBlockIsForgotten() throws {
let (zone, memory) = zone()
let before = snapshot(zone)
memory.refuses = { _, data in data.count == HeapZone.mastersPerBlock * 4 }
#expect(throws: MacError.memoryAddress) { try zone.newHandle(8) }
#expect(throws: MacError.memoryAddress) { try zone.newEmptyHandle() }
#expect(snapshot(zone) == before)
memory.refuses = { _, _ in false }
#expect(try zone.newHandle(8) != 0)
}

@Test func newEmptyHandleReleasesItsMasterPointer() throws {
let (zone, memory) = zone()
try zone.disposeHandle(zone.newEmptyHandle())
let next = try zone.newEmptyHandle()
try zone.disposeHandle(next)
memory.refuses = { address, _ in address == next }
#expect(throws: MacError.memoryAddress) { try zone.newEmptyHandle() }
#expect(zone.handleID(next) == nil)
memory.refuses = { _, _ in false }
#expect(try zone.newEmptyHandle() == next)
}

@Test func disposeHandleChangesNothingWhenRefused() throws {
let (zone, memory) = zone()
let handle = try zone.newHandle(16)
try zone.update(handle, setting: .resource)
var disposed: [HandleID] = []
zone.resourceDisposed = { disposed.append($0) }
let before = snapshot(zone)
memory.refuses = { address, _ in address == handle }
#expect(throws: MacError.memoryAddress) { try zone.disposeHandle(handle) }
#expect(snapshot(zone) == before)
#expect(disposed.isEmpty)
#expect(try zone.handleSize(handle) == 16)
#expect(try zone.state(handle) == .resource)
}

@Test func setHandleSizeKeepsTheOldBlockWhenAMoveIsRefused() throws {
let (zone, memory) = zone()
let handle = try zone.newHandle(8)
let block = try memory.load32(handle)
try memory.write([1, 2, 3, 4, 5, 6, 7, 8], at: block)
// A pointer after the block, so growing has to move it.
_ = try zone.newPointer(8)
let before = snapshot(zone)
for refused in [{ (_: UInt32, data: [UInt8]) in data.count == 8 }, // copying the bytes
{ (address: UInt32, _: [UInt8]) in address == handle }] { // the master pointer
memory.refuses = refused
#expect(throws: MacError.memoryAddress) { try zone.setHandleSize(handle, 200) }
#expect(snapshot(zone) == before)
#expect(try zone.handleSize(handle) == 8)
#expect(try memory.load32(handle) == block)
#expect(try zone.recoverHandle(block) == handle)
memory.refuses = { _, _ in false }
}
try zone.setHandleSize(handle, 200)
#expect(try memory.read(memory.load32(handle), count: 8) == [1, 2, 3, 4, 5, 6, 7, 8])
}

@Test func emptyAndPurgeChangeNothingWhenRefused() throws {
let (zone, memory) = zone()
let handle = try zone.newHandle(32)
try zone.update(handle, setting: .purgeable)
let before = snapshot(zone)
memory.refuses = { address, _ in address == handle }
#expect(throws: MacError.memoryAddress) { try zone.emptyHandle(handle) }
#expect(throws: MacError.memoryAddress) { try zone.purge(needing: 4096) }
#expect(snapshot(zone) == before)
#expect(try zone.handleSize(handle) == 32)
#expect(try zone.state(handle) == .purgeable)
}

@Test func reallocateHandleLeavesAnEmptyHandleWhenRefused() throws {
let (zone, memory) = zone()
let handle = try zone.newHandle(32)
try zone.emptyHandle(handle)
let empty = snapshot(zone)
try zone.reallocateHandle(handle, 32)
// Freeing the old block clears the master pointer; the new block's address is refused.
memory.refuses = { address, data in address == handle && data != [0, 0, 0, 0] }
#expect(throws: MacError.memoryAddress) { try zone.reallocateHandle(handle, 48) }
#expect(snapshot(zone) == empty)
#expect(throws: MacError.nilHandle) { try zone.handleSize(handle) }
#expect(try memory.load32(handle) == 0)
}
}
Loading