Skip to content

Commit

Permalink
mingw_open_existing: handle directories better (#5342)
Browse files Browse the repository at this point in the history
[`CreateFileW()` requires `FILE_FLAG_BACKUP_SEMANTICS` to create a
directory
handle](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew#directories)
and errors out with `ERROR_ACCESS_DENIED` without this flag. Fall back
to accessing Directory handles this way.

This fixes #5068
  • Loading branch information
dscho authored Jan 23, 2025
2 parents f48c92b + fae6b7a commit f045ed3
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions compat/mingw.c
Original file line number Diff line number Diff line change
Expand Up @@ -810,13 +810,24 @@ static int mingw_open_existing(const wchar_t *filename, int oflags, ...)
&security_attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (handle == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
if (err == ERROR_ACCESS_DENIED) {
DWORD attrs = GetFileAttributesW(filename);
if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
handle = CreateFileW(filename, access,
FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
&security_attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL| FILE_FLAG_BACKUP_SEMANTICS, NULL);
}

/* See `mingw_open_append()` for why we have this conversion. */
if (err == ERROR_INVALID_PARAMETER)
err = ERROR_PATH_NOT_FOUND;
if (handle == INVALID_HANDLE_VALUE) {
err = GetLastError();

errno = err_win_to_posix(err);
return -1;
/* See `mingw_open_append()` for why we have this conversion. */
if (err == ERROR_INVALID_PARAMETER)
err = ERROR_PATH_NOT_FOUND;

errno = err_win_to_posix(err);
return -1;
}
}

fd = _open_osfhandle((intptr_t)handle, oflags | O_BINARY);
Expand Down

0 comments on commit f045ed3

Please sign in to comment.