File: Runtime.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 (217 lines) | stat: -rw-r--r-- 8,467 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
/// A container to manage execution state of one or more module instances.
public final class Runtime {
    public let store: Store
    let interceptor: RuntimeInterceptor?

    /// Initializes a new instant of a WebAssembly interpreter runtime.
    /// - Parameter hostModules: Host module names mapped to their corresponding ``HostModule`` definitions.
    public init(hostModules: [String: HostModule] = [:], interceptor: RuntimeInterceptor? = nil) {
        store = Store(hostModules)
        self.interceptor = interceptor
    }
}

public protocol RuntimeInterceptor {
    func onEnterFunction(_ address: FunctionAddress, store: Store)
    func onExitFunction(_ address: FunctionAddress, store: Store)
}

extension Runtime {
    public func instantiate(module: Module, name: String? = nil) throws -> ModuleInstance {
        let instance = try instantiate(module: module, externalValues: store.getExternalValues(module))

        if let name {
            store.namedModuleInstances[name] = instance
        }

        return instance
    }

    /// > Note:
    /// <https://webassembly.github.io/spec/core/exec/modules.html#instantiation>
    func instantiate(module: Module, externalValues: [ExternalValue]) throws -> ModuleInstance {
        // Step 3 of instantiation algorithm, according to Wasm 2.0 spec.
        guard module.imports.count == externalValues.count else {
            throw InstantiationError.importsAndExternalValuesMismatch
        }

        // Step 4.
        let isValid = zip(module.imports, externalValues).map { i, e -> Bool in
            switch (i.descriptor, e) {
            case (.function, .function),
                (.table, .table),
                (.memory, .memory),
                (.global, .global):
                return true
            default: return false
            }
        }.reduce(true) { $0 && $1 }

        guard isValid else {
            throw InstantiationError.importsAndExternalValuesMismatch
        }

        // Steps 5-8.
        let initialGlobals = try evaluateGlobals(module: module, externalValues: externalValues)

        // Step 9.
        // Process `elem.init` evaluation during allocation

        // Step 11.
        let instance = store.allocate(
            module: module,
            externalValues: externalValues,
            initialGlobals: initialGlobals
        )

        // Step 12-13.

        // Steps 14-15.
        do {
            for (elementIndex, element) in module.elements.enumerated() {
                let elementIndex = UInt32(elementIndex)
                switch element.mode {
                case let .active(tableIndex, offsetExpression):
                    let initIseq = InstructionSequence(instructions: offsetExpression + [
                        .numericConst(.i32(0)),
                        .numericConst(.i32(UInt32(element.initializer.count))),
                        .tableInit(tableIndex, elementIndex),
                        .tableElementDrop(elementIndex),
                    ])
                    defer { initIseq.deallocate() }
                    try evaluateConstExpr(initIseq, instance: instance)

                case .declarative:
                    let initIseq: InstructionSequence = [.tableElementDrop(elementIndex)]
                    defer { initIseq.deallocate() }
                    try evaluateConstExpr(initIseq, instance: instance)

                case .passive:
                    continue
                }
            }
        } catch Trap.undefinedElement, Trap.tableSizeOverflow, Trap.outOfBoundsTableAccess {
            throw InstantiationError.outOfBoundsTableAccess
        } catch {
            throw error
        }

        // Step 16.
        do {
            for case let (dataIndex, .active(data)) in module.data.enumerated() {
                assert(data.index == 0)
                let iseq = InstructionSequence(instructions: data.offset + [
                    .numericConst(.i32(0)),
                    .numericConst(.i32(UInt32(data.initializer.count))),
                    .memoryInit(UInt32(dataIndex)),
                    .memoryDataDrop(UInt32(dataIndex)),
                ])
                defer { iseq.deallocate() }
                try evaluateConstExpr(iseq, instance: instance)
            }
        } catch Trap.outOfBoundsMemoryAccess {
            throw InstantiationError.outOfBoundsMemoryAccess
        } catch {
            throw error
        }

        // Step 17.
        if let startIndex = module.start {
            try withExecution { initExecution in
                try initExecution.invoke(functionAddress: instance.functionAddresses[Int(startIndex)], runtime: self)
                try initExecution.run(runtime: self)
            }
        }

        return instance
    }

    private func evaluateGlobals(module: Module, externalValues: [ExternalValue]) throws -> [Value] {
        try store.withTemporaryModuleInstance { globalModuleInstance in
            for externalValue in externalValues {
                switch externalValue {
                case let .global(address):
                    globalModuleInstance.globalAddresses.append(address)
                case let .function(address):
                    globalModuleInstance.functionAddresses.append(address.address)
                default:
                    continue
                }
            }
            
            globalModuleInstance.types = module.types
            
            for function in module.functions {
                let address = store.allocate(function: function, module: globalModuleInstance)
                globalModuleInstance.functionAddresses.append(address)
            }
            
            let globalInitializers = try module.globals.map { global in
                let iseq = InstructionSequence(instructions: global.initializer)
                defer { iseq.deallocate() }
                return try evaluateConstExpr(iseq, instance: globalModuleInstance, arity: 1) { initExecution in
                    return initExecution.stack.popValue()
                }
            }
            
            return globalInitializers
        }
    }

    func evaluateConstExpr(_ iseq: InstructionSequence, instance: ModuleInstance, arity: Int = 0) throws {
        try evaluateConstExpr(iseq, instance: instance, arity: arity, body: { _ in })
    }

    func evaluateConstExpr<T>(
        _ iseq: InstructionSequence,
        instance: ModuleInstance,
        arity: Int = 0,
        body: (inout ExecutionState) throws -> T
    ) throws -> T {
        try withExecution { initExecution in
            try initExecution.stack.pushFrame(
                iseq: iseq,
                arity: arity,
                module: instance.selfAddress,
                argc: 0,
                defaultLocals: nil,
                returnPC: initExecution.programCounter + 1
            )
            initExecution.programCounter = iseq.baseAddress
            try initExecution.run(runtime: self)
            return try body(&initExecution)
        }
    }
}

extension Runtime {
    @available(*, unavailable, message: "Runtime doesn't manage execution state anymore. Use ExecutionState.step instead")
    public func step() throws {
        fatalError()
    }

    @available(*, unavailable, message: "Runtime doesn't manage execution state anymore. Use ExecutionState.step instead")
    public func run() throws {
        fatalError()
    }

    public func getGlobal(_ moduleInstance: ModuleInstance, globalName: String) throws -> Value {
        guard case let .global(address) = moduleInstance.exportInstances.first(where: { $0.name == globalName })?.value else {
            throw Trap._raw("no global export with name \(globalName) in a module instance \(moduleInstance)")
        }

        return store.globals[address].value
    }

    public func invoke(_ moduleInstance: ModuleInstance, function: String, with arguments: [Value] = []) throws -> [Value] {
        guard case let .function(function)? = moduleInstance.exports[function] else {
            throw Trap.exportedFunctionNotFound(moduleInstance, name: function)
        }
        return try function.invoke(arguments, runtime: self)
    }

    /// Invokes a function of the given address with the given parameters.
    public func invoke(_ address: FunctionAddress, with parameters: [Value] = []) throws -> [Value] {
        try Function(address: address).invoke(parameters, runtime: self)
    }
}