Skip to content

Commit b91033a

Browse files
committed
Avoid possible dangling-pointer access in tsearch_readline_callback.
tsearch_readline() saves the string pointer it returns to the caller for possible use in the associated error context callback. However, the caller will usually pfree that string sometime before it next calls tsearch_readline(), so that there is a window where an ereport will try to print an already-freed string. The built-in users of tsearch_readline() happen to all do that pfree at the bottoms of their loops, so that the window is effectively empty for them. However, this is not documented as a requirement, and contrib/dict_xsyn doesn't do it like that, so it seems likely that third-party dictionaries might have live bugs here. The practical consequences of this seem pretty limited in any case, since production builds wouldn't clobber the freed string immediately, besides which you'd not expect syntax errors in dictionary files being used in production. Still, it's clearly a bug waiting to bite somebody. Fix by pstrdup'ing the string to be saved for the error callback, and then pfree'ing it next time through. It's been like this for a long time, so back-patch to all supported branches. Discussion: https://postgr.es/m/48A4FA71-524E-41B9-953A-FD04EF36E2E7@yesql.se
1 parent a950fb0 commit b91033a

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/backend/tsearch/ts_locale.c

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,28 @@ tsearch_readline(tsearch_readline_state *stp)
150150
{
151151
char *result;
152152

153+
/* Advance line number to use in error reports */
153154
stp->lineno++;
154-
stp->curline = NULL;
155+
156+
/* Clear curline, it's no longer relevant */
157+
if (stp->curline)
158+
{
159+
pfree(stp->curline);
160+
stp->curline = NULL;
161+
}
162+
163+
/* Collect next line, if there is one */
155164
result = t_readline(stp->fp);
156-
stp->curline = result;
165+
if (!result)
166+
return NULL;
167+
168+
/*
169+
* Save a copy of the line for possible use in error reports. (We cannot
170+
* just save "result", since it's likely to get pfree'd at some point by
171+
* the caller; an error after that would try to access freed data.)
172+
*/
173+
stp->curline = pstrdup(result);
174+
157175
return result;
158176
}
159177

@@ -163,7 +181,16 @@ tsearch_readline(tsearch_readline_state *stp)
163181
void
164182
tsearch_readline_end(tsearch_readline_state *stp)
165183
{
184+
/* Suppress use of curline in any error reported below */
185+
if (stp->curline)
186+
{
187+
pfree(stp->curline);
188+
stp->curline = NULL;
189+
}
190+
191+
/* Release other resources */
166192
FreeFile(stp->fp);
193+
167194
/* Pop the error context stack */
168195
error_context_stack = stp->cb.previous;
169196
}

0 commit comments

Comments
 (0)