> On Dec 1, 2026, at 19:48, Heikki Linnakangas <[email protected]> wrote:
> 
> 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.

Thanks for pushing.

> 
> 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_ob...@mail.gmail.com
> 

I reviewed several recent patches about pg_upgrade that David Rowley posted, 
but unfortunately, I haven’t reviewed Bohyun’s. I just put the patch to my TODO 
of reviews.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Reply via email to