Commit 4e3846c6
4e3846c669e3Merged
Ryan Seys <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
regexp: fix use-after-free and leak in the compile-error path
compile_error mishandled the compiler state on a catchable RegexpError two ways. First, it freed c->stripped before building the error message, but in /x (extended) mode c->src aliases c->stripped, so formatting the message read freed memory -- build the message first.
Second, it freed only c->stripped. When sp_re_error_handler longjmps out, the
re_compiler never returns to re_compile, so the bytecode (c->code), the
char-class ranges (c->classes), and the named-capture names (c->named_captures)
all leak; on success these instead transfer to the compiled pattern. Free them
all before invoking the handler. A loop of 20000 failed Regexp.new compiles
under leaks drops from 60000 leaked blocks to zero.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- 4e3846c669e3
- Parent
- ef0dd7102c46
lib/regexp/re_compile.cmodifiedView file
static voidcompile_error(re_compiler *c, const char *msg){ if (c->stripped) free(c->stripped); c->stripped = NULL; /* Build the message before freeing: in /x (extended) mode c->src aliases c->stripped, so reading it after the free would be a use-after-free. */ char buf[1024]; snprintf(buf, sizeof(buf), "%s: /%.*s/", msg, (int)(c->src_end - c->src), c->src); /* Free all half-built compiler state: a catchable RegexpError handler longjmps out and `c` never returns to re_compile, so the bytecode, char-class ranges, and named-capture names would otherwise leak. (On success these transfer to the compiled pattern instead.) */ free(c->code); c->code = NULL; if (c->classes) { for (uint16_t i = 0; i < c->num_classes; i++) free(c->classes[i].ranges); free(c->classes); c->classes = NULL; } if (c->named_captures) { for (uint16_t i = 0; i < c->num_named; i++) free((void *)c->named_captures[i].name); free(c->named_captures); c->named_captures = NULL; } if (c->stripped) free(c->stripped); c->stripped = NULL; if (sp_re_error_handler) { sp_re_error_handler(buf); /* shouldn't return; fall through to exit as a safety net */