From 46178509bcf37226eac7ff2d943dc34b8568a7b1 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Fri, 11 Mar 2022 13:27:33 -0800 Subject: [PATCH] regex: fix free_fail_stack undefined behavior MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * lib/regexec.c (push_fail_stack): Don’t increment number of re_fail_stack_t entries until after successful allocation. This prevents a crash if re_realloc or re_malloc fails here, and a later free_fail_stack examines regs or a later pop_fail_stack examines node. Problem discovered by Coverity scan sent 2022-03-11 11:03:52Z. --- ChangeLog | 10 ++++++++++ lib/regexec.c | 5 +++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index 53d744d83f..ca26d9774f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,13 @@ +2022-03-11 Paul Eggert + + regex: fix free_fail_stack undefined behavior + * lib/regexec.c (push_fail_stack): Don’t increment number of + re_fail_stack_t entries until after successful allocation. This + prevents a crash if re_realloc or re_malloc fails here, and a + later free_fail_stack examines regs or a later pop_fail_stack + examines node. Problem discovered by Coverity scan sent + 2022-03-11 11:03:52Z. + 2022-03-01 Paul Eggert Create lib/Makefile.am after gnulib-comp.m4 diff --git a/lib/regexec.c b/lib/regexec.c index aea1e7da52..0691e91e1e 100644 --- a/lib/regexec.c +++ b/lib/regexec.c @@ -1308,8 +1308,8 @@ push_fail_stack (struct re_fail_stack_t *fs, Idx str_idx, Idx dest_node, re_node_set *eps_via_nodes) { reg_errcode_t err; - Idx num = fs->num++; - if (fs->num == fs->alloc) + Idx num = fs->num; + if (num + 1 == fs->alloc) { struct re_fail_stack_ent_t *new_array; new_array = re_realloc (fs->stack, struct re_fail_stack_ent_t, @@ -1324,6 +1324,7 @@ push_fail_stack (struct re_fail_stack_t *fs, Idx str_idx, Idx dest_node, fs->stack[num].regs = re_malloc (regmatch_t, 2 * nregs); if (fs->stack[num].regs == NULL) return REG_ESPACE; + fs->num = num + 1; memcpy (fs->stack[num].regs, regs, sizeof (regmatch_t) * nregs); memcpy (fs->stack[num].regs + nregs, prevregs, sizeof (regmatch_t) * nregs); err = re_node_set_init_copy (&fs->stack[num].eps_via_nodes, eps_via_nodes); -- 2.39.5