]> wimlib.net Git - wimlib/blob - src/win32_replacements.c
Move CPU and memory information to util
[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 free software; you can redistribute it and/or modify it under
10  * the terms of the GNU Lesser General Public License as published by the Free
11  * Software Foundation; either version 3 of the License, or (at your option) any
12  * later version.
13  *
14  * This file is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this file; if not, see http://www.gnu.org/licenses/.
21  */
22
23 #ifdef __WIN32__
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #include <errno.h>
30 #include <pthread.h>
31 #include <io.h> /* for _get_osfhandle()  */
32 #include <fcntl.h>
33
34 #include "wimlib/win32_common.h"
35
36 #include "wimlib/assert.h"
37 #include "wimlib/glob.h"
38 #include "wimlib/error.h"
39 #include "wimlib/util.h"
40
41 static int
42 win32_error_to_errno(DWORD err_code)
43 {
44         /* This mapping is that used in Cygwin.
45          * Some of these choices are arbitrary. */
46         switch (err_code) {
47         case ERROR_ACCESS_DENIED:
48                 return EACCES;
49         case ERROR_ACTIVE_CONNECTIONS:
50                 return EAGAIN;
51         case ERROR_ALREADY_EXISTS:
52                 return EEXIST;
53         case ERROR_BAD_DEVICE:
54                 return ENODEV;
55         case ERROR_BAD_EXE_FORMAT:
56                 return ENOEXEC;
57         case ERROR_BAD_NETPATH:
58                 return ENOENT;
59         case ERROR_BAD_NET_NAME:
60                 return ENOENT;
61         case ERROR_BAD_NET_RESP:
62                 return ENOSYS;
63         case ERROR_BAD_PATHNAME:
64                 return ENOENT;
65         case ERROR_BAD_PIPE:
66                 return EINVAL;
67         case ERROR_BAD_UNIT:
68                 return ENODEV;
69         case ERROR_BAD_USERNAME:
70                 return EINVAL;
71         case ERROR_BEGINNING_OF_MEDIA:
72                 return EIO;
73         case ERROR_BROKEN_PIPE:
74                 return EPIPE;
75         case ERROR_BUSY:
76                 return EBUSY;
77         case ERROR_BUS_RESET:
78                 return EIO;
79         case ERROR_CALL_NOT_IMPLEMENTED:
80                 return ENOSYS;
81         case ERROR_CANNOT_MAKE:
82                 return EPERM;
83         case ERROR_CHILD_NOT_COMPLETE:
84                 return EBUSY;
85         case ERROR_COMMITMENT_LIMIT:
86                 return EAGAIN;
87         case ERROR_CRC:
88                 return EIO;
89         case ERROR_DEVICE_DOOR_OPEN:
90                 return EIO;
91         case ERROR_DEVICE_IN_USE:
92                 return EAGAIN;
93         case ERROR_DEVICE_REQUIRES_CLEANING:
94                 return EIO;
95         case ERROR_DIRECTORY:
96                 return ENOTDIR;
97         case ERROR_DIR_NOT_EMPTY:
98                 return ENOTEMPTY;
99         case ERROR_DISK_CORRUPT:
100                 return EIO;
101         case ERROR_DISK_FULL:
102                 return ENOSPC;
103 #ifdef ENOTUNIQ
104         case ERROR_DUP_NAME:
105                 return ENOTUNIQ;
106 #endif
107         case ERROR_EAS_DIDNT_FIT:
108                 return ENOSPC;
109 #ifdef ENOTSUP
110         case ERROR_EAS_NOT_SUPPORTED:
111                 return ENOTSUP;
112 #endif
113         case ERROR_EA_LIST_INCONSISTENT:
114                 return EINVAL;
115         case ERROR_EA_TABLE_FULL:
116                 return ENOSPC;
117         case ERROR_END_OF_MEDIA:
118                 return ENOSPC;
119         case ERROR_EOM_OVERFLOW:
120                 return EIO;
121         case ERROR_EXE_MACHINE_TYPE_MISMATCH:
122                 return ENOEXEC;
123         case ERROR_EXE_MARKED_INVALID:
124                 return ENOEXEC;
125         case ERROR_FILEMARK_DETECTED:
126                 return EIO;
127         case ERROR_FILENAME_EXCED_RANGE:
128                 return ENAMETOOLONG;
129         case ERROR_FILE_CORRUPT:
130                 return EEXIST;
131         case ERROR_FILE_EXISTS:
132                 return EEXIST;
133         case ERROR_FILE_INVALID:
134                 return ENXIO;
135         case ERROR_FILE_NOT_FOUND:
136                 return ENOENT;
137         case ERROR_HANDLE_DISK_FULL:
138                 return ENOSPC;
139 #ifdef ENODATA
140         case ERROR_HANDLE_EOF:
141                 return ENODATA;
142 #endif
143         case ERROR_INVALID_ADDRESS:
144                 return EINVAL;
145         case ERROR_INVALID_AT_INTERRUPT_TIME:
146                 return EINTR;
147         case ERROR_INVALID_BLOCK_LENGTH:
148                 return EIO;
149         case ERROR_INVALID_DATA:
150                 return EINVAL;
151         case ERROR_INVALID_DRIVE:
152                 return ENODEV;
153         case ERROR_INVALID_EA_NAME:
154                 return EINVAL;
155         case ERROR_INVALID_EXE_SIGNATURE:
156                 return ENOEXEC;
157 #ifdef EBADRQC
158         case ERROR_INVALID_FUNCTION:
159                 return EBADRQC;
160 #endif
161         case ERROR_INVALID_HANDLE:
162                 return EBADF;
163         case ERROR_INVALID_NAME:
164                 return ENOENT;
165         case ERROR_INVALID_PARAMETER:
166                 return EINVAL;
167         case ERROR_INVALID_SIGNAL_NUMBER:
168                 return EINVAL;
169         case ERROR_IOPL_NOT_ENABLED:
170                 return ENOEXEC;
171         case ERROR_IO_DEVICE:
172                 return EIO;
173         case ERROR_IO_INCOMPLETE:
174                 return EAGAIN;
175         case ERROR_IO_PENDING:
176                 return EAGAIN;
177         case ERROR_LOCK_VIOLATION:
178                 return EBUSY;
179         case ERROR_MAX_THRDS_REACHED:
180                 return EAGAIN;
181         case ERROR_META_EXPANSION_TOO_LONG:
182                 return EINVAL;
183         case ERROR_MOD_NOT_FOUND:
184                 return ENOENT;
185 #ifdef EMSGSIZE
186         case ERROR_MORE_DATA:
187                 return EMSGSIZE;
188 #endif
189         case ERROR_NEGATIVE_SEEK:
190                 return EINVAL;
191         case ERROR_NETNAME_DELETED:
192                 return ENOENT;
193         case ERROR_NOACCESS:
194                 return EFAULT;
195         case ERROR_NONE_MAPPED:
196                 return EINVAL;
197         case ERROR_NONPAGED_SYSTEM_RESOURCES:
198                 return EAGAIN;
199 #ifdef ENOLINK
200         case ERROR_NOT_CONNECTED:
201                 return ENOLINK;
202 #endif
203         case ERROR_NOT_ENOUGH_MEMORY:
204                 return ENOMEM;
205         case ERROR_NOT_OWNER:
206                 return EPERM;
207 #ifdef ENOMEDIUM
208         case ERROR_NOT_READY:
209                 return ENOMEDIUM;
210 #endif
211         case ERROR_NOT_SAME_DEVICE:
212                 return EXDEV;
213         case ERROR_NOT_SUPPORTED:
214                 return ENOSYS;
215         case ERROR_NO_DATA:
216                 return EPIPE;
217         case ERROR_NO_DATA_DETECTED:
218                 return EIO;
219 #ifdef ENOMEDIUM
220         case ERROR_NO_MEDIA_IN_DRIVE:
221                 return ENOMEDIUM;
222 #endif
223 #ifdef ENMFILE
224         case ERROR_NO_MORE_FILES:
225                 return ENMFILE;
226 #endif
227 #ifdef ENMFILE
228         case ERROR_NO_MORE_ITEMS:
229                 return ENMFILE;
230 #endif
231         case ERROR_NO_MORE_SEARCH_HANDLES:
232                 return ENFILE;
233         case ERROR_NO_PROC_SLOTS:
234                 return EAGAIN;
235         case ERROR_NO_SIGNAL_SENT:
236                 return EIO;
237         case ERROR_NO_SYSTEM_RESOURCES:
238                 return EFBIG;
239         case ERROR_NO_TOKEN:
240                 return EINVAL;
241         case ERROR_OPEN_FAILED:
242                 return EIO;
243         case ERROR_OPEN_FILES:
244                 return EAGAIN;
245         case ERROR_OUTOFMEMORY:
246                 return ENOMEM;
247         case ERROR_PAGED_SYSTEM_RESOURCES:
248                 return EAGAIN;
249         case ERROR_PAGEFILE_QUOTA:
250                 return EAGAIN;
251         case ERROR_PATH_NOT_FOUND:
252                 return ENOENT;
253         case ERROR_PIPE_BUSY:
254                 return EBUSY;
255         case ERROR_PIPE_CONNECTED:
256                 return EBUSY;
257 #ifdef ECOMM
258         case ERROR_PIPE_LISTENING:
259                 return ECOMM;
260         case ERROR_PIPE_NOT_CONNECTED:
261                 return ECOMM;
262 #endif
263         case ERROR_POSSIBLE_DEADLOCK:
264                 return EDEADLOCK;
265         case ERROR_PRIVILEGE_NOT_HELD:
266                 return EPERM;
267         case ERROR_PROCESS_ABORTED:
268                 return EFAULT;
269         case ERROR_PROC_NOT_FOUND:
270                 return ESRCH;
271 #ifdef ENONET
272         case ERROR_REM_NOT_LIST:
273                 return ENONET;
274 #endif
275         case ERROR_SECTOR_NOT_FOUND:
276                 return EINVAL;
277         case ERROR_SEEK:
278                 return EINVAL;
279         case ERROR_SETMARK_DETECTED:
280                 return EIO;
281         case ERROR_SHARING_BUFFER_EXCEEDED:
282                 return ENOLCK;
283         case ERROR_SHARING_VIOLATION:
284                 return EBUSY;
285         case ERROR_SIGNAL_PENDING:
286                 return EBUSY;
287         case ERROR_SIGNAL_REFUSED:
288                 return EIO;
289 #ifdef ELIBBAD
290         case ERROR_SXS_CANT_GEN_ACTCTX:
291                 return ELIBBAD;
292 #endif
293         case ERROR_THREAD_1_INACTIVE:
294                 return EINVAL;
295         case ERROR_TOO_MANY_LINKS:
296                 return EMLINK;
297         case ERROR_TOO_MANY_OPEN_FILES:
298                 return EMFILE;
299         case ERROR_WAIT_NO_CHILDREN:
300                 return ECHILD;
301         case ERROR_WORKING_SET_QUOTA:
302                 return EAGAIN;
303         case ERROR_WRITE_PROTECT:
304                 return EROFS;
305         default:
306                 return -1;
307         }
308 }
309
310 static void
311 set_errno_from_win32_error(DWORD err)
312 {
313         errno = win32_error_to_errno(err);
314 }
315
316 static void
317 set_errno_from_GetLastError(void)
318 {
319         set_errno_from_win32_error(GetLastError());
320 }
321
322 /* Replacement for POSIX fsync() */
323 int
324 fsync(int fd)
325 {
326         HANDLE h;
327
328         h = (HANDLE)_get_osfhandle(fd);
329         if (h == INVALID_HANDLE_VALUE)
330                 goto err;
331         if (!FlushFileBuffers(h))
332                 goto err_set_errno;
333         return 0;
334 err_set_errno:
335         set_errno_from_GetLastError();
336 err:
337         return -1;
338 }
339
340 /* Use the Win32 API to get the number of processors.  */
341 unsigned
342 get_available_cpus(void)
343 {
344         SYSTEM_INFO sysinfo;
345         GetSystemInfo(&sysinfo);
346         return sysinfo.dwNumberOfProcessors;
347 }
348
349 /* Use the Win32 API to get the amount of available memory.  */
350 u64
351 get_available_memory(void)
352 {
353         MEMORYSTATUSEX status = {
354                 .dwLength = sizeof(status),
355         };
356         GlobalMemoryStatusEx(&status);
357         return (u64)min(status.ullTotalPhys, status.ullTotalVirtual) * 85 / 100;
358 }
359
360 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
361  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
362  * really does the right thing under all circumstances. */
363 wchar_t *
364 realpath(const wchar_t *path, wchar_t *resolved_path)
365 {
366         DWORD ret;
367         DWORD err;
368         wimlib_assert(resolved_path == NULL);
369
370         ret = GetFullPathNameW(path, 0, NULL, NULL);
371         if (!ret) {
372                 err = GetLastError();
373                 goto fail_win32;
374         }
375
376         resolved_path = MALLOC(ret * sizeof(wchar_t));
377         if (!resolved_path)
378                 goto out;
379         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
380         if (!ret) {
381                 err = GetLastError();
382                 FREE(resolved_path);
383                 resolved_path = NULL;
384                 goto fail_win32;
385         }
386         goto out;
387 fail_win32:
388         set_errno_from_win32_error(err);
389 out:
390         return resolved_path;
391 }
392
393 /* A quick hack to get reasonable rename() semantics on Windows, in particular
394  * deleting the destination file instead of failing with ERROR_FILE_EXISTS and
395  * working around any processes that may have the destination file open.
396  *
397  * Note: This is intended to be called when overwriting a regular file with an
398  * updated copy and is *not* a fully POSIX compliant rename().  For that you may
399  * wish to take a look at Cygwin's implementation, but be prepared...
400  *
401  * Return 0 on success, -1 on regular error, or 1 if the destination file was
402  * deleted but the source could not be renamed and therefore should not be
403  * deleted.
404  */
405 int
406 win32_rename_replacement(const wchar_t *srcpath, const wchar_t *dstpath)
407 {
408         wchar_t *tmpname;
409
410         /* Normally, MoveFileExW() with the MOVEFILE_REPLACE_EXISTING flag does
411          * what we want.  */
412
413         if (MoveFileExW(srcpath, dstpath, MOVEFILE_REPLACE_EXISTING))
414                 return 0;
415
416         /* MoveFileExW() failed.  One way this can happen is if any process has
417          * the destination file open, in which case ERROR_ACCESS_DENIED is
418          * produced.  This can commonly happen if there is a backup or antivirus
419          * program monitoring or scanning the files.  This behavior is very
420          * different from the behavior of POSIX rename(), which simply unlinks
421          * the destination file and allows other processes to keep it open!  */
422
423         if (GetLastError() != ERROR_ACCESS_DENIED)
424                 goto err_set_errno;
425
426         /* We can work around the above-mentioned problem by renaming the
427          * destination file to yet another temporary file, then "deleting" it,
428          * which on Windows will in fact not actually delete it immediately but
429          * rather mark it for deletion when the last handle to it is closed.  */
430         {
431                 static const wchar_t orig_suffix[5] = L".orig";
432                 const size_t num_rand_chars = 9;
433                 wchar_t *p;
434
435                 size_t dstlen = wcslen(dstpath);
436
437                 tmpname = alloca(sizeof(wchar_t) *
438                                  (dstlen + ARRAY_LEN(orig_suffix) + num_rand_chars + 1));
439                 p = tmpname;
440                 p = wmempcpy(p, dstpath, dstlen);
441                 p = wmempcpy(p, orig_suffix, ARRAY_LEN(orig_suffix));
442                 randomize_char_array_with_alnum(p, num_rand_chars);
443                 p += num_rand_chars;
444                 *p = L'\0';
445         }
446
447         if (!MoveFile(dstpath, tmpname))
448                 goto err_set_errno;
449
450         if (!DeleteFile(tmpname)) {
451                 set_errno_from_GetLastError();
452                 WARNING_WITH_ERRNO("Failed to delete original file "
453                                    "(moved to \"%ls\")", tmpname);
454         }
455
456         if (!MoveFile(srcpath, dstpath)) {
457                 set_errno_from_GetLastError();
458                 WARNING_WITH_ERRNO("Atomic semantics not respected in "
459                                    "failed rename() (new file is at \"%ls\")",
460                                    srcpath);
461                 return 1;
462         }
463
464         return 0;
465
466 err_set_errno:
467         set_errno_from_GetLastError();
468         return -1;
469 }
470
471 /* This really could be replaced with _wcserror_s, but this doesn't seem to
472  * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
473  * linked in by Visual Studio...?). */
474 int
475 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
476 {
477         static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
478
479         pthread_mutex_lock(&strerror_lock);
480         mbstowcs(buf, strerror(errnum), buflen);
481         buf[buflen - 1] = '\0';
482         pthread_mutex_unlock(&strerror_lock);
483         return 0;
484 }
485
486 static int
487 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
488                    bool is_pwrite)
489 {
490         HANDLE h;
491         LARGE_INTEGER orig_offset;
492         DWORD bytes_read_or_written;
493         LARGE_INTEGER relative_offset;
494         OVERLAPPED overlapped;
495         BOOL bret;
496
497         h = (HANDLE)_get_osfhandle(fd);
498         if (h == INVALID_HANDLE_VALUE)
499                 goto err;
500
501         if (GetFileType(h) == FILE_TYPE_PIPE) {
502                 errno = ESPIPE;
503                 goto err;
504         }
505
506         /* Get original position */
507         relative_offset.QuadPart = 0;
508         if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
509                 goto err_set_errno;
510
511         memset(&overlapped, 0, sizeof(overlapped));
512         overlapped.Offset = offset;
513         overlapped.OffsetHigh = offset >> 32;
514
515         /* Do the read or write at the specified offset */
516         if (is_pwrite)
517                 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
518         else
519                 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
520         if (!bret)
521                 goto err_set_errno;
522
523         /* Restore the original position */
524         if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
525                 goto err_set_errno;
526
527         return bytes_read_or_written;
528 err_set_errno:
529         set_errno_from_GetLastError();
530 err:
531         return -1;
532 }
533
534 /* Dumb Windows implementation of pread().  It temporarily changes the file
535  * offset, so it is not safe to use with readers/writers on the same file
536  * descriptor.  */
537 ssize_t
538 pread(int fd, void *buf, size_t count, off_t offset)
539 {
540         return do_pread_or_pwrite(fd, buf, count, offset, false);
541 }
542
543 /* Dumb Windows implementation of pwrite().  It temporarily changes the file
544  * offset, so it is not safe to use with readers/writers on the same file
545  * descriptor. */
546 ssize_t
547 pwrite(int fd, const void *buf, size_t count, off_t offset)
548 {
549         return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
550 }
551
552 /* Replacement for glob() in Windows native builds that operates on wide
553  * characters.  */
554 int
555 win32_wglob(const wchar_t *pattern, int flags,
556             int (*errfunc)(const wchar_t *epath, int eerrno),
557             glob_t *pglob)
558 {
559         WIN32_FIND_DATAW dat;
560         DWORD err;
561         HANDLE hFind;
562         int ret;
563         size_t nspaces;
564         int errno_save;
565
566         const wchar_t *backslash, *end_slash;
567         size_t prefix_len;
568
569         backslash = wcsrchr(pattern, L'\\');
570         end_slash = wcsrchr(pattern, L'/');
571
572         if (backslash > end_slash)
573                 end_slash = backslash;
574
575         if (end_slash)
576                 prefix_len = end_slash - pattern + 1;
577         else
578                 prefix_len = 0;
579
580         /* This function does not support all functionality of the POSIX glob(),
581          * so make sure the parameters are consistent with supported
582          * functionality. */
583         wimlib_assert(errfunc == NULL);
584         wimlib_assert((flags & GLOB_ERR) == GLOB_ERR);
585         wimlib_assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
586
587         hFind = FindFirstFileW(pattern, &dat);
588         if (hFind == INVALID_HANDLE_VALUE) {
589                 err = GetLastError();
590                 if (err == ERROR_FILE_NOT_FOUND) {
591                         errno = 0;
592                         return GLOB_NOMATCH;
593                 } else {
594                         set_errno_from_win32_error(err);
595                         return GLOB_ABORTED;
596                 }
597         }
598         pglob->gl_pathc = 0;
599         pglob->gl_pathv = NULL;
600         nspaces = 0;
601         do {
602                 wchar_t *path;
603                 if (pglob->gl_pathc == nspaces) {
604                         size_t new_nspaces;
605                         wchar_t **pathv;
606
607                         new_nspaces = nspaces * 2 + 1;
608                         pathv = REALLOC(pglob->gl_pathv,
609                                         new_nspaces * sizeof(pglob->gl_pathv[0]));
610                         if (!pathv)
611                                 goto oom;
612                         pglob->gl_pathv = pathv;
613                         nspaces = new_nspaces;
614                 }
615                 size_t filename_len = wcslen(dat.cFileName);
616                 size_t len_needed = prefix_len + filename_len;
617
618                 path = MALLOC((len_needed + 1) * sizeof(wchar_t));
619                 if (!path)
620                         goto oom;
621
622                 wmemcpy(path, pattern, prefix_len);
623                 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
624                 pglob->gl_pathv[pglob->gl_pathc++] = path;
625         } while (FindNextFileW(hFind, &dat));
626         err = GetLastError();
627         CloseHandle(hFind);
628         if (err != ERROR_NO_MORE_FILES) {
629                 set_errno_from_win32_error(err);
630                 ret = GLOB_ABORTED;
631                 goto fail_globfree;
632         }
633         return 0;
634
635 oom:
636         CloseHandle(hFind);
637         errno = ENOMEM;
638         ret = GLOB_NOSPACE;
639 fail_globfree:
640         errno_save = errno;
641         globfree(pglob);
642         errno = errno_save;
643         return ret;
644 }
645
646 void
647 globfree(glob_t *pglob)
648 {
649         size_t i;
650         for (i = 0; i < pglob->gl_pathc; i++)
651                 FREE(pglob->gl_pathv[i]);
652         FREE(pglob->gl_pathv);
653 }
654
655 /* Replacement for fopen(path, "a") that doesn't prevent other processes from
656  * reading the file  */
657 FILE *
658 win32_open_logfile(const wchar_t *path)
659 {
660         HANDLE h;
661         int fd;
662         FILE *fp;
663
664         h = CreateFile(path, FILE_APPEND_DATA, FILE_SHARE_VALID_FLAGS,
665                        NULL, OPEN_ALWAYS, 0, NULL);
666         if (h == INVALID_HANDLE_VALUE)
667                 return NULL;
668
669         fd = _open_osfhandle((intptr_t)h, O_APPEND);
670         if (fd < 0) {
671                 CloseHandle(h);
672                 return NULL;
673         }
674
675         fp = fdopen(fd, "a");
676         if (!fp) {
677                 close(fd);
678                 return NULL;
679         }
680
681         return fp;
682 }
683
684 #endif /* __WIN32__ */