From 10260c794b211117a56ee2eb2deacf609bcca25f Mon Sep 17 00:00:00 2001 From: Michael Paquier Date: Thu, 25 Nov 2021 12:16:21 +0900 Subject: [PATCH] Fix fstat() emulation on Windows with standard streams MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit The emulation of fstat() in win32stat.c caused two issues with the existing in-core callers, failing on EINVAL when using a stream as argument: - psql's \copy would crash when using a stream. - pg_recvlogical would fail with -f -. The tests in copyselect.sql from the main test suite covers the first case, and there is a TAP test for the second case. However, in both cases, as the standard streams are always redirected, automated tests did not notice those issues, requiring a terminal on Windows to be reproducible. This issue has been introduced in bed9075, and the origin of the problem is that GetFileInformationByHandle() does not work directly on streams, so this commit adds an extra code path to emulate and return a set of stats that match best with the reality. Note that redirected streams rely on handles that can be queried with GetFileInformationByHandle(), but we can rely on GetFinalPathNameByHandleA() to detect this case. Author: Dmitry Koval, Juan José Santamaría Flecha Discussion: https://postgr.es/m/17288-6b58a91025a8a8a3@postgresql.org Backpatch-through: 14 --- src/port/win32stat.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/port/win32stat.c b/src/port/win32stat.c index 2ad8ee13595..3956fac0603 100644 --- a/src/port/win32stat.c +++ b/src/port/win32stat.c @@ -289,6 +289,7 @@ int _pgfstat64(int fileno, struct stat *buf) { HANDLE hFile = (HANDLE) _get_osfhandle(fileno); + char path[MAX_PATH]; if (hFile == INVALID_HANDLE_VALUE || buf == NULL) { @@ -296,6 +297,25 @@ _pgfstat64(int fileno, struct stat *buf) return -1; } + /* + * Check if the fileno is a data stream. If so, unless it has been + * redirected to a file, getting information through its HANDLE will fail, + * so emulate its stat information in the most appropriate way and return + * it instead. + */ + if ((fileno == _fileno(stdin) || + fileno == _fileno(stdout) || + fileno == _fileno(stderr)) && + GetFinalPathNameByHandleA(hFile, path, MAX_PATH, VOLUME_NAME_NT) == 0) + { + memset(buf, 0, sizeof(*buf)); + buf->st_mode = _S_IFCHR; + buf->st_dev = fileno; + buf->st_rdev = fileno; + buf->st_nlink = 1; + return 0; + } + /* * Since we already have a file handle there is no need to check for * ERROR_DELETE_PENDING. -- 2.30.2