Skip to content

Commit f81d50d

Browse files
committed
Prevent corner-case core dump in rfree().
rfree() failed to cope with the case that pg_regcomp() had initialized the regex_t struct but then failed to allocate any memory for re->re_guts (ie, the first malloc call in pg_regcomp() failed). It would try to touch the guts struct anyway, and thus dump core. This is a sufficiently narrow corner case that it's not surprising it's never been seen in the field; but still a bug is a bug, so patch all active branches. Noted while investigating whether we need to call pg_regfree after a failure return from pg_regcomp. Other than this bug, it turns out we don't, so adjust comments appropriately.
1 parent 2f9907c commit f81d50d

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

src/backend/regex/regcomp.c

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,9 @@ static struct fns functions = {
276276

277277
/*
278278
* pg_regcomp - compile regular expression
279+
*
280+
* Note: on failure, no resources remain allocated, so pg_regfree()
281+
* need not be applied to re.
279282
*/
280283
int
281284
pg_regcomp(regex_t *re,
@@ -1846,15 +1849,18 @@ rfree(regex_t *re)
18461849
g = (struct guts *) re->re_guts;
18471850
re->re_guts = NULL;
18481851
re->re_fns = NULL;
1849-
g->magic = 0;
1850-
freecm(&g->cmap);
1851-
if (g->tree != NULL)
1852-
freesubre((struct vars *) NULL, g->tree);
1853-
if (g->lacons != NULL)
1854-
freelacons(g->lacons, g->nlacons);
1855-
if (!NULLCNFA(g->search))
1856-
freecnfa(&g->search);
1857-
FREE(g);
1852+
if (g != NULL)
1853+
{
1854+
g->magic = 0;
1855+
freecm(&g->cmap);
1856+
if (g->tree != NULL)
1857+
freesubre((struct vars *) NULL, g->tree);
1858+
if (g->lacons != NULL)
1859+
freelacons(g->lacons, g->nlacons);
1860+
if (!NULLCNFA(g->search))
1861+
freecnfa(&g->search);
1862+
FREE(g);
1863+
}
18581864
}
18591865

18601866
#ifdef REG_DEBUG

src/backend/utils/adt/regexp.c

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,9 +182,8 @@ RE_compile_and_cache(text *text_re, int cflags)
182182

183183
if (regcomp_result != REG_OKAY)
184184
{
185-
/* re didn't compile */
185+
/* re didn't compile (no need for pg_regfree, if so) */
186186
pg_regerror(regcomp_result, &re_temp.cre_re, errMsg, sizeof(errMsg));
187-
/* XXX should we pg_regfree here? */
188187
ereport(ERROR,
189188
(errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
190189
errmsg("invalid regular expression: %s", errMsg)));

0 commit comments

Comments
 (0)