From d9c0c728afe734b7087dbb9a4bc16d5b682d139d Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Fri, 18 Sep 2015 13:55:17 -0400
Subject: [PATCH] Fix low-probability memory leak in regex execution.

After an internal failure in shortest() or longest() while pinning down the
exact location of a match, find() forgot to free the DFA structure before
returning.  This is pretty unlikely to occur, since we just successfully
ran the "search" variant of the DFA; but it could happen, and it would
result in a session-lifespan memory leak since this code uses malloc()
directly.  Problem seems to have been aboriginal in Spencer's library,
so back-patch all the way.

In passing, correct a thinko in a comment I added awhile back about the
meaning of the "ntree" field.

I happened across these issues while comparing our code to Tcl's version
of the library.
---
 src/backend/regex/regcomp.c | 2 +-
 src/backend/regex/regexec.c | 6 +++++-
 src/include/regex/regguts.h | 2 +-
 3 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/src/backend/regex/regcomp.c b/src/backend/regex/regcomp.c
index 6b95975f2be..d137ac0d3d1 100644
--- a/src/backend/regex/regcomp.c
+++ b/src/backend/regex/regcomp.c
@@ -228,7 +228,7 @@ struct vars
 	struct subre *tree;			/* subexpression tree */
 	struct subre *treechain;	/* all tree nodes allocated */
 	struct subre *treefree;		/* any free tree nodes */
-	int			ntree;			/* number of tree nodes */
+	int			ntree;			/* number of tree nodes, plus one */
 	struct cvec *cv;			/* interface cvec */
 	struct cvec *cv2;			/* utility cvec */
 	struct subre *lacons;		/* lookahead-constraint vector */
diff --git a/src/backend/regex/regexec.c b/src/backend/regex/regexec.c
index efd1e9ba022..8505994747f 100644
--- a/src/backend/regex/regexec.c
+++ b/src/backend/regex/regexec.c
@@ -348,7 +348,11 @@ find(struct vars * v,
 						   (chr **) NULL, &hitend);
 		else
 			end = longest(v, d, begin, v->stop, &hitend);
-		NOERR();
+		if (ISERR())
+		{
+			freedfa(d);
+			return v->err;
+		}
 		if (hitend && cold == NULL)
 			cold = begin;
 		if (end != NULL)
diff --git a/src/include/regex/regguts.h b/src/include/regex/regguts.h
index 94e06f041b7..fccaf298bf1 100644
--- a/src/include/regex/regguts.h
+++ b/src/include/regex/regguts.h
@@ -467,7 +467,7 @@ struct guts
 	size_t		nsub;			/* copy of re_nsub */
 	struct subre *tree;
 	struct cnfa search;			/* for fast preliminary search */
-	int			ntree;			/* number of subre's, less one */
+	int			ntree;			/* number of subre's, plus one */
 	struct colormap cmap;
 	int			FUNCPTR(compare, (const chr *, const chr *, size_t));
 	struct subre *lacons;		/* lookahead-constraint vector */
-- 
GitLab