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