From 53c16f98484eedc99184e2d129852aa8089e2596 Mon Sep 17 00:00:00 2001 From: Fr0gzilla <242606097+Fr0gzilla@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:53:46 +0100 Subject: [PATCH] fix(macos_host): CreateFileW reports why it failed (ERROR_FILE_EXISTS for CREATE_NEW on an existing file) CreateFileW answered every failure with ERROR_FILE_NOT_FOUND. The static CRT turns that into errno, so an exclusive _wsopen_s (_O_CREAT | _O_EXCL) on an existing file failed with ENOENT instead of EEXIST, and a caller that tells the two apart (startup_trace.h's "never replace an existing file") gave the wrong reason. It now maps the open's errno: EEXIST to ERROR_FILE_EXISTS (80, what Windows answers CREATE_NEW with), EACCES/EPERM to ERROR_ACCESS_DENIED, ENOTDIR to ERROR_PATH_NOT_FOUND, anything else to ERROR_FILE_NOT_FOUND as before. Checked on an Apple M5 with a static-CRT guest: CREATE_NEW on an existing file gives 80, an exclusive _wsopen_s on it gives EEXIST, OPEN_EXISTING on a missing file still gives 2. --- runtime/macos_host/kernel32.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/runtime/macos_host/kernel32.cpp b/runtime/macos_host/kernel32.cpp index 013b2595b1..011eb84019 100644 --- a/runtime/macos_host/kernel32.cpp +++ b/runtime/macos_host/kernel32.cpp @@ -322,7 +322,13 @@ HANDLE CreateFileW(const char16_t* name, uint32_t access, uint32_t, void*, uint3 else if (disposition == 5) mode |= O_TRUNC; // TRUNCATE_EXISTING int fd = open(to_host_path(narrow.c_str()).c_str(), mode, 0644); if (fd < 0) { - set_last_error(2 /* ERROR_FILE_NOT_FOUND */); + // The CRT turns these into errno: a CREATE_NEW on an existing file is ERROR_FILE_EXISTS, which it reports as + // EEXIST (an exclusive _wsopen_s, _O_CREAT | _O_EXCL), not ERROR_FILE_NOT_FOUND's ENOENT. + const int err = errno; + set_last_error(err == EEXIST ? 80 // ERROR_FILE_EXISTS + : err == EACCES || err == EPERM ? 5 // ERROR_ACCESS_DENIED + : err == ENOTDIR ? 3 // ERROR_PATH_NOT_FOUND + : 2); // ERROR_FILE_NOT_FOUND return kInvalid; } return new Object{Object::File, fd};