1/**
2 * This file has no copyright assigned and is placed in the Public Domain.
3 * This file is part of the mingw-w64 runtime package.
4 * No warranty is given; refer to the file DISCLAIMER.PD within this package.
5 */
6
7#include <sys/stat.h>
8#include <string.h>
9#include <wchar.h>
10#include <errno.h>
11#include <fcntl.h>
12#include <windows.h>
13#include "__mingw_fix_stat.h"
14
15#ifdef MINGW_FIX_STAT_IS_WIDE
16int __mingw_fix_wstat_fallback_fd(int ret, const wchar_t *filename, unsigned short mode)
17#else
18int __mingw_fix_stat_fallback_fd(int ret, const char *filename, unsigned short mode)
19#endif
20{
21 int fd = -1;
22
23 /*
24 * CRT _stat does not handle paths with ? and * characters and returns ENOENT.
25 * This prevents _stat from working on paths like \\?\C:\foo.txt.
26 * CRT _stat incorrectly sets S_IFREG for pipe and char devices.
27 * For these cases open specified filename and return its fd which will be passed to CRT fstat() by caller.
28 */
29 if ((ret < 0 && errno == ENOENT && __MINGW_STR_PBRK((filename), "?*")) || (ret == 0 && S_ISREG(mode))) {
30 HANDLE handle = __MINGW_CREATE_FILE((filename), FILE_READ_ATTRIBUTES, FILE_SHARE_VALID_FLAGS, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
31 if (handle != NULL && handle != INVALID_HANDLE_VALUE) {
32 /* Open filename and return fd if CRT _stat failed or if the file is not regular disk file. */
33 if (ret < 0 || GetFileType(handle) != FILE_TYPE_DISK) {
34 int saved_errno = errno;
35 fd = _open_osfhandle((intptr_t)handle, O_RDONLY);
36 errno = saved_errno;
37 }
38 if (fd < 0)
39 CloseHandle(handle);
40 }
41 }
42
43 return fd;
44}