Skip to content

Commit 19cfaf9

Browse files
Test backtrace attached to Trap
1 parent 43f28eb commit 19cfaf9

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

Sources/WasmKit/Execution/NameRegistry.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,13 @@ struct NameRegistry {
1919
registry.register(instance: instance, nameMap: nameMap)
2020
}
2121
}
22+
23+
for (name, entry) in instance.exports {
24+
// Use exported name if the function doesn't have name in name section.
25+
guard case .function(let function) = entry else { continue }
26+
guard registry.functionNames[function] == nil else { continue }
27+
registry.functionNames[function] = name
28+
}
2229
}
2330
}
2431

@@ -48,7 +55,7 @@ struct NameRegistry {
4855
}
4956
// Fallback
5057
if function.isWasm {
51-
return "function[\(function.wasm.index)]"
58+
return "wasm function[\(function.wasm.index)]"
5259
} else {
5360
return "unknown host function"
5461
}

Tests/WATTests/EncoderTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ class EncoderTests: XCTestCase {
147147
""",
148148
options: EncodeOptions(nameSection: true)
149149
)
150-
150+
151151
var parser = WasmParser.Parser(bytes: bytes)
152152
var customSections: [CustomSection] = []
153153
while let payload = try parser.parseNext() {

Tests/WasmKitTests/ExecutionTests.swift

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,49 @@ final class ExecutionTests: XCTestCase {
5151
let results = try _start()
5252
XCTAssertEqual(results, [.i32(42)])
5353
}
54+
55+
func testBacktrace() throws {
56+
let module = try parseWasm(
57+
bytes: wat2wasm(
58+
"""
59+
(module
60+
(memory (export "memory") 1)
61+
(func $foo (result i32)
62+
unreachable
63+
)
64+
(func $bar (result i32)
65+
(call $foo)
66+
)
67+
(func (export "_start")
68+
(call $bar)
69+
(drop)
70+
)
71+
)
72+
""",
73+
options: EncodeOptions(nameSection: true)
74+
)
75+
)
76+
77+
let engine = Engine()
78+
let store = Store(engine: engine)
79+
let instance = try module.instantiate(store: store)
80+
let _start = try XCTUnwrap(instance.exports[function: "_start"])
81+
82+
let trap: Trap
83+
do {
84+
try _start()
85+
XCTFail("expect unreachable trap")
86+
return
87+
} catch let error {
88+
trap = try XCTUnwrap(error as? Trap)
89+
}
90+
91+
XCTAssertEqual(
92+
trap.backtrace?.symbols.compactMap(\.?.name),
93+
[
94+
"foo",
95+
"bar",
96+
"_start",
97+
])
98+
}
5499
}

0 commit comments

Comments
 (0)