File: GuestMemory.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (377 lines) | stat: -rw-r--r-- 15,518 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/// A write/read-able view representation of WebAssembly Memory instance
public protocol GuestMemory {
    /// Executes the given closure with a mutable buffer pointer to the host memory region mapped as guest memory.
    func withUnsafeMutableBufferPointer<T>(
        offset: UInt,
        count: Int,
        _ body: (UnsafeMutableRawBufferPointer) throws -> T
    ) rethrows -> T
}

/// 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)
    }
}

/// Auto implementation of ``GuestPointee`` for ``RawRepresentable`` types
extension GuestPrimitivePointee where Self: RawRepresentable, Self.RawValue: GuestPointee {
    /// Reads a value of RawValue type and constructs a value of Self type
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> Self {
        Self(rawValue: .readFromGuest(pointer))!
    }

    /// Writes the raw value of the given value to the given pointer of guest memory
    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: Self) {
        Self.RawValue.writeToGuest(at: pointer, value: value.rawValue)
    }
}

extension UInt8: GuestPrimitivePointee {
    /// Reads a value of `UInt8` type from the given pointer of guest memory
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt8 {
        pointer.withHostPointer(count: MemoryLayout<UInt8>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt8.self)
            return pointer.baseAddress!.pointee
        }
    }

    /// Writes the given value at the given pointer of guest memory
    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt8) {
        pointer.withHostPointer(count: MemoryLayout<UInt8>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt8.self)
            pointer.baseAddress!.pointee = value
        }
    }
}

extension UInt16: GuestPrimitivePointee {
    /// Reads a value of `UInt16` type from the given pointer of guest memory
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt16 {
        pointer.withHostPointer(count: MemoryLayout<UInt16>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt16.self)
            let value = pointer.baseAddress!.pointee
            #if _endian(little)
                return value
            #else
                return value.byteSwapped
            #endif
        }
    }

    /// Writes the given value at the given pointer of guest memory
    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt16) {
        pointer.withHostPointer(count: MemoryLayout<UInt16>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt16.self)
            let writingValue: UInt16
            #if _endian(little)
                writingValue = value
            #else
                value = value.byteSwapped
            #endif
            pointer.baseAddress!.pointee = writingValue
        }
    }
}

extension UInt32: GuestPrimitivePointee {
    /// Reads a value of `UInt32` type from the given pointer of guest memory
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt32 {
        pointer.withHostPointer(count: MemoryLayout<UInt32>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt32.self)
            let value = pointer.baseAddress!.pointee
            #if _endian(little)
                return value
            #else
                return value.byteSwapped
            #endif
        }
    }

    /// Writes the given value at the given pointer of guest memory
    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt32) {
        pointer.withHostPointer(count: MemoryLayout<UInt32>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt32.self)
            let writingValue: UInt32
            #if _endian(little)
                writingValue = value
            #else
                value = value.byteSwapped
            #endif
            pointer.baseAddress!.pointee = writingValue
        }
    }
}

extension UInt64: GuestPrimitivePointee {
    /// Reads a value of `UInt64` type from the given pointer of guest memory
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UInt64 {
        pointer.withHostPointer(count: MemoryLayout<UInt64>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt64.self)
            let value = pointer.baseAddress!.pointee
            #if _endian(little)
                return value
            #else
                return value.byteSwapped
            #endif
        }
    }

    /// Writes the given value at the given pointer of guest memory
    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UInt64) {
        pointer.withHostPointer(count: MemoryLayout<UInt64>.size) { hostPointer in
            let pointer = hostPointer.assumingMemoryBound(to: UInt64.self)
            let writingValue: UInt64
            #if _endian(little)
                writingValue = value
            #else
                value = value.byteSwapped
            #endif
            pointer.baseAddress!.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

    /// Creates a new pointer from the given memory space and offset
    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>(count: Int, _ body: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R {
        try memorySpace.withUnsafeMutableBufferPointer(offset: UInt(offset), count: count) { buffer in
            try body(UnsafeMutableRawBufferPointer(start: buffer.baseAddress!, count: count))
        }
    }

    /// 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 {
    /// Returns the size of this type in bytes in guest memory
    public static var sizeInGuest: UInt32 {
        return UInt32(MemoryLayout<UInt32>.size)
    }

    /// Returns the required alignment of this type, in bytes
    public static var alignInGuest: UInt32 {
        return UInt32(MemoryLayout<UInt32>.alignment)
    }

    /// Reads a value of self type from the given pointer of guest memory
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UnsafeGuestRawPointer {
        UnsafeGuestRawPointer(memorySpace: pointer.memorySpace, offset: UInt32.readFromGuest(pointer))
    }

    /// Writes the given value at the given pointer of guest memory
    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UnsafeGuestRawPointer) {
        UInt32.writeToGuest(at: pointer, value: value.offset)
    }
}

extension UnsafeGuestRawPointer {
    /// Returns a boolean value indicating whether the first pointer references a guest
    /// memory location earlier than the second pointer assuming they point the same guest
    /// memory space.
    public static func < (lhs: UnsafeGuestRawPointer, rhs: UnsafeGuestRawPointer) -> Bool {
        // Assuming they point the same guest memory space
        lhs.offset < rhs.offset
    }

    /// Returns a boolean value indicating whether the first pointer references a guest
    /// memory location later than the second pointer assuming they point the same guest
    /// memory space.
    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> {
    /// A raw pointer representation of guest memory space
    public let raw: UnsafeGuestRawPointer

    /// Creates a new pointer from the given raw pointer
    public init(_ raw: UnsafeGuestRawPointer) {
        self.raw = raw
    }

    /// Creates a new pointer from the given memory space and offset
    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>(count: Int, _ body: (UnsafeMutableBufferPointer<Pointee>) throws -> R) rethrows -> R {
        try raw.withHostPointer(count: MemoryLayout<Pointee>.stride * count) { 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 {
    /// Returns the size of this type in bytes in guest memory
    public static var sizeInGuest: UInt32 {
        UnsafeGuestRawPointer.sizeInGuest
    }

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

    /// Reads a value of self type from the given pointer of guest memory
    public static func readFromGuest(_ pointer: UnsafeGuestRawPointer) -> UnsafeGuestPointer<Pointee> {
        UnsafeGuestPointer(UnsafeGuestRawPointer.readFromGuest(pointer))
    }

    /// Writes the given value at the given pointer of guest memory
    public static func writeToGuest(at pointer: UnsafeGuestRawPointer, value: UnsafeGuestPointer<Pointee>) {
        UnsafeGuestRawPointer.writeToGuest(at: pointer, value: value.raw)
    }
}

extension UnsafeGuestPointer {
    /// Returns a new pointer offset from this pointer by the specified number of instances.
    public static func + (lhs: UnsafeGuestPointer, rhs: UInt32) -> UnsafeGuestPointer {
        let advanced = lhs.raw.advanced(by: Pointee.sizeInGuest * rhs)
        return UnsafeGuestPointer(advanced)
    }

    /// Returns a new pointer offset from this pointer by the specified number of instances.
    public static func += (lhs: inout Self, rhs: UInt32) {
        lhs = lhs + rhs
    }

    /// Returns a boolean value indicating whether the first pointer references a guest
    /// memory location earlier than the second pointer assuming they point the same guest
    /// memory space.
    public static func < (lhs: UnsafeGuestPointer, rhs: UnsafeGuestPointer) -> Bool {
        lhs.raw < rhs.raw
    }

    /// Returns a boolean value indicating whether the first pointer references a guest
    /// memory location later than the second pointer assuming they point the same guest
    /// memory space.
    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> {
    /// A pointer to the first element of the buffer
    public let baseAddress: UnsafeGuestPointer<Pointee>
    /// The number of elements in the buffer
    public let count: UInt32

    /// Creates a new buffer from the given base address and count
    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(count: Int(count)) { baseAddress in
            try body(baseAddress)
        }
    }
}

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
    }
}