File: GuestMemory.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (347 lines) | stat: -rw-r--r-- 12,632 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/// A write/read-able view representation of WebAssembly Memory instance
public struct GuestMemory {
    private let store: Store
    private let address: MemoryAddress

    public init(store: Store, address: MemoryAddress) {
        self.store = store
        self.address = address
    }

    /// Executes the given closure with a mutable buffer pointer to the host memory region mapped as guest memory.
    func withUnsafeMutableBufferPointer<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T {
        try store.withMemory(at: address) { memory in
            try memory.data.withUnsafeMutableBufferPointer { buffer in
                try body(UnsafeMutableRawBufferPointer(buffer))
            }
        }
    }
}

/// A pointer-referenceable type that is intended to be pointee of ``UnsafeGuestPointer``
public protocol GuestPointee {
    /// Returns the size of this type in bytes in guest memory
    static var sizeInGuest: UInt32 { get }

    /// Returns the required alignment of this type, in bytes
    static var alignInGuest: UInt32 { get }

    /// Reads a value of self type from the given pointer of guest memory
    static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> Self

    /// Writes the given value at the given pointer of guest memory
    static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: Self)
}

/// A pointer-referenceable primitive type that have the same size and alignment in host and guest
public protocol GuestPrimitivePointee: GuestPointee {}
extension GuestPrimitivePointee {
    /// Returns the same size of this type in bytes in the host
    public static var sizeInGuest: UInt32 {
        UInt32(MemoryLayout<Self>.size)
    }

    /// Returns the same required alignment of this type in the host
    public static var alignInGuest: UInt32 {
        UInt32(MemoryLayout<Self>.alignment)
    }
}

extension GuestPrimitivePointee where Self: RawRepresentable, Self.RawValue: GuestPointee {
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> Self {
        Self(rawValue: .readFromGuest(pointer))!
    }

    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: Self) {
        Self.RawValue.writeToGuest(at: pointer, value: value.rawValue)
    }
}

extension UInt8: GuestPrimitivePointee {
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt8 {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt8.self)
            return pointer.pointee
        }
    }

    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt8) {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt8.self)
            pointer.pointee = value
        }
    }
}

extension UInt16: GuestPrimitivePointee {
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt16 {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt16.self)
            let value = pointer.pointee
            #if _endian(little)
                return value
            #else
                return value.byteSwapped
            #endif
        }
    }

    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt16) {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt16.self)
            let writingValue: UInt16
            #if _endian(little)
                writingValue = value
            #else
                value = value.byteSwapped
            #endif
            pointer.pointee = writingValue
        }
    }
}

extension UInt32: GuestPrimitivePointee {
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt32 {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt32.self)
            let value = pointer.pointee
            #if _endian(little)
                return value
            #else
                return value.byteSwapped
            #endif
        }
    }

    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt32) {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt32.self)
            let writingValue: UInt32
            #if _endian(little)
                writingValue = value
            #else
                value = value.byteSwapped
            #endif
            pointer.pointee = writingValue
        }
    }
}

extension UInt64: GuestPrimitivePointee {
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt64 {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt64.self)
            let value = pointer.pointee
            #if _endian(little)
                return value
            #else
                return value.byteSwapped
            #endif
        }
    }

    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt64) {
        pointer.withHostPointer { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt64.self)
            let writingValue: UInt64
            #if _endian(little)
                writingValue = value
            #else
                value = value.byteSwapped
            #endif
            pointer.pointee = writingValue
        }
    }
}

/// A raw pointer representation of guest memory space
/// > Note: This type assumes pointer-size is 32-bit because WASI preview1 assumes the address space is 32-bit
public struct UnsafeGuestRawPointer {
    /// A guest memory space that this pointer points
    public let memorySpace: GuestMemory
    /// An offset from the base address of the guest memory region
    public let offset: UInt32

    public init(memorySpace: GuestMemory, offset: UInt32) {
        self.memorySpace = memorySpace
        self.offset = offset
    }

    /// Executes the given closure with a mutable raw pointer to the host memory region mapped as guest memory.
    public func withHostPointer<R>(_ body: (UnsafeMutableRawPointer) throws -> R) rethrows -> R {
        try memorySpace.withUnsafeMutableBufferPointer { buffer in
            try body(buffer.baseAddress!.advanced(by: Int(offset)))
        }
    }

    /// Returns a new pointer offset from this pointer by the specified number of bytes.
    public func advanced(by n: UInt32) -> UnsafeGuestRawPointer {
        UnsafeGuestRawPointer(memorySpace: memorySpace, offset: offset + n)
    }

    /// Obtains the next pointer that is properly aligned for the specified `alignment` value.
    public func alignedUp(toMultipleOf alignment: UInt32) -> UnsafeGuestRawPointer {
        let mask = alignment &- 1
        let aligned = (offset &+ mask) & ~mask
        return UnsafeGuestRawPointer(memorySpace: memorySpace, offset: aligned)
    }

    /// Returns a typed pointer to the same memory location.
    public func assumingMemoryBound<T>(to: T.Type) -> UnsafeGuestPointer<T> {
        return UnsafeGuestPointer(self)
    }
}

extension UnsafeGuestRawPointer: GuestPointee {
    public static var sizeInGuest: UInt32 {
        return UInt32(MemoryLayout<UInt32>.size)
    }

    public static var alignInGuest: UInt32 {
        return UInt32(MemoryLayout<UInt32>.alignment)
    }

    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UnsafeGuestRawPointer {
        UnsafeGuestRawPointer(memorySpace: pointer.memorySpace, offset: UInt32.readFromGuest(pointer))
    }

    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UnsafeGuestRawPointer) {
        UInt32.writeToGuest(at: pointer, value: value.offset)
    }
}

extension UnsafeGuestRawPointer {
    public static func < (lhs: UnsafeGuestRawPointer, rhs: UnsafeGuestRawPointer) -> Bool {
        // Assuming they point the same guest memory space
        lhs.offset < rhs.offset
    }

    public static func > (lhs: UnsafeGuestRawPointer, rhs: UnsafeGuestRawPointer) -> Bool {
        // Assuming they point the same guest memory space
        lhs.offset > rhs.offset
    }
}

/// A pointee-bound pointer representation of guest memory space
public struct UnsafeGuestPointer<Pointee: GuestPointee> {
    public let raw: UnsafeGuestRawPointer

    public init(_ raw: UnsafeGuestRawPointer) {
        self.raw = raw
    }

    public init(memorySpace: GuestMemory, offset: UInt32) {
        self.raw = UnsafeGuestRawPointer(memorySpace: memorySpace, offset: offset)
    }

    /// Executes the given closure with a mutable pointer to the host memory region mapped as guest memory.
    public func withHostPointer<R>(_ body: (UnsafeMutablePointer<Pointee>) throws -> R) rethrows -> R {
        try raw.withHostPointer { raw in
            try body(raw.assumingMemoryBound(to: Pointee.self))
        }
    }

    /// Accesses the instance referenced by this pointer.
    public var pointee: Pointee {
        get { Pointee.readFromGuest(self.raw) }
        nonmutating set { Pointee.writeToGuest(at: raw, value: newValue) }
    }
}

extension UnsafeGuestPointer: GuestPointee {
    public static var sizeInGuest: UInt32 {
        UnsafeGuestRawPointer.sizeInGuest
    }

    public static var alignInGuest: UInt32 {
        UnsafeGuestRawPointer.alignInGuest
    }

    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UnsafeGuestPointer<Pointee> {
        UnsafeGuestPointer(UnsafeGuestRawPointer.readFromGuest(pointer))
    }

    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UnsafeGuestPointer<Pointee>) {
        UnsafeGuestRawPointer.writeToGuest(at: pointer, value: value.raw)
    }
}

extension UnsafeGuestPointer {
    public static func + (lhs: UnsafeGuestPointer, rhs: UInt32) -> UnsafeGuestPointer {
        let advanced = lhs.raw.advanced(by: Pointee.sizeInGuest * rhs)
        return UnsafeGuestPointer(advanced)
    }

    public static func += (lhs: inout Self, rhs: UInt32) {
        lhs = lhs + rhs
    }

    public static func < (lhs: UnsafeGuestPointer, rhs: UnsafeGuestPointer) -> Bool {
        lhs.raw < rhs.raw
    }

    public static func > (lhs: UnsafeGuestPointer, rhs: UnsafeGuestPointer) -> Bool {
        lhs.raw > rhs.raw
    }
}

/// A pointee-bound interface to a buffer of elements stored contiguously in guest memory
public struct UnsafeGuestBufferPointer<Pointee: GuestPointee> {
    public let baseAddress: UnsafeGuestPointer<Pointee>
    public let count: UInt32

    public init(baseAddress: UnsafeGuestPointer<Pointee>, count: UInt32) {
        self.baseAddress = baseAddress
        self.count = count
    }

    /// Executes the given closure with a mutable buffer pointer to the host memory region mapped as guest memory.
    public func withHostPointer<R>(_ body: (UnsafeMutableBufferPointer<Pointee>) throws -> R) rethrows -> R {
        try baseAddress.withHostPointer { baseAddress in
            try body(UnsafeMutableBufferPointer(start: baseAddress, count: Int(count)))
        }
    }
}

extension UnsafeGuestBufferPointer: Sequence {
    /// An iterator over the elements of the buffer.
    public struct Iterator: IteratorProtocol {
        var position: UInt32
        let buffer: UnsafeGuestBufferPointer

        /// Accesses the next element and advances to the subsequent element, or
        /// returns `nil` if no next element exists.
        public mutating func next() -> Pointee? {
            guard position != buffer.count else { return nil }
            let pointer = buffer.baseAddress + position
            position += 1
            return pointer.pointee
        }
    }

    /// Returns an iterator over the elements of this buffer.
    public func makeIterator() -> Iterator {
        Iterator(position: 0, buffer: self)
    }
}

extension UnsafeGuestBufferPointer: Collection {
    public typealias Index = UInt32

    /// The index of the first element in a nonempty buffer.
    public var startIndex: UInt32 { 0 }

    /// The "past the end" position---that is, the position one greater than the
    /// last valid subscript argument.
    public var endIndex: UInt32 { count }

    /// Accesses the pointee at the specified offset from the base address of the buffer.
    public subscript(position: UInt32) -> Element {
        (self.baseAddress + position).pointee
    }

    /// Returns the position immediately after the given index.
    public func index(after i: UInt32) -> UInt32 {
        return i + 1
    }
}