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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
|
package wasm
// EH integration tests for the gonix WASM host.
//
// These tests load wasm-eh-tests.wasm — a minimal C++ binary with no Lix
// dependency — and call each eh_test_* function via the full host EH stack
// (invoke_*, __cxa_*, setThrew, etc.).
//
// Build the test binary first:
//
// meson compile -C ../../build-wasm wasm-eh-tests.wasm
//
// Run:
//
// go test ./wasm/ -run TestEH_ -v
import (
"context"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/nixos/lix/gonix/store"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)
// ehTestWASMPath returns the path to wasm-eh-tests.wasm, relative to this
// source file. Returns "" if the file does not exist.
func ehTestWASMPath() string {
_, thisFile, _, _ := runtime.Caller(0)
// thisFile = .../gonix/wasm/eh_test.go
// WASM is at .../build-wasm/lix/wasm-eh-tests.wasm
dir := filepath.Dir(filepath.Dir(filepath.Dir(thisFile)))
p := filepath.Join(dir, "build-wasm", "lix", "wasm-eh-tests.wasm")
if _, err := os.Stat(p); err != nil {
return ""
}
return p
}
// ehRuntime holds the wazero runtime and instantiated wasm-eh-tests module.
type ehRuntime struct {
rt *Runtime
mod api.Module
ctx context.Context
}
// newEHTestRuntime loads wasm-eh-tests.wasm and wires up the env/wasi host
// modules (same EH stack as the real evaluator, but no lix_store / nix_init).
func newEHTestRuntime(t *testing.T) *ehRuntime {
t.Helper()
wasmPath := ehTestWASMPath()
if wasmPath == "" {
t.Skip("wasm-eh-tests.wasm not built — run: meson compile -C build-wasm wasm-eh-tests.wasm")
}
wasmBytes, err := os.ReadFile(wasmPath)
if err != nil {
t.Fatalf("read wasm-eh-tests.wasm: %v", err)
}
ctx := context.Background()
rc := wazero.NewRuntimeConfigInterpreter().
WithCoreFeatures(api.CoreFeaturesV2).
WithDebugInfoEnabled(true)
r := wazero.NewRuntimeWithConfig(ctx, rc)
t.Cleanup(func() { r.Close(ctx) })
if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil {
t.Fatalf("wasi: %v", err)
}
// Build a Runtime shell — enough to host instantiateEnv.
rt := &Runtime{
r: r,
store: &store.StubStore{},
nixConfig: "",
}
compiled, err := r.CompileModule(ctx, wasmBytes)
if err != nil {
t.Fatalf("compile: %v", err)
}
hostTableEntries, err := parseHostTableEntries(wasmBytes, compiled)
if err != nil {
t.Fatalf("parseHostTableEntries: %v", err)
}
rt.hostTableEntries = hostTableEntries
if err := rt.instantiateEnv(ctx, compiled); err != nil {
t.Fatalf("instantiateEnv: %v", err)
}
// wasm-eh-tests.wasm does not import lix_store, but wazero requires all
// imports to be satisfied. Register a stub if the module asks for it.
hasLixStore := false
for _, fn := range compiled.ImportedFunctions() {
mod, _, isImport := fn.Import()
if isImport && mod == "lix_store" {
hasLixStore = true
break
}
}
if hasLixStore {
if err := rt.instantiateLixStore(ctx); err != nil {
t.Fatalf("instantiateLixStore: %v", err)
}
}
cfg := wazero.NewModuleConfig().
WithName("wasm-eh-tests").
WithStdout(os.Stdout).
WithStderr(os.Stderr).
WithStartFunctions()
mod, err := r.InstantiateModule(ctx, compiled, cfg)
if err != nil {
t.Fatalf("instantiate wasm-eh-tests: %v", err)
}
rt.mod = mod
// _initialize runs global constructors (may be absent in this tiny binary).
if initFn := mod.ExportedFunction("_initialize"); initFn != nil {
if _, err := initFn.Call(ctx); err != nil {
t.Fatalf("_initialize: %v", err)
}
}
// Cache malloc/free for buffer allocation.
rt.fnMalloc = mod.ExportedFunction("malloc")
rt.fnFree = mod.ExportedFunction("free")
return &ehRuntime{rt: rt, mod: mod, ctx: ctx}
}
// callEHTest calls eh_test_NAME(bufPtr, 256) and returns (retval, bufString).
// bufString is only meaningful when retval == 0.
func (e *ehRuntime) callEHTest(t *testing.T, name string) (int32, string) {
t.Helper()
fn := e.mod.ExportedFunction(name)
if fn == nil {
t.Fatalf("exported function %q not found in wasm-eh-tests.wasm", name)
}
const bufMax = 256
bufPtr, err := e.rt.malloc(e.ctx, bufMax)
if err != nil {
t.Fatalf("malloc: %v", err)
}
defer e.rt.freePtr(e.ctx, bufPtr)
// Zero the buffer so we get a clean string even if the function writes nothing.
e.mod.Memory().Write(bufPtr, make([]byte, bufMax))
res, callErr := fn.Call(e.ctx, uint64(bufPtr), bufMax)
if callErr != nil {
// A wazero error (trap / unreachable) — report it but don't fail here;
// some tests (dtor_throw) expect this.
return -2, callErr.Error()
}
retval := int32(res[0])
// Read buf as null-terminated string.
raw, ok := e.mod.Memory().Read(bufPtr, bufMax)
if !ok {
t.Fatalf("memory read failed")
}
s := string(raw)
if i := strings.IndexByte(s, 0); i >= 0 {
s = s[:i]
}
return retval, s
}
// ---------------------------------------------------------------------------
// Tests — in priority order from the plan.
// ---------------------------------------------------------------------------
// 1. Basic throw/catch.
func TestEH_Simple(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_simple")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "caught: simple error" {
t.Fatalf("expected buf=%q, got %q", "caught: simple error", buf)
}
}
// 2. throw / catch / throw; / outer catch.
func TestEH_Rethrow(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_rethrow")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "outer caught: rethrown" {
t.Fatalf("expected buf=%q, got %q", "outer caught: rethrown", buf)
}
}
// 3. throw Derived / catch Base& — exercises __cxa_can_catch.
func TestEH_CatchHierarchy(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_catch_hierarchy")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "base caught: derived error" {
t.Fatalf("expected buf=%q, got %q", "base caught: derived error", buf)
}
}
// 4. std::current_exception / std::rethrow_exception — the critical failing case.
func TestEH_ExceptionPtr(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_exception_ptr")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "rethrown: captured error" {
t.Fatalf("expected buf=%q, got %q", "rethrown: captured error", buf)
}
}
// 5. Multiple catch clauses — correct one selected.
func TestEH_MultiCatch(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_multi_catch")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "matched: Other" {
t.Fatalf("expected buf=%q, got %q", "matched: Other", buf)
}
}
// 6. Nested try blocks — inner catches, outer never fires.
func TestEH_NestedTry(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_nested_try")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "inner caught" {
t.Fatalf("expected buf=%q, got %q", "inner caught", buf)
}
}
// 7. Exception state cleanup between calls.
func TestEH_CatchAndResume(t *testing.T) {
e := newEHTestRuntime(t)
// First call: exception path.
retval, buf := e.callEHTest(t, "eh_test_catch_and_resume")
if retval != 0 {
t.Fatalf("call 1: expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "exception handled" {
t.Fatalf("call 1: expected buf=%q, got %q", "exception handled", buf)
}
// Second call: no exception — verifies EH state was fully cleaned up.
retval, buf = e.callEHTest(t, "eh_test_catch_and_resume")
if retval != 0 {
t.Fatalf("call 2: expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "no exception" {
t.Fatalf("call 2: expected buf=%q, got %q", "no exception", buf)
}
}
// 9. Exception propagates through a frame with no catch block.
// After this test the runtime must NOT have fatalErr set — the rethrow chain
// must be classified as a normal EH throw, not a fatal trap.
// We verify by making a second successful call on the same runtime.
// Emscripten emits find_matching_catch_2 + resumeException + unreachable in
// the middle frame. __resumeException must panic to prevent the unreachable
// from firing.
func TestEH_PropagateThroughNoCatch(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_propagate_through")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "caught after propagate: propagated" {
t.Fatalf("expected buf=%q, got %q", "caught after propagate: propagated", buf)
}
}
// 10. exception_ptr capture → rethrow_exception → catch(T&){throw;} chain.
// Mirrors writeDerivation→blockOn→derivationStrictInternal exactly.
func TestEH_ExceptionPtrRethrowChain(t *testing.T) {
e := newEHTestRuntime(t)
retval, buf := e.callEHTest(t, "eh_test_exception_ptr_rethrow_chain")
if retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "chained: propagated" {
t.Fatalf("expected buf=%q, got %q", "chained: propagated", buf)
}
}
// 11. Same runtime: rethrow chain followed by a simple call.
// After a normal exception+rethrow chain the runtime must NOT have fatalErr
// set — the fatal-trap heuristic must not misclassify __cxa_rethrow /
// __resumeException as fatal traps just because g_exceptionLast didn't change.
func TestEH_ExceptionPtrRethrowChainThenSucceed(t *testing.T) {
e := newEHTestRuntime(t)
// Call 1: full rethrow chain (exercises __resumeException + __cxa_rethrow
// with an already-set g_exceptionLast).
retval, buf := e.callEHTest(t, "eh_test_exception_ptr_rethrow_chain")
if retval != 0 {
t.Fatalf("call 1: expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "chained: propagated" {
t.Fatalf("call 1: expected buf=%q, got %q", "chained: propagated", buf)
}
// The rethrow chain must not have poisoned fatalErr.
if e.rt.HasFatalError() {
t.Fatalf("fatalErr set after normal rethrow chain — fatal-trap heuristic misfire")
}
// Call 2: simple throw/catch on the same runtime — must work cleanly.
retval, buf = e.callEHTest(t, "eh_test_simple")
if retval != 0 {
t.Fatalf("call 2: expected retval=0, got %d (buf=%q)", retval, buf)
}
if buf != "caught: simple error" {
t.Fatalf("call 2: expected buf=%q, got %q", "caught: simple error", buf)
}
}
// 11. __cxa_end_catch must not leak exceptionLast across nested rethrows.
//
// Mirrors the real derivation-eval hang: throw → catch(...){capture ptr} →
// rethrow_exception → catch(T&){throw;} → catch(T&){throw;} → outermost catch.
//
// If __cxa_end_catch unconditionally zeros g_exceptionLast (the bug), each
// catch/rethrow cycle adds an entry to g_exceptionCaught without the previous
// entry ever being cleared, growing the stack without bound. The 20-iteration
// loop never terminates — the test fails with the 5s timeout.
//
// After the fix (only zero exceptionLast when the stack is fully empty), the
// catch stack is clean after each iteration and the loop completes promptly.
func TestEH_UncaughtDepthStable(t *testing.T) {
e := newEHTestRuntime(t)
type result struct {
retval int32
buf string
}
done := make(chan result, 1)
go func() {
retval, buf := e.callEHTest(t, "eh_test_uncaught_depth_stable")
done <- result{retval, buf}
}()
select {
case r := <-done:
if r.retval != 0 {
t.Fatalf("expected retval=0, got %d (buf=%q)", r.retval, r.buf)
}
if r.buf != "stable" {
t.Fatalf("expected buf=%q, got %q", "stable", r.buf)
}
if e.rt.HasFatalError() {
t.Fatalf("fatalErr set after stable rethrow chain — should not happen")
}
// The catch stack must be fully unwound: every begin_catch must be
// balanced by an end_catch. A non-zero depth means __cxa_rethrow_primary_exception
// leaked an entry that __cxa_end_catch never cleaned up.
if depth := EHCatchDepth(); depth != 0 {
t.Fatalf("g_exceptionCaught depth=%d after fully-handled exception chain — expected 0 (__cxa_rethrow_primary_exception leak)", depth)
}
case <-time.After(5 * time.Second):
t.Fatal("eh_test_uncaught_depth_stable hung for >5s — __cxa_end_catch exceptionLast leak")
}
}
// 8. Destructor throws during unwind.
//
// In native C++, std::terminate fires when a destructor throws while another
// exception is active. Emscripten+WASM does not replicate this behaviour —
// the destructor's throw may be caught by the surrounding catch(...) instead.
//
// The test therefore does NOT assert a specific return value. It asserts only
// that the call returns within 5 seconds (no infinite loop) and does not
// return the impossible success value of 0 with "survived" text that would
// indicate the WASM continued past where terminate should have fired.
func TestEH_DtorThrow(t *testing.T) {
e := newEHTestRuntime(t)
done := make(chan struct {
retval int32
buf string
}, 1)
go func() {
retval, buf := e.callEHTest(t, "eh_test_dtor_throw")
done <- struct {
retval int32
buf string
}{retval, buf}
}()
select {
case result := <-done:
t.Logf("eh_test_dtor_throw returned retval=%d buf=%q", result.retval, result.buf)
// retval=0 would mean "survived" which is logically impossible —
// the function only returns 0 if the catch block exits cleanly, but
// the C++ code after the try/catch writes "survived (unexpected)" and
// returns -1. A trap (-2) or -1 are both acceptable outcomes.
if result.retval == 0 {
t.Fatalf("eh_test_dtor_throw returned 0 — impossible code path reached")
}
case <-time.After(5 * time.Second):
t.Fatal("eh_test_dtor_throw hung for >5s — host is looping on std::terminate")
}
}
|