8000 Further tweaking of the readfile() function in pg_ctl. · danielcode/postgres@e7bab08 · GitHub
[go: up one dir, main page]

Skip to content

Commit e7bab08

Browse files
committed
Further tweaking of the readfile() function in pg_ctl.
Don't leak a file descriptor if the file is empty or we can't read its size. Expect there to be a newline at the end of the last line, too. If there isn't, ignore anything after the last newline. This makes it a tiny bit more robust in case the file is appended to concurrently, so that we don't return the last line if it hasn't been fully written yet. And this makes the code a bit less obscure, anyway. Per Tom Lane's suggestion. Backpatch to all supported branches.
1 parent 623e49c commit e7bab08

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/bin/pg_ctl/pg_ctl.c

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,14 @@ readfile(const char *path)
333333
if (fd < 0)
334334
return NULL;
335335
if (fstat(fd, &statbuf) < 0)
336+
{
337+
close(fd);
336338
return NULL;
339+
}
337340
if (statbuf.st_size == 0)
338341
{
339342
/* empty file */
343+
close(fd);
340344
result = (char **) pg_malloc(sizeof(char *));
341345
*result = NULL;
342346
return result;
@@ -352,14 +356,17 @@ readfile(const char *path)
352356
return NULL;
353357
}
354358

355-
/* count newlines */
359+
/*
360+
* Count newlines. We expect there to be a newline after each full line,
361+
* including one at the end of file. If there isn't a newline at the end,
362+
* any characters after the last newline will be ignored.
363+
*/
356364
nlines = 0;
357-
for (i = 0; i < len - 1; i++)
365+
for (i = 0; i < len; i++)
358366
{
359367
if (buffer[i] == '\n')
360368
nlines++;
361369
}
362-
nlines++; /* account for the last line */
363370

364371
/* set up the result buffer */
365372
result = (char **) pg_malloc((nlines + 1) * sizeof(char *));
@@ -369,7 +376,7 @@ readfile(const char *path)
369376
n = 0;
370377
for (i = 0; i < len; i++)
371378
{
372-
if (buffer[i] == '\n' || i == len - 1)
379+
if (buffer[i] == '\n')
373380
{
374381
int slen = &buffer[i] - linebegin + 1;
375382
char *linebuf = pg_malloc(slen + 1);

0 commit comments

Comments
 (0)
0