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