-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathParseWasm.swift
314 lines (264 loc) · 9.15 KB
/
ParseWasm.swift
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
import struct Foundation.Data
/// Represents the type of value in WebAssembly
enum ValueType: String, Codable {
case i32
case i64
case f32
case f64
case funcref
case externref
case v128
}
/// Represents a function type in WebAssembly
struct FunctionType: Codable {
let parameters: [ValueType]
let results: [ValueType]
}
/// Represents a table type in WebAssembly
struct TableType: Codable {
let element: ElementType
let minimum: UInt32
let maximum: UInt32?
enum ElementType: String, Codable {
case funcref
case externref
}
}
/// Represents a memory type in WebAssembly
struct MemoryType: Codable {
let minimum: UInt32
let maximum: UInt32?
let shared: Bool
let index: IndexType
enum IndexType: String, Codable {
case i32
case i64
}
}
/// Represents a global type in WebAssembly
struct GlobalType: Codable {
let value: ValueType
let mutable: Bool
}
/// Represents an import entry in WebAssembly
struct ImportEntry: Codable {
let module: String
let name: String
let kind: ImportKind
enum ImportKind: Codable {
case function(type: FunctionType)
case table(type: TableType)
case memory(type: MemoryType)
case global(type: GlobalType)
}
}
/// Parse state for WebAssembly parsing
private class ParseState {
private let moduleBytes: Data
private var offset: Int
init(moduleBytes: Data) {
self.moduleBytes = moduleBytes
self.offset = 0
}
func hasMoreBytes() -> Bool {
return offset < moduleBytes.count
}
func readByte() throws -> UInt8 {
guard offset < moduleBytes.count else {
throw ParseError.unexpectedEndOfData
}
let byte = moduleBytes[offset]
offset += 1
return byte
}
func skipBytes(_ count: Int) throws {
guard offset + count <= moduleBytes.count else {
throw ParseError.unexpectedEndOfData
}
offset += count
}
/// Read an unsigned LEB128 integer
func readUnsignedLEB128() throws -> UInt32 {
var result: UInt32 = 0
var shift: UInt32 = 0
var byte: UInt8
repeat {
byte = try readByte()
result |= UInt32(byte & 0x7F) << shift
shift += 7
if shift > 32 {
throw ParseError.integerOverflow
}
} while (byte & 0x80) != 0
return result
}
func readName() throws -> String {
let nameLength = try readUnsignedLEB128()
guard offset + Int(nameLength) <= moduleBytes.count else {
throw ParseError.unexpectedEndOfData
}
let nameBytes = moduleBytes[offset..<(offset + Int(nameLength))]
guard let name = String(bytes: nameBytes, encoding: .utf8) else {
throw ParseError.invalidUTF8
}
offset += Int(nameLength)
return name
}
func assertBytes(_ expected: [UInt8]) throws {
let baseOffset = offset
let expectedLength = expected.count
guard baseOffset + expectedLength <= moduleBytes.count else {
throw ParseError.unexpectedEndOfData
}
for i in 0..<expectedLength {
if moduleBytes[baseOffset + i] != expected[i] {
throw ParseError.invalidMagicNumber
}
}
offset += expectedLength
}
}
enum ParseError: Error {
case invalidBufferSource
case unexpectedEndOfData
case invalidMagicNumber
case invalidVersion
case unknownImportDescriptorType(UInt8)
case unknownTableElementType(UInt8)
case unknownValueType(UInt8)
case invalidFunctionTypeForm(UInt8)
case integerOverflow
case invalidUTF8
}
/// Parse a WebAssembly module bytes and return the imports entries.
/// - Parameter moduleBytes: The WebAssembly module bytes
/// - Returns: Array of import entries
/// - Throws: ParseError if the module bytes are invalid
func parseImports(moduleBytes: Data) throws -> [ImportEntry] {
let parseState = ParseState(moduleBytes: moduleBytes)
try parseMagicNumber(parseState)
try parseVersion(parseState)
var types: [FunctionType] = []
var imports: [ImportEntry] = []
while parseState.hasMoreBytes() {
let sectionId = try parseState.readByte()
let sectionSize = try parseState.readUnsignedLEB128()
switch sectionId {
case 1: // Type section
let typeCount = try parseState.readUnsignedLEB128()
for _ in 0..<typeCount {
types.append(try parseFunctionType(parseState))
}
case 2: // Import section
let importCount = try parseState.readUnsignedLEB128()
for _ in 0..<importCount {
let module = try parseState.readName()
let name = try parseState.readName()
let type = try parseState.readByte()
switch type {
case 0x00: // Function
let index = try parseState.readUnsignedLEB128()
guard index < UInt32(types.count) else {
throw ParseError.unexpectedEndOfData
}
imports.append(ImportEntry(module: module, name: name, kind: .function(type: types[Int(index)])))
case 0x01: // Table
let tableType = try parseTableType(parseState)
imports.append(ImportEntry(module: module, name: name, kind: .table(type: tableType)))
case 0x02: // Memory
let limits = try parseLimits(parseState)
imports.append(ImportEntry(module: module, name: name, kind: .memory(type: limits)))
case 0x03: // Global
let globalType = try parseGlobalType(parseState)
imports.append(ImportEntry(module: module, name: name, kind: .global(type: globalType)))
default:
throw ParseError.unknownImportDescriptorType(type)
}
}
// Skip the rest of the module
return imports
default: // Other sections
try parseState.skipBytes(Int(sectionSize))
}
}
return []
}
private func parseMagicNumber(_ parseState: ParseState) throws {
let expected: [UInt8] = [0x00, 0x61, 0x73, 0x6D]
try parseState.assertBytes(expected)
}
private func parseVersion(_ parseState: ParseState) throws {
let expected: [UInt8] = [0x01, 0x00, 0x00, 0x00]
try parseState.assertBytes(expected)
}
private func parseTableType(_ parseState: ParseState) throws -> TableType {
let elementType = try parseState.readByte()
let element: TableType.ElementType
switch elementType {
case 0x70:
element = .funcref
case 0x6F:
element = .externref
default:
throw ParseError.unknownTableElementType(elementType)
}
let limits = try parseLimits(parseState)
return TableType(element: element, minimum: limits.minimum, maximum: limits.maximum)
}
private func parseLimits(_ parseState: ParseState) throws -> MemoryType {
let flags = try parseState.readByte()
let minimum = try parseState.readUnsignedLEB128()
let hasMaximum = (flags & 1) != 0
let shared = (flags & 2) != 0
let isMemory64 = (flags & 4) != 0
let index: MemoryType.IndexType = isMemory64 ? .i64 : .i32
if hasMaximum {
let maximum = try parseState.readUnsignedLEB128()
return MemoryType(minimum: minimum, maximum: maximum, shared: shared, index: index)
} else {
return MemoryType(minimum: minimum, maximum: nil, shared: shared, index: index)
}
}
private func parseGlobalType(_ parseState: ParseState) throws -> GlobalType {
let value = try parseValueType(parseState)
let mutable = try parseState.readByte() == 1
return GlobalType(value: value, mutable: mutable)
}
private func parseValueType(_ parseState: ParseState) throws -> ValueType {
let type = try parseState.readByte()
switch type {
case 0x7F:
return .i32
case 0x7E:
return .i64
case 0x7D:
return .f32
case 0x7C:
return .f64
case 0x70:
return .funcref
case 0x6F:
return .externref
case 0x7B:
return .v128
default:
throw ParseError.unknownValueType(type)
}
}
private func parseFunctionType(_ parseState: ParseState) throws -> FunctionType {
let form = try parseState.readByte()
if form != 0x60 {
throw ParseError.invalidFunctionTypeForm(form)
}
var parameters: [ValueType] = []
let parameterCount = try parseState.readUnsignedLEB128()
for _ in 0..<parameterCount {
parameters.append(try parseValueType(parseState))
}
var results: [ValueType] = []
let resultCount = try parseState.readUnsignedLEB128()
for _ in 0..<resultCount {
results.append(try parseValueType(parseState))
}
return FunctionType(parameters: parameters, results: results)
}