Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3ea7e95

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 733fa9a commit 3ea7e95

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
@@ -147,10 +147,28 @@ tsearch_readline(tsearch_readline_state *stp)
147147
{
148148
char *result;
149149

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

@@ -160,7 +178,16 @@ tsearch_readline(tsearch_readline_state *stp)
160178
void
161179
tsearch_readline_end(tsearch_readline_state *stp)
162180
{
181+
/* Suppress use of curline in any error reported below */
182+
if (stp->curline)
183+
{
184+
pfree(stp->curline);
185+
stp->curline = NULL;
186+
}
187+
188+
/* Release other resources */
163189
FreeFile(stp->fp);
190+
164191
/* Pop the error context stack */
165192
error_context_stack = stp->cb.previous;
166193
}

0 commit comments

Comments
 (0)