Skip to content

Commit 10260c7

Browse files
committed
Fix fstat() emulation on Windows with standard streams
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
1 parent 3030903 commit 10260c7

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/port/win32stat.c

+20
Original file line numberDiff line numberDiff line change
@@ -289,13 +289,33 @@ int
289289
_pgfstat64(int fileno, struct stat *buf)
290290
{
291291
HANDLE hFile = (HANDLE) _get_osfhandle(fileno);
292+
char path[MAX_PATH];
292293

293294
if (hFile == INVALID_HANDLE_VALUE || buf == NULL)
294295
{
295296
errno = EINVAL;
296297
return -1;
297298
}
298299

300+
/*
301+
* Check if the fileno is a data stream. If so, unless it has been
302+
* redirected to a file, getting information through its HANDLE will fail,
303+
* so emulate its stat information in the most appropriate way and return
304+
* it instead.
305+
*/
306+
if ((fileno == _fileno(stdin) ||
307+
fileno == _fileno(stdout) ||
308+
fileno == _fileno(stderr)) &&
309+
GetFinalPathNameByHandleA(hFile, path, MAX_PATH, VOLUME_NAME_NT) == 0)
310+
{
311+
memset(buf, 0, sizeof(*buf));
312+
buf->st_mode = _S_IFCHR;
313+
buf->st_dev = fileno;
314+
buf->st_rdev = fileno;
315+
buf->st_nlink = 1;
316+
return 0;
317+
}
318+
299319
/*
300320
* Since we already have a file handle there is no need to check for
301321
* ERROR_DELETE_PENDING.

0 commit comments

Comments
 (0)