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