2 * win32_replacements.c - Replacements for various functions not available on
3 * Windows, such as fsync().
7 * Copyright (C) 2013 Eric Biggers
9 * This file is part of wimlib, a library for working with WIM files.
11 * wimlib is free software; you can redistribute it and/or modify it under the
12 * terms of the GNU General Public License as published by the Free
13 * Software Foundation; either version 3 of the License, or (at your option)
16 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
17 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 * A PARTICULAR PURPOSE. See the GNU General Public License for more
21 * You should have received a copy of the GNU General Public License
22 * along with wimlib; if not, see http://www.gnu.org/licenses/.
33 #include <io.h> /* for _get_osfhandle() */
35 #include "wimlib/win32_common.h"
37 #include "wimlib/assert.h"
38 #include "wimlib/glob.h"
39 #include "wimlib/error.h"
40 #include "wimlib/util.h"
42 /* Replacement for POSIX fsync() */
48 h = (HANDLE)_get_osfhandle(fd);
49 if (h == INVALID_HANDLE_VALUE)
51 if (!FlushFileBuffers(h))
55 set_errno_from_GetLastError();
60 /* Use the Win32 API to get the number of processors. */
62 win32_get_number_of_processors(void)
65 GetSystemInfo(&sysinfo);
66 return sysinfo.dwNumberOfProcessors;
69 /* Use the Win32 API to get the amount of available memory. */
71 win32_get_avail_memory(void)
73 MEMORYSTATUSEX status = {
74 .dwLength = sizeof(status),
76 GlobalMemoryStatusEx(&status);
77 return status.ullTotalPhys;
80 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
81 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
82 * really does the right thing under all circumstances. */
84 realpath(const wchar_t *path, wchar_t *resolved_path)
88 wimlib_assert(resolved_path == NULL);
90 ret = GetFullPathNameW(path, 0, NULL, NULL);
96 resolved_path = MALLOC(ret * sizeof(wchar_t));
99 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
101 err = GetLastError();
103 resolved_path = NULL;
108 set_errno_from_win32_error(err);
110 return resolved_path;
113 /* A quick hack to get reasonable rename() semantics on Windows, in particular
114 * deleting the destination file instead of failing with ERROR_FILE_EXISTS and
115 * working around any processes that may have the destination file open.
117 * Note: This is intended to be called when overwriting a regular file with an
118 * updated copy and is *not* a fully POSIX compliant rename(). For that you may
119 * wish to take a look at Cygwin's implementation, but be prepared...
121 * Return 0 on success, -1 on regular error, or 1 if the destination file was
122 * deleted but the source could not be renamed and therefore should not be
126 win32_rename_replacement(const wchar_t *srcpath, const wchar_t *dstpath)
130 /* Normally, MoveFileExW() with the MOVEFILE_REPLACE_EXISTING flag does
133 if (MoveFileExW(srcpath, dstpath, MOVEFILE_REPLACE_EXISTING))
136 /* MoveFileExW() failed. One way this can happen is if any process has
137 * the destination file open, in which case ERROR_ACCESS_DENIED is
138 * produced. This can commonly happen if there is a backup or antivirus
139 * program monitoring or scanning the files. This behavior is very
140 * different from the behavior of POSIX rename(), which simply unlinks
141 * the destination file and allows other processes to keep it open! */
143 if (GetLastError() != ERROR_ACCESS_DENIED)
146 /* We can work around the above-mentioned problem by renaming the
147 * destination file to yet another temporary file, then "deleting" it,
148 * which on Windows will in fact not actually delete it immediately but
149 * rather mark it for deletion when the last handle to it is closed. */
151 static const wchar_t orig_suffix[5] = L".orig";
152 const size_t num_rand_chars = 9;
155 size_t dstlen = wcslen(dstpath);
157 tmpname = alloca(sizeof(wchar_t) *
158 (dstlen + ARRAY_LEN(orig_suffix) + num_rand_chars + 1));
160 p = wmempcpy(p, dstpath, dstlen);
161 p = wmempcpy(p, orig_suffix, ARRAY_LEN(orig_suffix));
162 randomize_char_array_with_alnum(p, num_rand_chars);
167 if (!MoveFile(dstpath, tmpname))
170 if (!DeleteFile(tmpname)) {
171 set_errno_from_GetLastError();
172 WARNING_WITH_ERRNO("Failed to delete original file "
173 "(moved to \"%ls\")", tmpname);
176 if (!MoveFile(srcpath, dstpath)) {
177 set_errno_from_GetLastError();
178 WARNING_WITH_ERRNO("Atomic semantics not respected in "
179 "failed rename() (new file is at \"%ls\")",
187 set_errno_from_GetLastError();
191 /* This really could be replaced with _wcserror_s, but this doesn't seem to
192 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
193 * linked in by Visual Studio...?). */
195 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
197 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
199 pthread_mutex_lock(&strerror_lock);
200 mbstowcs(buf, strerror(errnum), buflen);
201 buf[buflen - 1] = '\0';
202 pthread_mutex_unlock(&strerror_lock);
207 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
211 LARGE_INTEGER orig_offset;
212 DWORD bytes_read_or_written;
213 LARGE_INTEGER relative_offset;
214 OVERLAPPED overlapped;
217 h = (HANDLE)_get_osfhandle(fd);
218 if (h == INVALID_HANDLE_VALUE)
221 if (GetFileType(h) == FILE_TYPE_PIPE) {
226 /* Get original position */
227 relative_offset.QuadPart = 0;
228 if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
231 memset(&overlapped, 0, sizeof(overlapped));
232 overlapped.Offset = offset;
233 overlapped.OffsetHigh = offset >> 32;
235 /* Do the read or write at the specified offset */
237 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
239 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
243 /* Restore the original position */
244 if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
247 return bytes_read_or_written;
249 set_errno_from_GetLastError();
254 /* Dumb Windows implementation of pread(). It temporarily changes the file
255 * offset, so it is not safe to use with readers/writers on the same file
258 pread(int fd, void *buf, size_t count, off_t offset)
260 return do_pread_or_pwrite(fd, buf, count, offset, false);
263 /* Dumb Windows implementation of pwrite(). It temporarily changes the file
264 * offset, so it is not safe to use with readers/writers on the same file
267 pwrite(int fd, const void *buf, size_t count, off_t offset)
269 return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
273 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
276 BY_HANDLE_FILE_INFORMATION file_info;
280 h = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
281 if (h == INVALID_HANDLE_VALUE) {
282 ret = WIMLIB_ERR_OPEN;
286 if (!GetFileInformationByHandle(h, &file_info)) {
287 ret = WIMLIB_ERR_STAT;
289 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
290 (u64)file_info.nFileIndexLow;
291 *dev_ret = file_info.dwVolumeSerialNumber;
294 err = GetLastError();
298 set_errno_from_GetLastError();
302 /* Replacement for glob() in Windows native builds that operates on wide
305 win32_wglob(const wchar_t *pattern, int flags,
306 int (*errfunc)(const wchar_t *epath, int eerrno),
309 WIN32_FIND_DATAW dat;
316 const wchar_t *backslash, *end_slash;
319 backslash = wcsrchr(pattern, L'\\');
320 end_slash = wcsrchr(pattern, L'/');
322 if (backslash > end_slash)
323 end_slash = backslash;
326 prefix_len = end_slash - pattern + 1;
330 /* This function does not support all functionality of the POSIX glob(),
331 * so make sure the parameters are consistent with supported
333 wimlib_assert(errfunc == NULL);
334 wimlib_assert((flags & GLOB_ERR) == GLOB_ERR);
335 wimlib_assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
337 hFind = FindFirstFileW(pattern, &dat);
338 if (hFind == INVALID_HANDLE_VALUE) {
339 err = GetLastError();
340 if (err == ERROR_FILE_NOT_FOUND) {
344 set_errno_from_win32_error(err);
349 pglob->gl_pathv = NULL;
353 if (pglob->gl_pathc == nspaces) {
357 new_nspaces = nspaces * 2 + 1;
358 pathv = REALLOC(pglob->gl_pathv,
359 new_nspaces * sizeof(pglob->gl_pathv[0]));
362 pglob->gl_pathv = pathv;
363 nspaces = new_nspaces;
365 size_t filename_len = wcslen(dat.cFileName);
366 size_t len_needed = prefix_len + filename_len;
368 path = MALLOC((len_needed + 1) * sizeof(wchar_t));
372 wmemcpy(path, pattern, prefix_len);
373 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
374 pglob->gl_pathv[pglob->gl_pathc++] = path;
375 } while (FindNextFileW(hFind, &dat));
376 err = GetLastError();
378 if (err != ERROR_NO_MORE_FILES) {
379 set_errno_from_win32_error(err);
397 globfree(glob_t *pglob)
400 for (i = 0; i < pglob->gl_pathc; i++)
401 FREE(pglob->gl_pathv[i]);
402 FREE(pglob->gl_pathv);
405 #endif /* __WIN32__ */