pg_upgrade: fix use-after-close in cleanup_output_dirs()

From: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
To: Pg Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: pg_upgrade: fix use-after-close in cleanup_output_dirs()
Date: 2026-12-01 07:08:50
Message-ID: 53B9188E-3328-47D4-8B96-D1EC35E99DA0@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

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/

Attachment Content-Type Size
v1-0001-pg_upgrade-fix-use-after-close-in-cleanup_output_.patch application/octet-stream 954 bytes

Browse pgsql-hackers by date

  From Date Subject
Next Message Nisha Moond 2026-12-01 07:12:06 Re: Add a hook for handling logical decoding messages on subscribers.
Previous Message Amit Kapila 2026-12-01 06:54:37 Re: Preserve conflict log table during upgrade