|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2024 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See http://swift.org/LICENSE.txt for license information |
| 9 | +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +#if !os(macOS) |
| 14 | + |
| 15 | +import Foundation |
| 16 | +import WasmKit |
| 17 | +import WASI |
| 18 | + |
| 19 | +typealias DefaultWasmPlugin = WasmKitPlugin |
| 20 | + |
| 21 | +struct WasmKitMacroRunner: WasmPlugin { |
| 22 | + let instance: ModuleInstance |
| 23 | + let runtime: Runtime |
| 24 | + |
| 25 | + init(wasm: Data) throws { |
| 26 | + let module = try parseWasm(bytes: Array(wasm)) |
| 27 | + let bridge = try WASIBridgeToHost() |
| 28 | + runtime = Runtime(hostModules: bridge.hostModules) |
| 29 | + instance = try runtime.instantiate(module: module) |
| 30 | + _ = try bridge.start(instance, runtime: runtime) |
| 31 | + } |
| 32 | + |
| 33 | + func handleMessage(_ json: Data) throws -> Data { |
| 34 | + let exports = instance.exports |
| 35 | + guard case let .memory(memoryAddr) = exports["memory"] else { fatalError("bad memory") } |
| 36 | + guard case let .function(malloc) = exports["wacro_malloc"] else { fatalError("bad wacro_malloc") } |
| 37 | + guard case let .function(parse) = exports["wacro_parse"] else { fatalError("bad wacro_parse") } |
| 38 | + guard case let .function(free) = exports["wacro_free"] else { fatalError("bad wacro_free") } |
| 39 | + |
| 40 | + let inAddr = try malloc.invoke([.i32(UInt32(json.count))], runtime: runtime)[0].i32 |
| 41 | + |
| 42 | + runtime.store.withMemory(at: memoryAddr) { mem in |
| 43 | + mem.data.replaceSubrange(Int(inAddr)..<(Int(inAddr) + json.count), with: json) |
| 44 | + } |
| 45 | + |
| 46 | + let outAddr = try parse.invoke([.i32(inAddr), .i32(UInt32(json.count))], runtime: runtime)[0].i32 |
| 47 | + let out = runtime.store.withMemory(at: memoryAddr) { mem in |
| 48 | + let bytes = Array(mem.data[Int(outAddr)..<(Int(outAddr) + 4)]) |
| 49 | + let len = |
| 50 | + (UInt32(bytes[0]) << 0) | |
| 51 | + (UInt32(bytes[1]) << 8) | |
| 52 | + (UInt32(bytes[2]) << 16) | |
| 53 | + (UInt32(bytes[3]) << 24) |
| 54 | + return Data(mem.data[(Int(outAddr) + 4)...].prefix(Int(len))) |
| 55 | + } |
| 56 | + |
| 57 | + _ = try free.invoke([.i32(outAddr)], runtime: runtime) |
| 58 | + |
| 59 | + return out |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +#endif |
0 commit comments