Subject: Re: [PATCH 2/2] compat/mingw: fix EACCESS when opening files with `O_CREAT | O_EXCL`

From: Junio C Hamano <[email-masked]>
Date: Thu, 13 Mar 2025 11:02:55 -0700

Patrick Steinhardt <[email-masked]> writes:

> +	/*
> +	 * Internally, `_wopen()` uses the `CreateFile()` API with CREATE_NEW,
> +	 * which may error out with ERROR_ACCESS_DENIED when the file is
> +	 * scheduled for deletion via `DeleteFileW()`. The file essentially
> +	 * exists, so we map this error to ERROR_ALREADY_EXISTS so that callers
> +	 * don't have to special-case this.
> +	 *
> +	 * This fixes issues for example with the lockfile interface when one
> +	 * process has a lock that it is about to commit or release while
> +	 * another process wants to acquire it.
> +	 */

The above may explain how the code gets ERROR_ACCESS_DENIED when
there is a pending DeleteFileW() on the file.  I however cannot
judge if the opposite is also always true, i.e. ERROR_ACCESS_DENIED
always mean the file did exist and hasn't gone away and no other
reason the code would ever get that error status.  Somebody with
better understanding on Windows API behaviour hopefully can review
it.

Thanks.

> +	if (fd < 0 && create && GetLastError() == ERROR_ACCESS_DENIED)
> +		errno = EEXIST;
>  	if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
>  		DWORD attrs = GetFileAttributesW(wfilename);
>  		if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))