Hi, While reviewing another patch, I just spotted a use-after-close issue in pg_upgrade.
cleanup_output_dirs() immediately closes log_opts.internal:
```
void
cleanup_output_dirs(void)
{
fclose(log_opts.internal);
```
Later in the same function, there is a branch that calls pg_log():
```
default:
/* different failure, just report it */
pg_log(PG_WARNING, "could not access directory \"%s\":
%m",
log_opts.rootdir);
break;
```
pg_log() calls pg_log_v(), which has the following check:
```
/* PG_VERBOSE and PG_STATUS are only output in verbose mode */
/* fopen() on log_opts.internal might have failed, so check it */
if (((type != PG_VERBOSE && type != PG_STATUS) || log_opts.verbose) &&
log_opts.internal != NULL)
{
if (type == PG_STATUS)
/* status messages get two leading spaces, see below */
fprintf(log_opts.internal, " %s\n", message);
else if (type == PG_REPORT_NONL)
fprintf(log_opts.internal, "%s", message);
else
fprintf(log_opts.internal, "%s\n", message);
fflush(log_opts.internal);
}
```
For PG_WARNING, the first part of the condition is true regardless of verbose
mode. Since cleanup_output_dirs() doesn’t set log_opts.internal to NULL after
closing the stream, pg_log_v() attempts to write to the closed stream with
fprintf() and then flush it with fflush(). This is the use-after-close issue.
The fix is straightforward. We just need to set log_opts.internal to NULL after
closing it. The attached patch does that.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
v1-0001-pg_upgrade-fix-use-after-close-in-cleanup_output_.patch
Description: Binary data
