2 * win32_replacements.c - Replacements for various functions not available on
3 * Windows, such as fsync().
7 * Copyright (C) 2013-2016 Eric Biggers
9 * This file is free software; you can redistribute it and/or modify it under
10 * the terms of the GNU Lesser General Public License as published by the Free
11 * Software Foundation; either version 3 of the License, or (at your option) any
14 * This file is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this file; if not, see http://www.gnu.org/licenses/.
31 #include <io.h> /* for _get_osfhandle() */
34 #include "wimlib/win32_common.h"
36 #include "wimlib/assert.h"
37 #include "wimlib/glob.h"
38 #include "wimlib/error.h"
39 #include "wimlib/util.h"
42 win32_error_to_errno(DWORD err_code)
44 /* This mapping is that used in Cygwin.
45 * Some of these choices are arbitrary. */
47 case ERROR_ACCESS_DENIED:
49 case ERROR_ACTIVE_CONNECTIONS:
51 case ERROR_ALREADY_EXISTS:
53 case ERROR_BAD_DEVICE:
55 case ERROR_BAD_EXE_FORMAT:
57 case ERROR_BAD_NETPATH:
59 case ERROR_BAD_NET_NAME:
61 case ERROR_BAD_NET_RESP:
63 case ERROR_BAD_PATHNAME:
69 case ERROR_BAD_USERNAME:
71 case ERROR_BEGINNING_OF_MEDIA:
73 case ERROR_BROKEN_PIPE:
79 case ERROR_CALL_NOT_IMPLEMENTED:
81 case ERROR_CANNOT_MAKE:
83 case ERROR_CHILD_NOT_COMPLETE:
85 case ERROR_COMMITMENT_LIMIT:
89 case ERROR_DEVICE_DOOR_OPEN:
91 case ERROR_DEVICE_IN_USE:
93 case ERROR_DEVICE_REQUIRES_CLEANING:
97 case ERROR_DIR_NOT_EMPTY:
99 case ERROR_DISK_CORRUPT:
101 case ERROR_DISK_FULL:
107 case ERROR_EAS_DIDNT_FIT:
110 case ERROR_EAS_NOT_SUPPORTED:
113 case ERROR_EA_LIST_INCONSISTENT:
115 case ERROR_EA_TABLE_FULL:
117 case ERROR_END_OF_MEDIA:
119 case ERROR_EOM_OVERFLOW:
121 case ERROR_EXE_MACHINE_TYPE_MISMATCH:
123 case ERROR_EXE_MARKED_INVALID:
125 case ERROR_FILEMARK_DETECTED:
127 case ERROR_FILENAME_EXCED_RANGE:
129 case ERROR_FILE_CORRUPT:
131 case ERROR_FILE_EXISTS:
133 case ERROR_FILE_INVALID:
135 case ERROR_FILE_NOT_FOUND:
137 case ERROR_HANDLE_DISK_FULL:
140 case ERROR_HANDLE_EOF:
143 case ERROR_INVALID_ADDRESS:
145 case ERROR_INVALID_AT_INTERRUPT_TIME:
147 case ERROR_INVALID_BLOCK_LENGTH:
149 case ERROR_INVALID_DATA:
151 case ERROR_INVALID_DRIVE:
153 case ERROR_INVALID_EA_NAME:
155 case ERROR_INVALID_EXE_SIGNATURE:
158 case ERROR_INVALID_FUNCTION:
161 case ERROR_INVALID_HANDLE:
163 case ERROR_INVALID_NAME:
165 case ERROR_INVALID_PARAMETER:
167 case ERROR_INVALID_SIGNAL_NUMBER:
169 case ERROR_IOPL_NOT_ENABLED:
171 case ERROR_IO_DEVICE:
173 case ERROR_IO_INCOMPLETE:
175 case ERROR_IO_PENDING:
177 case ERROR_LOCK_VIOLATION:
179 case ERROR_MAX_THRDS_REACHED:
181 case ERROR_META_EXPANSION_TOO_LONG:
183 case ERROR_MOD_NOT_FOUND:
186 case ERROR_MORE_DATA:
189 case ERROR_NEGATIVE_SEEK:
191 case ERROR_NETNAME_DELETED:
195 case ERROR_NONE_MAPPED:
197 case ERROR_NONPAGED_SYSTEM_RESOURCES:
200 case ERROR_NOT_CONNECTED:
203 case ERROR_NOT_ENOUGH_MEMORY:
205 case ERROR_NOT_OWNER:
208 case ERROR_NOT_READY:
211 case ERROR_NOT_SAME_DEVICE:
213 case ERROR_NOT_SUPPORTED:
217 case ERROR_NO_DATA_DETECTED:
220 case ERROR_NO_MEDIA_IN_DRIVE:
224 case ERROR_NO_MORE_FILES:
228 case ERROR_NO_MORE_ITEMS:
231 case ERROR_NO_MORE_SEARCH_HANDLES:
233 case ERROR_NO_PROC_SLOTS:
235 case ERROR_NO_SIGNAL_SENT:
237 case ERROR_NO_SYSTEM_RESOURCES:
241 case ERROR_OPEN_FAILED:
243 case ERROR_OPEN_FILES:
245 case ERROR_OUTOFMEMORY:
247 case ERROR_PAGED_SYSTEM_RESOURCES:
249 case ERROR_PAGEFILE_QUOTA:
251 case ERROR_PATH_NOT_FOUND:
253 case ERROR_PIPE_BUSY:
255 case ERROR_PIPE_CONNECTED:
258 case ERROR_PIPE_LISTENING:
260 case ERROR_PIPE_NOT_CONNECTED:
263 case ERROR_POSSIBLE_DEADLOCK:
265 case ERROR_PRIVILEGE_NOT_HELD:
267 case ERROR_PROCESS_ABORTED:
269 case ERROR_PROC_NOT_FOUND:
272 case ERROR_REM_NOT_LIST:
275 case ERROR_SECTOR_NOT_FOUND:
279 case ERROR_SETMARK_DETECTED:
281 case ERROR_SHARING_BUFFER_EXCEEDED:
283 case ERROR_SHARING_VIOLATION:
285 case ERROR_SIGNAL_PENDING:
287 case ERROR_SIGNAL_REFUSED:
290 case ERROR_SXS_CANT_GEN_ACTCTX:
293 case ERROR_THREAD_1_INACTIVE:
295 case ERROR_TOO_MANY_LINKS:
297 case ERROR_TOO_MANY_OPEN_FILES:
299 case ERROR_WAIT_NO_CHILDREN:
301 case ERROR_WORKING_SET_QUOTA:
303 case ERROR_WRITE_PROTECT:
311 set_errno_from_win32_error(DWORD err)
313 errno = win32_error_to_errno(err);
317 set_errno_from_GetLastError(void)
319 set_errno_from_win32_error(GetLastError());
322 /* Replacement for POSIX fsync() */
328 h = (HANDLE)_get_osfhandle(fd);
329 if (h == INVALID_HANDLE_VALUE)
331 if (!FlushFileBuffers(h))
335 set_errno_from_GetLastError();
340 /* Use the Win32 API to get the number of processors. */
342 get_available_cpus(void)
345 GetSystemInfo(&sysinfo);
346 return sysinfo.dwNumberOfProcessors;
349 /* Use the Win32 API to get the amount of available memory. */
351 get_available_memory(void)
353 MEMORYSTATUSEX status = {
354 .dwLength = sizeof(status),
356 GlobalMemoryStatusEx(&status);
357 return (u64)min(status.ullTotalPhys, status.ullTotalVirtual) * 85 / 100;
360 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
361 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
362 * really does the right thing under all circumstances. */
364 realpath(const wchar_t *path, wchar_t *resolved_path)
368 wimlib_assert(resolved_path == NULL);
370 ret = GetFullPathNameW(path, 0, NULL, NULL);
372 err = GetLastError();
376 resolved_path = MALLOC(ret * sizeof(wchar_t));
379 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
381 err = GetLastError();
383 resolved_path = NULL;
388 set_errno_from_win32_error(err);
390 return resolved_path;
393 /* A quick hack to get reasonable rename() semantics on Windows, in particular
394 * deleting the destination file instead of failing with ERROR_FILE_EXISTS and
395 * working around any processes that may have the destination file open.
397 * Note: This is intended to be called when overwriting a regular file with an
398 * updated copy and is *not* a fully POSIX compliant rename(). For that you may
399 * wish to take a look at Cygwin's implementation, but be prepared...
401 * Return 0 on success, -1 on regular error, or 1 if the destination file was
402 * deleted but the source could not be renamed and therefore should not be
406 win32_rename_replacement(const wchar_t *srcpath, const wchar_t *dstpath)
410 /* Normally, MoveFileExW() with the MOVEFILE_REPLACE_EXISTING flag does
413 if (MoveFileExW(srcpath, dstpath, MOVEFILE_REPLACE_EXISTING))
416 /* MoveFileExW() failed. One way this can happen is if any process has
417 * the destination file open, in which case ERROR_ACCESS_DENIED is
418 * produced. This can commonly happen if there is a backup or antivirus
419 * program monitoring or scanning the files. This behavior is very
420 * different from the behavior of POSIX rename(), which simply unlinks
421 * the destination file and allows other processes to keep it open! */
423 if (GetLastError() != ERROR_ACCESS_DENIED)
426 /* We can work around the above-mentioned problem by renaming the
427 * destination file to yet another temporary file, then "deleting" it,
428 * which on Windows will in fact not actually delete it immediately but
429 * rather mark it for deletion when the last handle to it is closed. */
431 static const wchar_t orig_suffix[5] = L".orig";
432 const size_t num_rand_chars = 9;
435 size_t dstlen = wcslen(dstpath);
437 tmpname = alloca(sizeof(wchar_t) *
438 (dstlen + ARRAY_LEN(orig_suffix) + num_rand_chars + 1));
440 p = wmempcpy(p, dstpath, dstlen);
441 p = wmempcpy(p, orig_suffix, ARRAY_LEN(orig_suffix));
442 randomize_char_array_with_alnum(p, num_rand_chars);
447 if (!MoveFile(dstpath, tmpname))
450 if (!DeleteFile(tmpname)) {
451 set_errno_from_GetLastError();
452 WARNING_WITH_ERRNO("Failed to delete original file "
453 "(moved to \"%ls\")", tmpname);
456 if (!MoveFile(srcpath, dstpath)) {
457 set_errno_from_GetLastError();
458 WARNING_WITH_ERRNO("Atomic semantics not respected in "
459 "failed rename() (new file is at \"%ls\")",
467 set_errno_from_GetLastError();
471 /* This really could be replaced with _wcserror_s, but this doesn't seem to
472 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
473 * linked in by Visual Studio...?). */
475 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
477 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
479 pthread_mutex_lock(&strerror_lock);
480 mbstowcs(buf, strerror(errnum), buflen);
481 buf[buflen - 1] = '\0';
482 pthread_mutex_unlock(&strerror_lock);
486 #define MAX_IO_AMOUNT 1048576
489 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
493 LARGE_INTEGER orig_offset;
494 DWORD result = 0xFFFFFFFF;
495 LARGE_INTEGER relative_offset;
496 OVERLAPPED overlapped;
500 h = (HANDLE)_get_osfhandle(fd);
501 if (h == INVALID_HANDLE_VALUE)
504 if (GetFileType(h) == FILE_TYPE_PIPE) {
509 /* Get original position */
510 relative_offset.QuadPart = 0;
511 if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT)) {
512 err = GetLastError();
513 win32_error(err, L"Failed to get original file position");
517 memset(&overlapped, 0, sizeof(overlapped));
518 overlapped.Offset = offset;
519 overlapped.OffsetHigh = offset >> 32;
521 /* Do the read or write at the specified offset */
522 count = min(count, MAX_IO_AMOUNT);
525 bret = WriteFile(h, buf, count, &result, &overlapped);
527 bret = ReadFile(h, buf, count, &result, &overlapped);
529 err = GetLastError();
530 win32_error(err, L"Failed to %s %zu bytes at offset %"PRIu64,
531 (is_pwrite ? "write" : "read"), count, offset);
535 wimlib_assert(result <= count);
537 /* Restore the original position */
538 if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN)) {
539 err = GetLastError();
540 win32_error(err, L"Failed to restore file position to %"PRIu64,
549 set_errno_from_win32_error(err);
553 /* Dumb Windows implementation of pread(). It temporarily changes the file
554 * offset, so it is not safe to use with readers/writers on the same file
557 win32_pread(int fd, void *buf, size_t count, off_t offset)
559 return do_pread_or_pwrite(fd, buf, count, offset, false);
562 /* Dumb Windows implementation of pwrite(). It temporarily changes the file
563 * offset, so it is not safe to use with readers/writers on the same file
566 win32_pwrite(int fd, const void *buf, size_t count, off_t offset)
568 return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
571 /* Replacement for read() which doesn't hide the Win32 error code */
573 win32_read(int fd, void *buf, size_t count)
575 HANDLE h = (HANDLE)_get_osfhandle(fd);
576 DWORD result = 0xFFFFFFFF;
578 if (h == INVALID_HANDLE_VALUE)
581 count = min(count, MAX_IO_AMOUNT);
583 if (!ReadFile(h, buf, count, &result, NULL)) {
584 DWORD err = GetLastError();
586 L"Error reading %zu bytes from fd %d", count, fd);
587 set_errno_from_win32_error(err);
591 wimlib_assert(result <= count);
595 /* Replacement for write() which doesn't hide the Win32 error code */
597 win32_write(int fd, const void *buf, size_t count)
599 HANDLE h = (HANDLE)_get_osfhandle(fd);
600 DWORD result = 0xFFFFFFFF;
602 if (h == INVALID_HANDLE_VALUE)
605 count = min(count, MAX_IO_AMOUNT);
607 if (!WriteFile(h, buf, count, &result, NULL)) {
608 DWORD err = GetLastError();
610 L"Error writing %zu bytes to fd %d", count, fd);
611 set_errno_from_win32_error(err);
615 wimlib_assert(result <= count);
619 /* Replacement for glob() in Windows native builds that operates on wide
622 win32_wglob(const wchar_t *pattern, int flags,
623 int (*errfunc)(const wchar_t *epath, int eerrno),
626 WIN32_FIND_DATAW dat;
633 const wchar_t *backslash, *end_slash;
636 backslash = wcsrchr(pattern, L'\\');
637 end_slash = wcsrchr(pattern, L'/');
639 if (backslash > end_slash)
640 end_slash = backslash;
643 prefix_len = end_slash - pattern + 1;
647 /* This function does not support all functionality of the POSIX glob(),
648 * so make sure the parameters are consistent with supported
650 wimlib_assert(errfunc == NULL);
651 wimlib_assert((flags & GLOB_ERR) == GLOB_ERR);
652 wimlib_assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
654 hFind = FindFirstFileW(pattern, &dat);
655 if (hFind == INVALID_HANDLE_VALUE) {
656 err = GetLastError();
657 if (err == ERROR_FILE_NOT_FOUND) {
661 set_errno_from_win32_error(err);
666 pglob->gl_pathv = NULL;
670 if (pglob->gl_pathc == nspaces) {
674 new_nspaces = nspaces * 2 + 1;
675 pathv = REALLOC(pglob->gl_pathv,
676 new_nspaces * sizeof(pglob->gl_pathv[0]));
679 pglob->gl_pathv = pathv;
680 nspaces = new_nspaces;
682 size_t filename_len = wcslen(dat.cFileName);
683 size_t len_needed = prefix_len + filename_len;
685 path = MALLOC((len_needed + 1) * sizeof(wchar_t));
689 wmemcpy(path, pattern, prefix_len);
690 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
691 pglob->gl_pathv[pglob->gl_pathc++] = path;
692 } while (FindNextFileW(hFind, &dat));
693 err = GetLastError();
695 if (err != ERROR_NO_MORE_FILES) {
696 set_errno_from_win32_error(err);
714 globfree(glob_t *pglob)
717 for (i = 0; i < pglob->gl_pathc; i++)
718 FREE(pglob->gl_pathv[i]);
719 FREE(pglob->gl_pathv);
722 /* Replacement for fopen(path, "a") that doesn't prevent other processes from
723 * reading the file */
725 win32_open_logfile(const wchar_t *path)
731 h = CreateFile(path, FILE_APPEND_DATA, FILE_SHARE_VALID_FLAGS,
732 NULL, OPEN_ALWAYS, 0, NULL);
733 if (h == INVALID_HANDLE_VALUE)
736 fd = _open_osfhandle((intptr_t)h, O_APPEND);
742 fp = fdopen(fd, "a");
751 #endif /* __WIN32__ */