]> wimlib.net Git - wimlib/blob - src/win32_replacements.c
mkwinpeimg: Quote $0
[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 /* rename() on Windows fails if the destination file exists.  And we need to
103  * make it work on wide characters.  Fix it. */
104 int
105 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
106 {
107         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
108                 return 0;
109         } else {
110                 set_errno_from_GetLastError();
111                 return -1;
112         }
113 }
114
115 /* Replacement for POSIX fnmatch() (partial functionality only) */
116 int
117 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
118 {
119         if (PathMatchSpecW(string, pattern))
120                 return 0;
121         else
122                 return FNM_NOMATCH;
123 }
124
125 /* truncate() replacement */
126 int
127 win32_truncate_replacement(const wchar_t *path, off_t size)
128 {
129         DWORD err = NO_ERROR;
130         LARGE_INTEGER liOffset;
131
132         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
133         if (h == INVALID_HANDLE_VALUE)
134                 goto fail;
135
136         liOffset.QuadPart = size;
137         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
138                 goto fail_close_handle;
139
140         if (!SetEndOfFile(h))
141                 goto fail_close_handle;
142         CloseHandle(h);
143         return 0;
144
145 fail_close_handle:
146         err = GetLastError();
147         CloseHandle(h);
148 fail:
149         if (err == NO_ERROR)
150                 err = GetLastError();
151         set_errno_from_win32_error(err);
152         return -1;
153 }
154
155
156 /* This really could be replaced with _wcserror_s, but this doesn't seem to
157  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
158  * linked in by Visual Studio...?). */
159 extern int
160 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
161 {
162         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
163
164         pthread_mutex_lock(&strerror_lock);
165         mbstowcs(buf, strerror(errnum), buflen);
166         buf[buflen - 1] = '\0';
167         pthread_mutex_unlock(&strerror_lock);
168         return 0;
169 }
170
171 static int
172 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
173                    bool is_pwrite)
174 {
175         HANDLE h;
176         LARGE_INTEGER orig_offset;
177         DWORD bytes_read_or_written;
178         LARGE_INTEGER relative_offset;
179         OVERLAPPED overlapped;
180         BOOL bret;
181
182         h = (HANDLE)_get_osfhandle(fd);
183         if (h == INVALID_HANDLE_VALUE)
184                 goto err;
185
186         if (GetFileType(h) == FILE_TYPE_PIPE) {
187                 errno = ESPIPE;
188                 goto err;
189         }
190
191         /* Get original position */
192         relative_offset.QuadPart = 0;
193         if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
194                 goto err_set_errno;
195
196         memset(&overlapped, 0, sizeof(overlapped));
197         overlapped.Offset = offset;
198         overlapped.OffsetHigh = offset >> 32;
199
200         /* Do the read or write at the specified offset */
201         if (is_pwrite)
202                 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
203         else
204                 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
205         if (!bret)
206                 goto err_set_errno;
207
208         /* Restore the original position */
209         if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
210                 goto err_set_errno;
211
212         return bytes_read_or_written;
213 err_set_errno:
214         set_errno_from_GetLastError();
215 err:
216         return -1;
217 }
218
219 /* Dumb Windows implementation of pread().  It temporarily changes the file
220  * offset, so it is not safe to use with readers/writers on the same file
221  * descriptor.  */
222 ssize_t
223 pread(int fd, void *buf, size_t count, off_t offset)
224 {
225         return do_pread_or_pwrite(fd, buf, count, offset, false);
226 }
227
228 /* Dumb Windows implementation of pwrite().  It temporarily changes the file
229  * offset, so it is not safe to use with readers/writers on the same file
230  * descriptor. */
231 ssize_t
232 pwrite(int fd, const void *buf, size_t count, off_t offset)
233 {
234         return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
235 }
236
237 /* Dumb Windows implementation of writev().  It writes the vectors one at a
238  * time. */
239 ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
240 {
241         ssize_t total_bytes_written = 0;
242
243         if (iovcnt <= 0) {
244                 errno = EINVAL;
245                 return -1;
246         }
247         for (int i = 0; i < iovcnt; i++) {
248                 ssize_t bytes_written;
249
250                 bytes_written = write(fd, iov[i].iov_base, iov[i].iov_len);
251                 if (bytes_written >= 0)
252                         total_bytes_written += bytes_written;
253                 if (bytes_written != iov[i].iov_len) {
254                         if (total_bytes_written == 0)
255                                 total_bytes_written = -1;
256                         break;
257                 }
258         }
259         return total_bytes_written;
260 }
261
262 int
263 win32_get_file_and_vol_ids(const wchar_t *path, u64 *ino_ret, u64 *dev_ret)
264 {
265         HANDLE h;
266         BY_HANDLE_FILE_INFORMATION file_info;
267         int ret;
268         DWORD err;
269
270         h = win32_open_existing_file(path, FILE_READ_ATTRIBUTES);
271         if (h == INVALID_HANDLE_VALUE) {
272                 ret = WIMLIB_ERR_OPEN;
273                 goto out;
274         }
275
276         if (!GetFileInformationByHandle(h, &file_info)) {
277                 ret = WIMLIB_ERR_STAT;
278         } else {
279                 *ino_ret = ((u64)file_info.nFileIndexHigh << 32) |
280                             (u64)file_info.nFileIndexLow;
281                 *dev_ret = file_info.dwVolumeSerialNumber;
282                 ret = 0;
283         }
284         err = GetLastError();
285         CloseHandle(h);
286         SetLastError(err);
287 out:
288         set_errno_from_GetLastError();
289         return ret;
290 }
291
292 /* Replacement for glob() in Windows native builds that operates on wide
293  * characters.  */
294 int
295 win32_wglob(const wchar_t *pattern, int flags,
296             int (*errfunc)(const wchar_t *epath, int eerrno),
297             glob_t *pglob)
298 {
299         WIN32_FIND_DATAW dat;
300         DWORD err;
301         HANDLE hFind;
302         int ret;
303         size_t nspaces;
304
305         const wchar_t *backslash, *end_slash;
306         size_t prefix_len;
307
308         backslash = wcsrchr(pattern, L'\\');
309         end_slash = wcsrchr(pattern, L'/');
310
311         if (backslash > end_slash)
312                 end_slash = backslash;
313
314         if (end_slash)
315                 prefix_len = end_slash - pattern + 1;
316         else
317                 prefix_len = 0;
318
319         /* This function does not support all functionality of the POSIX glob(),
320          * so make sure the parameters are consistent with supported
321          * functionality. */
322         wimlib_assert(errfunc == NULL);
323         wimlib_assert((flags & GLOB_ERR) == GLOB_ERR);
324         wimlib_assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
325
326         hFind = FindFirstFileW(pattern, &dat);
327         if (hFind == INVALID_HANDLE_VALUE) {
328                 err = GetLastError();
329                 if (err == ERROR_FILE_NOT_FOUND) {
330                         errno = 0;
331                         return GLOB_NOMATCH;
332                 } else {
333                         /* The other possible error codes for FindFirstFile()
334                          * are undocumented. */
335                         errno = EIO;
336                         return GLOB_ABORTED;
337                 }
338         }
339         pglob->gl_pathc = 0;
340         pglob->gl_pathv = NULL;
341         nspaces = 0;
342         do {
343                 wchar_t *path;
344                 if (pglob->gl_pathc == nspaces) {
345                         size_t new_nspaces;
346                         wchar_t **pathv;
347
348                         new_nspaces = nspaces * 2 + 1;
349                         pathv = REALLOC(pglob->gl_pathv,
350                                         new_nspaces * sizeof(pglob->gl_pathv[0]));
351                         if (!pathv)
352                                 goto oom;
353                         pglob->gl_pathv = pathv;
354                         nspaces = new_nspaces;
355                 }
356                 size_t filename_len = wcslen(dat.cFileName);
357                 size_t len_needed = prefix_len + filename_len;
358
359                 path = MALLOC((len_needed + 1) * sizeof(wchar_t));
360                 if (!path)
361                         goto oom;
362
363                 wmemcpy(path, pattern, prefix_len);
364                 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
365                 pglob->gl_pathv[pglob->gl_pathc++] = path;
366         } while (FindNextFileW(hFind, &dat));
367         err = GetLastError();
368         CloseHandle(hFind);
369         if (err == ERROR_NO_MORE_FILES) {
370                 errno = 0;
371                 return 0;
372         } else {
373                 /* Other possible error codes for FindNextFile() are
374                  * undocumented */
375                 errno = EIO;
376                 ret = GLOB_ABORTED;
377                 goto fail_globfree;
378         }
379 oom:
380         CloseHandle(hFind);
381         errno = ENOMEM;
382         ret = GLOB_NOSPACE;
383 fail_globfree:
384         globfree(pglob);
385         return ret;
386 }
387
388 void
389 globfree(glob_t *pglob)
390 {
391         size_t i;
392         for (i = 0; i < pglob->gl_pathc; i++)
393                 free(pglob->gl_pathv[i]);
394         free(pglob->gl_pathv);
395 }
396
397 #endif /* __WIN32__ */