+
+ /* MoveFileExW() failed. One way this can happen is if any process has
+ * the destination file open, in which case ERROR_ACCESS_DENIED is
+ * produced. This can commonly happen if there is a backup or antivirus
+ * program monitoring or scanning the files. This behavior is very
+ * different from the behavior of POSIX rename(), which simply unlinks
+ * the destination file and allows other processes to keep it open! */
+
+ if (GetLastError() != ERROR_ACCESS_DENIED)
+ goto err_set_errno;
+
+ /* We can work around the above-mentioned problem by renaming the
+ * destination file to yet another temporary file, then "deleting" it,
+ * which on Windows will in fact not actually delete it immediately but
+ * rather mark it for deletion when the last handle to it is closed. */
+ {
+ static const wchar_t orig_suffix[5] = L".orig";
+ const size_t num_rand_chars = 9;
+ wchar_t *p;
+
+ size_t dstlen = wcslen(dstpath);
+
+ tmpname = alloca(sizeof(wchar_t) *
+ (dstlen + ARRAY_LEN(orig_suffix) + num_rand_chars + 1));
+ p = tmpname;
+ p = wmempcpy(p, dstpath, dstlen);
+ p = wmempcpy(p, orig_suffix, ARRAY_LEN(orig_suffix));
+ randomize_char_array_with_alnum(p, num_rand_chars);
+ p += num_rand_chars;
+ *p = L'\0';
+ }
+
+ if (!MoveFile(dstpath, tmpname))
+ goto err_set_errno;
+
+ if (!DeleteFile(tmpname)) {