psql: Don't close stdin, don't leak file descriptor with ON_ERROR_STOP - Mailing list pgsql-hackers

From Marti Raudsepp
Subject psql: Don't close stdin, don't leak file descriptor with ON_ERROR_STOP
Date
Msg-id AANLkTi=033=6jo=vCLCfhkXVWVn8H6y4Oq1yNpAVOeex@mail.gmail.com
Whole thread Raw
Responses Re: psql: Don't close stdin, don't leak file descriptor with ON_ERROR_STOP
List pgsql-hackers
Hi list,

Here's the second patch from my coccicheck run. Originally it flagged
the fact that the opened file in psql's process_file() wasn't being
closed in the ON_ERROR_STOP path, but there seem to be two more
unintended behaviors here.

(1) In the error path, the value of pset.inputfile wasn't being
properly restored. The caller does free(fname) on line 786, so
psql.inputfile would point to unallocated memory.

(2) The more significant issue is that stdin *was closed in the
success return path. So when you run a script with two "\i -" lines,
the first "\q" would close stdin and the next one would fail with:
    psql:-:0: could not read from input file: Bad file descriptor

In fact, this means that stdin was being accessed after being
fclose()d, which is undefined behavior per ANSI C, though it seems to
work just fine on Linux.

The new behavior requires the same amount of "\q"s as the number of
executions of '-' because stdin is never closed.

Regards,
Marti

Attachment

pgsql-hackers by date:

Previous
From: "Stephen R. van den Berg"
Date:
Subject: Re: pg_rawdump
Next
From: Dimitri Fontaine
Date:
Subject: Re: Extensions, this time with a patch