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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// wasm-eh-tests.cc — standalone C++ EH test functions for the gonix WASM host.
//
// No Lix dependency. Compiled to wasm-eh-tests.wasm with Emscripten -fexceptions.
// Each function has the signature:
//   extern "C" int32_t eh_test_NAME(char* buf, int32_t max);
// Returns 0 on success (buf may contain a result string for assertion),
// -1 on failure (buf contains a null-terminated error message).
//
// IMPORTANT: every throw must be in a *called* function, not directly in the
// try body.  Emscripten only emits invoke_* wrappers for call sites, not for
// inline throws.  Each test therefore has a [[noreturn]] helper that does the
// actual throw so the compiler wraps the call in invoke_*.

#include <cstdint>
#include <cstdio>
#include <cstring>
#include <exception>
#include <stdexcept>

// ---------------------------------------------------------------------------
// Type hierarchy
// ---------------------------------------------------------------------------

struct Base : public std::exception
{
    const char * what() const noexcept override
    {
        return "base error";
    }
};

struct Derived : public Base
{
    const char * what() const noexcept override
    {
        return "derived error";
    }
};

struct Other : public std::exception
{
    const char * what() const noexcept override
    {
        return "other error";
    }
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

static int32_t write_buf(char * buf, int32_t max, const char * msg)
{
    int32_t n = static_cast<int32_t>(strlen(msg));
    if (n >= max) {
        n = max - 1;
    }
    memcpy(buf, msg, n);
    buf[n] = '\0';
    return n;
}

// ---------------------------------------------------------------------------
// Throw helpers — each must be in a separate function so Emscripten wraps the
// call site in invoke_*.  Mark [[noreturn]] so the compiler knows they throw.
// ---------------------------------------------------------------------------

[[noreturn]]
static void throw_runtime_error(const char * msg)
{
    throw std::runtime_error(msg);
}

[[noreturn]]
static void throw_derived()
{
    throw Derived();
}

[[noreturn]]
static void throw_runtime_error_rethrow()
{
    throw std::runtime_error("rethrown");
}

// rethrow_current() wraps bare `throw;` in a callee so the compiler emits
// invoke_* at the call site in the surrounding catch block.
[[noreturn]]
static void rethrow_current()
{
    throw;
}

[[noreturn]]
static void throw_for_exception_ptr()
{
    throw std::runtime_error("captured error");
}

[[noreturn]]
static void throw_for_nested()
{
    throw std::runtime_error("inner error");
}

[[noreturn]]
static void throw_for_multi()
{
    throw Other();
}

[[noreturn]]
static void throw_for_resume()
{
    throw std::runtime_error("transient error");
}

// ---------------------------------------------------------------------------
// 1. eh_test_simple — basic throw / catch
// ---------------------------------------------------------------------------

extern "C" int32_t eh_test_simple(char * buf, int32_t max)
{
    try {
        throw_runtime_error("simple error");
    } catch (const std::runtime_error & e) {
        char tmp[256];
        snprintf(tmp, sizeof(tmp), "caught: %s", e.what());
        write_buf(buf, max, tmp);
        return 0;
    }
    write_buf(buf, max, "no exception caught");
    return -1;
}

// ---------------------------------------------------------------------------
// 2. eh_test_rethrow — throw / catch / throw; / outer catch
// ---------------------------------------------------------------------------

extern "C" int32_t eh_test_rethrow(char * buf, int32_t max)
{
    try {
        try {
            throw_runtime_error_rethrow();
        } catch (const std::runtime_error &) {
            rethrow_current(); // bare throw; in a callee so compiler emits invoke_*
        }
    } catch (const std::runtime_error & e) {
        char tmp[256];
        snprintf(tmp, sizeof(tmp), "outer caught: %s", e.what());
        write_buf(buf, max, tmp);
        return 0;
    }
    write_buf(buf, max, "no exception caught");
    return -1;
}

// ---------------------------------------------------------------------------
// 3. eh_test_catch_hierarchy — throw Derived / catch Base& (__cxa_can_catch)
// ---------------------------------------------------------------------------

extern "C" int32_t eh_test_catch_hierarchy(char * buf, int32_t max)
{
    try {
        throw_derived();
    } catch (const Base & e) {
        char tmp[256];
        snprintf(tmp, sizeof(tmp), "base caught: %s", e.what());
        write_buf(buf, max, tmp);
        return 0;
    }
    write_buf(buf, max, "no exception caught");
    return -1;
}

// ---------------------------------------------------------------------------
// 4. eh_test_nested_try — nested try blocks; inner catches; outer never fires
// ---------------------------------------------------------------------------

extern "C" int32_t eh_test_nested_try(char * buf, int32_t max)
{
    bool outer_fired = false;
    try {
        try {
            throw_for_nested();
        } catch (const std::runtime_error &) {
            write_buf(buf, max, "inner caught");
            // handled — do not rethrow
        }
    } catch (...) {
        outer_fired = true;
    }
    if (outer_fired) {
        write_buf(buf, max, "outer fired unexpectedly");
        return -1;
    }
    return 0;
}

// ---------------------------------------------------------------------------
// 5. eh_test_exception_ptr — std::current_exception / std::rethrow_exception
//    This is the exact pattern that caused std::terminate in derivation eval.
// ---------------------------------------------------------------------------

extern "C" int32_t eh_test_exception_ptr(char * buf, int32_t max)
{
    std::exception_ptr captured;

    // Capture inside catch
    try {
        throw_for_exception_ptr();
    } catch (...) {
        captured = std::current_exception();
    }

    // Rethrow outside the original catch block
    if (captured) {
        try {
            std::rethrow_exception(captured);
        } catch (const std::runtime_error & e) {
            char tmp[256];
            snprintf(tmp, sizeof(tmp), "rethrown: %s", e.what());
            write_buf(buf, max, tmp);
            return 0;
        }
    }

    write_buf(buf, max, "exception_ptr was null");
    return -1;
}

// ---------------------------------------------------------------------------
// 6. eh_test_dtor_throw — destructor throws while another exception is active.
//    std::terminate() is called by the C++ runtime.  Our host must not loop.
// ---------------------------------------------------------------------------

struct ThrowingDtor
{
    ~ThrowingDtor() noexcept(false)
    {
        throw std::runtime_error("dtor threw");
    }
};

[[noreturn]]
static void throw_with_dtor()
{
    ThrowingDtor td;
    throw std::runtime_error("outer throw");
}

extern "C" int32_t eh_test_dtor_throw(char * buf, int32_t max)
{
    try {
        throw_with_dtor();
    } catch (...) {
    }
    // Should not reach here — std::terminate fires first.
    write_buf(buf, max, "survived (unexpected)");
    return -1;
}

// ---------------------------------------------------------------------------
// 7. eh_test_multi_catch — multiple catch clauses; correct one selected
// ---------------------------------------------------------------------------

extern "C" int32_t eh_test_multi_catch(char * buf, int32_t max)
{
    try {
        throw_for_multi();
    } catch (const std::runtime_error &) {
        write_buf(buf, max, "matched: runtime_error (wrong)");
        return -1;
    } catch (const Base &) {
        write_buf(buf, max, "matched: Base (wrong)");
        return -1;
    } catch (const Other &) {
        write_buf(buf, max, "matched: Other");
        return 0;
    } catch (...) {
        write_buf(buf, max, "matched: catch-all (wrong)");
        return -1;
    }
    write_buf(buf, max, "no exception caught");
    return -1;
}

// ---------------------------------------------------------------------------
// 9. eh_test_propagate_through — exception propagates through a frame with no
//    catch block.  Emscripten emits find_matching_catch_2 + resumeException +
//    unreachable in the middle frame.  The host's __resumeException must panic
//    (never return) for the enclosing invoke_* to catch it and set setThrew.
//
//    middle_no_catch: no try/catch — just calls throw_runtime_error.
//    Emscripten codegen for middle_no_catch:
//      invoke_*(slot_of_throw_runtime_error, "propagated")
//      ; if threw:
//      call __cxa_find_matching_catch_2()   ; no typed clauses
//      call __resumeException(thrown)       ; re-raises — must never return
//      unreachable
// ---------------------------------------------------------------------------

// No catch — exception propagates up through this frame.
// [[noinline]] is critical: without it Emscripten inlines this into the outer
// function and the resumeException+unreachable pattern never appears.
[[gnu::noinline]]
static int32_t middle_no_catch(char * buf, int32_t max)
{
    throw_runtime_error("propagated");
    write_buf(buf, max, "no throw (unexpected)");
    return -1;
}

extern "C" int32_t eh_test_propagate_through(char * buf, int32_t max)
{
    try {
        middle_no_catch(buf, max);
    } catch (const std::runtime_error & e) {
        char tmp[256];
        snprintf(tmp, sizeof(tmp), "caught after propagate: %s", e.what());
        write_buf(buf, max, tmp);
        return 0;
    }
    write_buf(buf, max, "no exception caught");
    return -1;
}

// ---------------------------------------------------------------------------
// 10. eh_test_exception_ptr_rethrow_chain — mirrors writeDerivation→blockOn:
//     throw → catch(...){capture ptr, end_catch} → rethrow_exception(ptr)
//     → caught by outer catch(T&){throw;} → outermost catch gets it.
//
//     This is the exact pattern in the real evaluator:
//       canonPath throws
//       writeDerivation: catch(...) { co_return result::current_exception(); }
//       blockOn / Result::value(): std::rethrow_exception(stored_ptr)
//       derivationStrictInternal: catch(Error&) { e.addTrace(...); throw; }
//       prim_derivationStrict: outermost catch
// ---------------------------------------------------------------------------

static std::exception_ptr capture_and_return()
{
    std::exception_ptr p;
    try {
        throw_runtime_error("propagated");
    } catch (...) {
        p = std::current_exception();
    }
    return p;
}

[[noreturn]]
static void rethrow_ptr(std::exception_ptr p)
{
    std::rethrow_exception(p);
}

// Middle layer: receives the rethrown exception, adds a modification, rethrows.
// Mirrors derivationStrictInternal's catch(Error&){addTrace;throw;} pattern.
// [[noinline]] prevents the compiler from collapsing the chain.
[[gnu::noinline]]
static void middle_catch_rethrow(char * buf, int32_t max)
{
    // capture in inner scope
    auto p = capture_and_return();
    // rethrow outside original catch — mirrors blockOn/Result::value()
    try {
        rethrow_ptr(p);
    } catch (std::runtime_error & e) {
        // add a "trace" by writing to buf, then rethrow — mirrors addTrace+throw
        snprintf(buf, max, "traced: %s", e.what());
        rethrow_current();
    }
}

extern "C" int32_t eh_test_exception_ptr_rethrow_chain(char * buf, int32_t max)
{
    try {
        middle_catch_rethrow(buf, max);
    } catch (const std::runtime_error & e) {
        char tmp[256];
        snprintf(tmp, sizeof(tmp), "chained: %s", e.what());
        write_buf(buf, max, tmp);
        return 0;
    }
    write_buf(buf, max, "no exception caught");
    return -1;
}

// ---------------------------------------------------------------------------
// 11. eh_test_uncaught_depth_stable — __cxa_end_catch must not leak
//     exceptionLast when there are nested rethrows.
//
//     Mirrors the real hang: canonPath throws → writeDerivation catches into
//     exception_ptr → rethrow_exception → derivationStrictInternal catch(T&){throw;}
//     → prim_derivationStrict catch(T&){throw;} → EvalState::callFunction ...
//
//     If __cxa_end_catch unconditionally zeroes g_exceptionLast (the bug),
//     subsequent __resumeException / __cxa_rethrow calls re-add entries to
//     g_exceptionCaught without the earlier entries ever being cleared,
//     growing the catch-stack without bound and looping forever.
//
//     A correct implementation completes all 20 iterations and returns "stable".
//     The buggy implementation never returns (test fails with 5s timeout).
// ---------------------------------------------------------------------------

// Captures the current exception into an exception_ptr, then returns.
// Mirrors writeDerivation's catch(...){ co_return result::current_exception(); }.
static std::exception_ptr capture_exception()
{
    std::exception_ptr p;
    try {
        throw_runtime_error("propagated");
    } catch (...) {
        p = std::current_exception();
    }
    return p;
}

// Rethrows via rethrow_exception, then catches and rethrows bare.
// Mirrors blockOn/Result::value() → derivationStrictInternal catch(T&){throw;}.
// [[noinline]] prevents the compiler from collapsing the chain.
[[gnu::noinline]]
static void rethrow_via_ptr_then_rethrow()
{
    auto p = capture_exception();
    try {
        std::rethrow_exception(p); // __cxa_rethrow_primary_exception
    } catch (std::runtime_error &) {
        rethrow_current(); // throw; — __cxa_rethrow
    }
}

// Outer layer: catches and rethrows again, like prim_derivationStrict.
// [[noinline]] ensures a separate invoke_* frame.
[[gnu::noinline]]
static void outer_catch_rethrow()
{
    try {
        rethrow_via_ptr_then_rethrow();
    } catch (std::runtime_error &) {
        rethrow_current();
    }
}

extern "C" int32_t eh_test_uncaught_depth_stable(char * buf, int32_t max)
{
    for (int i = 0; i < 20; i++) {
        try {
            outer_catch_rethrow();
        } catch (const std::runtime_error &) {
            // exception fully handled — catch stack must be empty after this
        }
    }
    write_buf(buf, max, "stable");
    return 0;
}

// ---------------------------------------------------------------------------
// 8. eh_test_catch_and_resume — state cleanup between calls
//    Call 1: throw flag set → exception handled, return 0
//    Call 2: no throw      → no exception, return 0
// ---------------------------------------------------------------------------

extern "C" int32_t eh_test_catch_and_resume(char * buf, int32_t max)
{
    static int call_count = 0;
    int call = ++call_count;

    if (call == 1) {
        try {
            throw_for_resume();
        } catch (const std::runtime_error &) {
            write_buf(buf, max, "exception handled");
            return 0;
        }
    } else {
        write_buf(buf, max, "no exception");
        return 0;
    }
    return -1;
}