Commit 53a523ba

53a523ba0225Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 4 files · +2 added · ~2 modified

Description

runtime,codegen: Regexp.new error catchable via stash-and-defer

Regexp.new("[invalid") used to terminate the process: spinel folds literal-arg Regexp.new into the static pattern table and pre-compiles in sp_re_init (called before main()'s setjmp scope). The library's compile_error -> sp_re_error_handler -> sp_raise_cls path then hit sp_exc_top == 0 and went straight to fprintf + exit.

Install a quiet startup handler during sp_re_init that longjmps back to a wrapping setjmp around each per-slot re_compile. Capture the message into sp_re_pat_err_; the slot itself is left NULL. regex_pat_c_expr checks the per-slot err first and raises a catchable RegexpError from inside the user's begin/ rescue scope. After sp_re_init the default raising handler is restored so dyn-compile errors stay catchable too.

Refs #846

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
53a523ba0225
Parent
eec56fd026a0

lib/sp_runtime.hmodifiedView file

@@ -2718,6 +2718,28 @@
27182718 static void sp_re_default_error_handler(const char *msg) {
27192719 sp_raise_cls("RegexpError", msg);
27202720 }
2721+/* Issue #846: during sp_re_init (before main()'s setjmp scope is
2722+ active), a bad literal `Regexp.new("[invalid")` pattern would
2723+ route through sp_raise_cls -> "unhandled exception" + exit
2724+ because sp_exc_top is 0. Install a startup handler that longjmps
2725+ back to sp_re_init's wrapping setjmp; the codegen-emitted loop
2726+ then stashes the error per slot for a deferred raise from the
2727+ first use site (where the user's begin/rescue is active). The
2728+ re_compile contract requires the error callback to not return
2729+ (otherwise the library's fall-through fprintf+exit fires) so
2730+ we longjmp out. */
2731+static const char *sp_re_startup_err = NULL;
2732+static jmp_buf sp_re_startup_jmp;
2733+static void sp_re_startup_error_handler(const char *msg) {
2734+ if (msg) {
2735+ size_t n = strlen(msg);
2736+ char *buf = sp_str_alloc_raw(n + 1);
2737+ memcpy(buf, msg, n);
2738+ buf[n] = 0;
2739+ sp_re_startup_err = buf;
2740+ }
2741+ longjmp(sp_re_startup_jmp, 1);
2742+}
27212743 extern void sp_re_set_error_handler(void (*fn)(const char *msg));
27222744 static void sp_mark_in_flight_exceptions(void) { for (int i = 0; i < sp_exc_top; i++) sp_mark_string(sp_exc_msg[i]); }
27232745