]> wimlib.net Git - wimlib/blob - src/win32_replacements.c
Use LGPLv3+ for src/*.c
[wimlib] / src / win32_replacements.c
1 /*
2  * win32_replacements.c - Replacements for various functions not available on
3  * Windows, such as fsync().
4  */
5
6 /*
7  * Copyright (C) 2013 Eric Biggers
8  *
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
12  * later version.
13  *
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
17  * details.
18  *
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/.
21  */
22
23 #ifdef __WIN32__
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #include <errno.h>
30 #include <pthread.h>
31 #include <io.h> /* for _get_osfhandle()  */
32 #include <fcntl.h>
33
34 #include "wimlib/win32_common.h"
35
36 #include "wimlib/assert.h"
37 #include "wimlib/glob.h"
38 #include "wimlib/error.h"
39 #include "wimlib/util.h"
40
41 /* Replacement for POSIX fsync() */
42 int
43 fsync(int fd)
44 {
45         HANDLE h;
46
47         h = (HANDLE)_get_osfhandle(fd);
48         if (h == INVALID_HANDLE_VALUE)
49                 goto err;
50         if (!FlushFileBuffers(h))
51                 goto err_set_errno;
52         return 0;
53 err_set_errno:
54         set_errno_from_GetLastError();
55 err:
56         return -1;
57 }
58
59 /* Use the Win32 API to get the number of processors.  */
60 unsigned
61 win32_get_number_of_processors(void)
62 {
63         SYSTEM_INFO sysinfo;
64         GetSystemInfo(&sysinfo);
65         return sysinfo.dwNumberOfProcessors;
66 }
67
68 /* Use the Win32 API to get the amount of available memory.  */
69 u64
70 win32_get_avail_memory(void)
71 {
72         MEMORYSTATUSEX status = {
73                 .dwLength = sizeof(status),
74         };
75         GlobalMemoryStatusEx(&status);
76         return status.ullTotalPhys;
77 }
78
79 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
80  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
81  * really does the right thing under all circumstances. */
82 wchar_t *
83 realpath(const wchar_t *path, wchar_t *resolved_path)
84 {
85         DWORD ret;
86         DWORD err;
87         wimlib_assert(resolved_path == NULL);
88
89         ret = GetFullPathNameW(path, 0, NULL, NULL);
90         if (!ret) {
91                 err = GetLastError();
92                 goto fail_win32;
93         }
94
95         resolved_path = MALLOC(ret * sizeof(wchar_t));
96         if (!resolved_path)
97                 goto out;
98         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
99         if (!ret) {
100                 err = GetLastError();
101                 FREE(resolved_path);
102                 resolved_path = NULL;
103                 goto fail_win32;
104         }
105         goto out;
106 fail_win32:
107         set_errno_from_win32_error(err);
108 out:
109         return resolved_path;
110 }
111
112 /* A quick hack to get reasonable rename() semantics on Windows, in particular
113  * deleting the destination file instead of failing with ERROR_FILE_EXISTS and
114  * working around any processes that may have the destination file open.
115  *
116  * Note: This is intended to be called when overwriting a regular file with an
117  * updated copy and is *not* a fully POSIX compliant rename().  For that you may
118  * wish to take a look at Cygwin's implementation, but be prepared...
119  *
120  * Return 0 on success, -1 on regular error, or 1 if the destination file was
121  * deleted but the source could not be renamed and therefore should not be
122  * deleted.
123  */
124 int
125 win32_rename_replacement(const wchar_t *srcpath, const wchar_t *dstpath)
126 {
127         wchar_t *tmpname;
128
129         /* Normally, MoveFileExW() with the MOVEFILE_REPLACE_EXISTING flag does
130          * what we want.  */
131
132         if (MoveFileExW(srcpath, dstpath, MOVEFILE_REPLACE_EXISTING))
133                 return 0;
134
135         /* MoveFileExW() failed.  One way this can happen is if any process has
136          * the destination file open, in which case ERROR_ACCESS_DENIED is
137          * produced.  This can commonly happen if there is a backup or antivirus
138          * program monitoring or scanning the files.  This behavior is very
139          * different from the behavior of POSIX rename(), which simply unlinks
140          * the destination file and allows other processes to keep it open!  */
141
142         if (GetLastError() != ERROR_ACCESS_DENIED)
143                 goto err_set_errno;
144
145         /* We can work around the above-mentioned problem by renaming the
146          * destination file to yet another temporary file, then "deleting" it,
147          * which on Windows will in fact not actually delete it immediately but
148          * rather mark it for deletion when the last handle to it is closed.  */
149         {
150                 static const wchar_t orig_suffix[5] = L".orig";
151                 const size_t num_rand_chars = 9;
152                 wchar_t *p;
153
154                 size_t dstlen = wcslen(dstpath);
155
156                 tmpname = alloca(sizeof(wchar_t) *
157                                  (dstlen + ARRAY_LEN(orig_suffix) + num_rand_chars + 1));
158                 p = tmpname;
159                 p = wmempcpy(p, dstpath, dstlen);
160                 p = wmempcpy(p, orig_suffix, ARRAY_LEN(orig_suffix));
161                 randomize_char_array_with_alnum(p, num_rand_chars);
162                 p += num_rand_chars;
163                 *p = L'\0';
164         }
165
166         if (!MoveFile(dstpath, tmpname))
167                 goto err_set_errno;
168
169         if (!DeleteFile(tmpname)) {
170                 set_errno_from_GetLastError();
171                 WARNING_WITH_ERRNO("Failed to delete original file "
172                                    "(moved to \"%ls\")", tmpname);
173         }
174
175         if (!MoveFile(srcpath, dstpath)) {
176                 set_errno_from_GetLastError();
177                 WARNING_WITH_ERRNO("Atomic semantics not respected in "
178                                    "failed rename() (new file is at \"%ls\")",
179                                    srcpath);
180                 return 1;
181         }
182
183         return 0;
184
185 err_set_errno:
186         set_errno_from_GetLastError();
187         return -1;
188 }
189
190 /* This really could be replaced with _wcserror_s, but this doesn't seem to
191  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
192  * linked in by Visual Studio...?). */
193 int
194 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
195 {
196         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
197
198         pthread_mutex_lock(&strerror_lock);
199         mbstowcs(buf, strerror(errnum), buflen);
200         buf[buflen - 1] = '\0';
201         pthread_mutex_unlock(&strerror_lock);
202         return 0;
203 }
204
205 static int
206 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
207                    bool is_pwrite)
208 {
209         HANDLE h;
210         LARGE_INTEGER orig_offset;
211         DWORD bytes_read_or_written;
212         LARGE_INTEGER relative_offset;
213         OVERLAPPED overlapped;
214         BOOL bret;
215
216         h = (HANDLE)_get_osfhandle(fd);
217         if (h == INVALID_HANDLE_VALUE)
218                 goto err;
219
220         if (GetFileType(h) == FILE_TYPE_PIPE) {
221                 errno = ESPIPE;
222                 goto err;
223         }
224
225         /* Get original position */
226         relative_offset.QuadPart = 0;
227         if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
228                 goto err_set_errno;
229
230         memset(&overlapped, 0, sizeof(overlapped));
231         overlapped.Offset = offset;
232         overlapped.OffsetHigh = offset >> 32;
233
234         /* Do the read or write at the specified offset */
235         if (is_pwrite)
236                 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
237         else
238                 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
239         if (!bret)
240                 goto err_set_errno;
241
242         /* Restore the original position */
243         if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
244                 goto err_set_errno;
245
246         return bytes_read_or_written;
247 err_set_errno:
248         set_errno_from_GetLastError();
249 err:
250         return -1;
251 }
252
253 /* Dumb Windows implementation of pread().  It temporarily changes the file
254  * offset, so it is not safe to use with readers/writers on the same file
255  * descriptor.  */
256 ssize_t
257 pread(int fd, void *buf, size_t count, off_t offset)
258 {
259         return do_pread_or_pwrite(fd, buf, count, offset, false);
260 }
261
262 /* Dumb Windows implementation of pwrite().  It temporarily changes the file
263  * offset, so it is not safe to use with readers/writers on the same file
264  * descriptor. */
265 ssize_t
266 pwrite(int fd, const void *buf, size_t count, off_t offset)
267 {
268         return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
269 }
270
271 /* Replacement for glob() in Windows native builds that operates on wide
272  * characters.  */
273 int
274 win32_wglob(const wchar_t *pattern, int flags,
275             int (*errfunc)(const wchar_t *epath, int eerrno),
276             glob_t *pglob)
277 {
278         WIN32_FIND_DATAW dat;
279         DWORD err;
280         HANDLE hFind;
281         int ret;
282         size_t nspaces;
283         int errno_save;
284
285         const wchar_t *backslash, *end_slash;
286         size_t prefix_len;
287
288         backslash = wcsrchr(pattern, L'\\');
289         end_slash = wcsrchr(pattern, L'/');
290
291         if (backslash > end_slash)
292                 end_slash = backslash;
293
294         if (end_slash)
295                 prefix_len = end_slash - pattern + 1;
296         else
297                 prefix_len = 0;
298
299         /* This function does not support all functionality of the POSIX glob(),
300          * so make sure the parameters are consistent with supported
301          * functionality. */
302         wimlib_assert(errfunc == NULL);
303         wimlib_assert((flags & GLOB_ERR) == GLOB_ERR);
304         wimlib_assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
305
306         hFind = FindFirstFileW(pattern, &dat);
307         if (hFind == INVALID_HANDLE_VALUE) {
308                 err = GetLastError();
309                 if (err == ERROR_FILE_NOT_FOUND) {
310                         errno = 0;
311                         return GLOB_NOMATCH;
312                 } else {
313                         set_errno_from_win32_error(err);
314                         return GLOB_ABORTED;
315                 }
316         }
317         pglob->gl_pathc = 0;
318         pglob->gl_pathv = NULL;
319         nspaces = 0;
320         do {
321                 wchar_t *path;
322                 if (pglob->gl_pathc == nspaces) {
323                         size_t new_nspaces;
324                         wchar_t **pathv;
325
326                         new_nspaces = nspaces * 2 + 1;
327                         pathv = REALLOC(pglob->gl_pathv,
328                                         new_nspaces * sizeof(pglob->gl_pathv[0]));
329                         if (!pathv)
330                                 goto oom;
331                         pglob->gl_pathv = pathv;
332                         nspaces = new_nspaces;
333                 }
334                 size_t filename_len = wcslen(dat.cFileName);
335                 size_t len_needed = prefix_len + filename_len;
336
337                 path = MALLOC((len_needed + 1) * sizeof(wchar_t));
338                 if (!path)
339                         goto oom;
340
341                 wmemcpy(path, pattern, prefix_len);
342                 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
343                 pglob->gl_pathv[pglob->gl_pathc++] = path;
344         } while (FindNextFileW(hFind, &dat));
345         err = GetLastError();
346         CloseHandle(hFind);
347         if (err != ERROR_NO_MORE_FILES) {
348                 set_errno_from_win32_error(err);
349                 ret = GLOB_ABORTED;
350                 goto fail_globfree;
351         }
352         return 0;
353
354 oom:
355         CloseHandle(hFind);
356         errno = ENOMEM;
357         ret = GLOB_NOSPACE;
358 fail_globfree:
359         errno_save = errno;
360         globfree(pglob);
361         errno = errno_save;
362         return ret;
363 }
364
365 void
366 globfree(glob_t *pglob)
367 {
368         size_t i;
369         for (i = 0; i < pglob->gl_pathc; i++)
370                 FREE(pglob->gl_pathv[i]);
371         FREE(pglob->gl_pathv);
372 }
373
374 /* Replacement for fopen(path, "a") that doesn't prevent other processes from
375  * reading the file  */
376 FILE *
377 win32_open_logfile(const wchar_t *path)
378 {
379         HANDLE h;
380         int fd;
381         FILE *fp;
382
383         h = CreateFile(path, FILE_APPEND_DATA, FILE_SHARE_VALID_FLAGS,
384                        NULL, OPEN_ALWAYS, 0, NULL);
385         if (h == INVALID_HANDLE_VALUE)
386                 return NULL;
387
388         fd = _open_osfhandle((intptr_t)h, O_APPEND);
389         if (fd < 0) {
390                 CloseHandle(h);
391                 return NULL;
392         }
393
394         fp = fdopen(fd, "a");
395         if (!fp) {
396                 close(fd);
397                 return NULL;
398         }
399
400         return fp;
401 }
402
403 #endif /* __WIN32__ */