]> wimlib.net Git - wimlib/blob - src/win32_replacements.c
write.c: Do not raw-copy packed resources
[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 /* Use the Win32 API to get the amount of available memory.  */
70 u64
71 win32_get_avail_memory(void)
72 {
73         MEMORYSTATUSEX status = {
74                 .dwLength = sizeof(status),
75         };
76         GlobalMemoryStatusEx(&status);
77         return status.ullTotalPhys;
78 }
79
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. */
83 wchar_t *
84 realpath(const wchar_t *path, wchar_t *resolved_path)
85 {
86         DWORD ret;
87         DWORD err;
88         wimlib_assert(resolved_path == NULL);
89
90         ret = GetFullPathNameW(path, 0, NULL, NULL);
91         if (!ret) {
92                 err = GetLastError();
93                 goto fail_win32;
94         }
95
96         resolved_path = MALLOC(ret * sizeof(wchar_t));
97         if (!resolved_path)
98                 goto out;
99         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
100         if (!ret) {
101                 err = GetLastError();
102                 FREE(resolved_path);
103                 resolved_path = NULL;
104                 goto fail_win32;
105         }
106         goto out;
107 fail_win32:
108         set_errno_from_win32_error(err);
109 out:
110         return resolved_path;
111 }
112
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.
116  *
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...
120  *
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
123  * deleted.
124  */
125 int
126 win32_rename_replacement(const wchar_t *srcpath, const wchar_t *dstpath)
127 {
128         wchar_t *tmpname;
129
130         /* Normally, MoveFileExW() with the MOVEFILE_REPLACE_EXISTING flag does
131          * what we want.  */
132
133         if (MoveFileExW(srcpath, dstpath, MOVEFILE_REPLACE_EXISTING))
134                 return 0;
135
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!  */
142
143         if (GetLastError() != ERROR_ACCESS_DENIED)
144                 goto err_set_errno;
145
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.  */
150         {
151                 static const wchar_t orig_suffix[5] = L".orig";
152                 const size_t num_rand_chars = 9;
153                 wchar_t *p;
154
155                 size_t dstlen = wcslen(dstpath);
156
157                 tmpname = alloca(sizeof(wchar_t) *
158                                  (dstlen + ARRAY_LEN(orig_suffix) + num_rand_chars + 1));
159                 p = tmpname;
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);
163                 p += num_rand_chars;
164                 *p = L'\0';
165         }
166
167         if (!MoveFile(dstpath, tmpname))
168                 goto err_set_errno;
169
170         if (!DeleteFile(tmpname)) {
171                 set_errno_from_GetLastError();
172                 WARNING_WITH_ERRNO("Failed to delete original file "
173                                    "(moved to \"%ls\")", tmpname);
174         }
175
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\")",
180                                    srcpath);
181                 return 1;
182         }
183
184         return 0;
185
186 err_set_errno:
187         set_errno_from_GetLastError();
188         return -1;
189 }
190
191 /* Replacement for POSIX fnmatch() (partial functionality only) */
192 int
193 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
194 {
195         if (PathMatchSpecW(string, pattern))
196                 return 0;
197         else
198                 return FNM_NOMATCH;
199 }
200
201 /* truncate() replacement */
202 int
203 win32_truncate_replacement(const wchar_t *path, off_t size)
204 {
205         DWORD err = NO_ERROR;
206         LARGE_INTEGER liOffset;
207
208         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
209         if (h == INVALID_HANDLE_VALUE)
210                 goto fail;
211
212         liOffset.QuadPart = size;
213         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
214                 goto fail_close_handle;
215
216         if (!SetEndOfFile(h))
217                 goto fail_close_handle;
218         CloseHandle(h);
219         return 0;
220
221 fail_close_handle:
222         err = GetLastError();
223         CloseHandle(h);
224 fail:
225         if (err == NO_ERROR)
226                 err = GetLastError();
227         set_errno_from_win32_error(err);
228         return -1;
229 }
230
231
232 /* This really could be replaced with _wcserror_s, but this doesn't seem to
233  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
234  * linked in by Visual Studio...?). */
235 extern int
236 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
237 {
238         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
239
240         pthread_mutex_lock(&strerror_lock);
241         mbstowcs(buf, strerror(errnum), buflen);
242         buf[buflen - 1] = '\0';
243         pthread_mutex_unlock(&strerror_lock);
244         return 0;
245 }
246
247 static int
248 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
249                    bool is_pwrite)
250 {
251         HANDLE h;
252         LARGE_INTEGER orig_offset;
253         DWORD bytes_read_or_written;
254         LARGE_INTEGER relative_offset;
255         OVERLAPPED overlapped;
256         BOOL bret;
257
258         h = (HANDLE)_get_osfhandle(fd);
259         if (h == INVALID_HANDLE_VALUE)
260                 goto err;
261
262         if (GetFileType(h) == FILE_TYPE_PIPE) {
263                 errno = ESPIPE;
264                 goto err;
265         }
266
267         /* Get original position */
268         relative_offset.QuadPart = 0;
269         if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
270                 goto err_set_errno;
271
272         memset(&overlapped, 0, sizeof(overlapped));
273         overlapped.Offset = offset;
274         overlapped.OffsetHigh = offset >> 32;
275
276         /* Do the read or write at the specified offset */
277         if (is_pwrite)
278                 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
279         else
280                 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
281         if (!bret)
282                 goto err_set_errno;
283
284         /* Restore the original position */
285         if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
286                 goto err_set_errno;
287
288         return bytes_read_or_written;
289 err_set_errno:
290         set_errno_from_GetLastError();
291 err:
292         return -1;
293 }
294
295 /* Dumb Windows implementation of pread().  It temporarily changes the file
296  * offset, so it is not safe to use with readers/writers on the same file
297  * descriptor.  */
298 ssize_t
299 pread(int fd, void *buf, size_t count, off_t offset)
300 {
301         return do_pread_or_pwrite(fd, buf, count, offset, false);
302 }
303
304 /* Dumb Windows implementation of pwrite().  It temporarily changes the file
305  * offset, so it is not safe to use with readers/writers on the same file
306  * descriptor. */
307 ssize_t
308 pwrite(int fd, const void *buf, size_t count, off_t offset)
309 {
310         return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
311 }
312
313 #if 0
314 /* Dumb Windows implementation of writev().  It writes the vectors one at a
315  * time. */
316 ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
317 {
318         ssize_t total_bytes_written = 0;
319
320         if (iovcnt <= 0) {
321                 errno = EINVAL;
322                 return -1;
323         }
324         for (int i = 0; i < iovcnt; i++) {
325                 ssize_t bytes_written;
326
327                 bytes_written = write(fd, iov[i].iov_base, iov[i].iov_len);
328                 if (bytes_written >= 0)
329                         total_bytes_written += bytes_written;
330                 if (bytes_written != iov[i].iov_len) {
331                         if (total_bytes_written == 0)
332                                 total_bytes_written = -1;
333                         break;
334                 }
335         }
336         return total_bytes_written;
337 }
338 #endif
339
340 int
341 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
342 {
343         HANDLE h;
344         BY_HANDLE_FILE_INFORMATION file_info;
345         int ret;
346         DWORD err;
347
348         h = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
349         if (h == INVALID_HANDLE_VALUE) {
350                 ret = WIMLIB_ERR_OPEN;
351                 goto out;
352         }
353
354         if (!GetFileInformationByHandle(h, &file_info)) {
355                 ret = WIMLIB_ERR_STAT;
356         } else {
357                 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
358                             (u64)file_info.nFileIndexLow;
359                 *dev_ret = file_info.dwVolumeSerialNumber;
360                 ret = 0;
361         }
362         err = GetLastError();
363         CloseHandle(h);
364         SetLastError(err);
365 out:
366         set_errno_from_GetLastError();
367         return ret;
368 }
369
370 /* Replacement for glob() in Windows native builds that operates on wide
371  * characters.  */
372 int
373 win32_wglob(const wchar_t *pattern, int flags,
374             int (*errfunc)(const wchar_t *epath, int eerrno),
375             glob_t *pglob)
376 {
377         WIN32_FIND_DATAW dat;
378         DWORD err;
379         HANDLE hFind;
380         int ret;
381         size_t nspaces;
382
383         const wchar_t *backslash, *end_slash;
384         size_t prefix_len;
385
386         backslash = wcsrchr(pattern, L'\\');
387         end_slash = wcsrchr(pattern, L'/');
388
389         if (backslash > end_slash)
390                 end_slash = backslash;
391
392         if (end_slash)
393                 prefix_len = end_slash - pattern + 1;
394         else
395                 prefix_len = 0;
396
397         /* This function does not support all functionality of the POSIX glob(),
398          * so make sure the parameters are consistent with supported
399          * functionality. */
400         wimlib_assert(errfunc == NULL);
401         wimlib_assert((flags & GLOB_ERR) == GLOB_ERR);
402         wimlib_assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
403
404         hFind = FindFirstFileW(pattern, &dat);
405         if (hFind == INVALID_HANDLE_VALUE) {
406                 err = GetLastError();
407                 if (err == ERROR_FILE_NOT_FOUND) {
408                         errno = 0;
409                         return GLOB_NOMATCH;
410                 } else {
411                         /* The other possible error codes for FindFirstFile()
412                          * are undocumented. */
413                         errno = EIO;
414                         return GLOB_ABORTED;
415                 }
416         }
417         pglob->gl_pathc = 0;
418         pglob->gl_pathv = NULL;
419         nspaces = 0;
420         do {
421                 wchar_t *path;
422                 if (pglob->gl_pathc == nspaces) {
423                         size_t new_nspaces;
424                         wchar_t **pathv;
425
426                         new_nspaces = nspaces * 2 + 1;
427                         pathv = REALLOC(pglob->gl_pathv,
428                                         new_nspaces * sizeof(pglob->gl_pathv[0]));
429                         if (!pathv)
430                                 goto oom;
431                         pglob->gl_pathv = pathv;
432                         nspaces = new_nspaces;
433                 }
434                 size_t filename_len = wcslen(dat.cFileName);
435                 size_t len_needed = prefix_len + filename_len;
436
437                 path = MALLOC((len_needed + 1) * sizeof(wchar_t));
438                 if (!path)
439                         goto oom;
440
441                 wmemcpy(path, pattern, prefix_len);
442                 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
443                 pglob->gl_pathv[pglob->gl_pathc++] = path;
444         } while (FindNextFileW(hFind, &dat));
445         err = GetLastError();
446         CloseHandle(hFind);
447         if (err == ERROR_NO_MORE_FILES) {
448                 errno = 0;
449                 return 0;
450         } else {
451                 /* Other possible error codes for FindNextFile() are
452                  * undocumented */
453                 errno = EIO;
454                 ret = GLOB_ABORTED;
455                 goto fail_globfree;
456         }
457 oom:
458         CloseHandle(hFind);
459         errno = ENOMEM;
460         ret = GLOB_NOSPACE;
461 fail_globfree:
462         globfree(pglob);
463         return ret;
464 }
465
466 void
467 globfree(glob_t *pglob)
468 {
469         size_t i;
470         for (i = 0; i < pglob->gl_pathc; i++)
471                 FREE(pglob->gl_pathv[i]);
472         FREE(pglob->gl_pathv);
473 }
474
475 #endif /* __WIN32__ */