| From: | Heikki Linnakangas <hlinnaka(at)iki(dot)fi> |
|---|---|
| To: | Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>, Pg Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org> |
| Cc: | Bohyun Lee <bohyun(dot)lee(at)databricks(dot)com> |
| Subject: | Re: pg_upgrade: fix use-after-close in cleanup_output_dirs() |
| Date: | 2026-12-01 11:48:11 |
| Message-ID: | 0615eb09-f9da-4fb9-8ecd-4a29df7a02d5@iki.fi |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
On 01/12/2026 09:08, Chao Li wrote:
> 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.
Committed, thanks.
This rings a bell. Bohyun's "pg_upgrade --initdb" patches [1] include
this fix too. I guess that patch set makes this case easier to hit,
that's why it came up with that patch. Was that the other patch you were
reviewing by any chance?
[1]
https://postgr.es/m/CAMPh8MrYxbKqaZzFHE9U7oVa6qrDwjm8XAG08S2=KACj_OBUQQ@mail.gmail.com
- Heikki
| From | Date | Subject | |
|---|---|---|---|
| Next Message | shveta malik | 2026-12-01 11:48:13 | Re: ALTER DEFAULT PRIVILEGES IN SCHEMA pg_conflict silently has no effect |
| Previous Message | Dipak Dudhabhate | 2026-12-01 11:39:26 | Undetected deadlock in logical decoding of composite-type columns with synchronous replication |