]> wimlib.net Git - wimlib/blob - src/win32_replacements.c
mount_image.c: add fallback definitions of RENAME_* constants
[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-2016 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 https://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 <io.h> /* for _get_osfhandle()  */
31 #include <fcntl.h>
32
33 #include "wimlib/win32_common.h"
34
35 #include "wimlib/assert.h"
36 #include "wimlib/glob.h"
37 #include "wimlib/error.h"
38 #include "wimlib/timestamp.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                 get_random_alnum_chars(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 #define MAX_IO_AMOUNT 1048576
472
473 static int
474 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
475                    bool is_pwrite)
476 {
477         HANDLE h;
478         LARGE_INTEGER orig_offset;
479         DWORD result = 0xFFFFFFFF;
480         LARGE_INTEGER relative_offset;
481         OVERLAPPED overlapped;
482         BOOL bret;
483         DWORD err = 0;
484
485         h = (HANDLE)_get_osfhandle(fd);
486         if (h == INVALID_HANDLE_VALUE)
487                 goto error;
488
489         if (GetFileType(h) == FILE_TYPE_PIPE) {
490                 errno = ESPIPE;
491                 goto error;
492         }
493
494         /* Get original position */
495         relative_offset.QuadPart = 0;
496         if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT)) {
497                 err = GetLastError();
498                 win32_error(err, L"Failed to get original file position");
499                 goto error;
500         }
501
502         memset(&overlapped, 0, sizeof(overlapped));
503         overlapped.Offset = offset;
504         overlapped.OffsetHigh = offset >> 32;
505
506         /* Do the read or write at the specified offset */
507         count = min(count, MAX_IO_AMOUNT);
508         SetLastError(0);
509         if (is_pwrite)
510                 bret = WriteFile(h, buf, count, &result, &overlapped);
511         else
512                 bret = ReadFile(h, buf, count, &result, &overlapped);
513         if (!bret) {
514                 err = GetLastError();
515                 win32_error(err, L"Failed to %s %zu bytes at offset %"PRIu64,
516                             (is_pwrite ? "write" : "read"), count, offset);
517                 goto error;
518         }
519
520         wimlib_assert(result <= count);
521
522         /* Restore the original position */
523         if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN)) {
524                 err = GetLastError();
525                 win32_error(err, L"Failed to restore file position to %"PRIu64,
526                             offset);
527                 goto error;
528         }
529
530         return result;
531
532 error:
533         if (err)
534                 set_errno_from_win32_error(err);
535         return -1;
536 }
537
538 /* Dumb Windows implementation of pread().  It temporarily changes the file
539  * offset, so it is not safe to use with readers/writers on the same file
540  * descriptor.  */
541 ssize_t
542 win32_pread(int fd, void *buf, size_t count, off_t offset)
543 {
544         return do_pread_or_pwrite(fd, buf, count, offset, false);
545 }
546
547 /* Dumb Windows implementation of pwrite().  It temporarily changes the file
548  * offset, so it is not safe to use with readers/writers on the same file
549  * descriptor. */
550 ssize_t
551 win32_pwrite(int fd, const void *buf, size_t count, off_t offset)
552 {
553         return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
554 }
555
556 /* Replacement for read() which doesn't hide the Win32 error code */
557 ssize_t
558 win32_read(int fd, void *buf, size_t count)
559 {
560         HANDLE h = (HANDLE)_get_osfhandle(fd);
561         DWORD result = 0xFFFFFFFF;
562
563         if (h == INVALID_HANDLE_VALUE)
564                 return -1;
565
566         count = min(count, MAX_IO_AMOUNT);
567         SetLastError(0);
568         if (!ReadFile(h, buf, count, &result, NULL)) {
569                 DWORD err = GetLastError();
570                 win32_error(err,
571                             L"Error reading %zu bytes from fd %d", count, fd);
572                 set_errno_from_win32_error(err);
573                 return -1;
574         }
575
576         wimlib_assert(result <= count);
577         return result;
578 }
579
580 /* Replacement for write() which doesn't hide the Win32 error code */
581 ssize_t
582 win32_write(int fd, const void *buf, size_t count)
583 {
584         HANDLE h = (HANDLE)_get_osfhandle(fd);
585         DWORD result = 0xFFFFFFFF;
586
587         if (h == INVALID_HANDLE_VALUE)
588                 return -1;
589
590         count = min(count, MAX_IO_AMOUNT);
591         SetLastError(0);
592         if (!WriteFile(h, buf, count, &result, NULL)) {
593                 DWORD err = GetLastError();
594                 win32_error(err,
595                             L"Error writing %zu bytes to fd %d", count, fd);
596                 set_errno_from_win32_error(err);
597                 return -1;
598         }
599
600         wimlib_assert(result <= count);
601         return result;
602 }
603
604 /* Replacement for glob() in Windows native builds that operates on wide
605  * characters.  */
606 int
607 win32_wglob(const wchar_t *pattern, int flags,
608             int (*errfunc)(const wchar_t *epath, int eerrno),
609             glob_t *pglob)
610 {
611         WIN32_FIND_DATAW dat;
612         DWORD err;
613         HANDLE hFind;
614         int ret;
615         size_t nspaces;
616         int errno_save;
617
618         const wchar_t *backslash, *end_slash;
619         size_t prefix_len;
620
621         backslash = wcsrchr(pattern, L'\\');
622         end_slash = wcsrchr(pattern, L'/');
623
624         if (backslash > end_slash)
625                 end_slash = backslash;
626
627         if (end_slash)
628                 prefix_len = end_slash - pattern + 1;
629         else
630                 prefix_len = 0;
631
632         /* This function does not support all functionality of the POSIX glob(),
633          * so make sure the parameters are consistent with supported
634          * functionality. */
635         wimlib_assert(errfunc == NULL);
636         wimlib_assert((flags & GLOB_ERR) == GLOB_ERR);
637         wimlib_assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
638
639         hFind = FindFirstFileW(pattern, &dat);
640         if (hFind == INVALID_HANDLE_VALUE) {
641                 err = GetLastError();
642                 if (err == ERROR_FILE_NOT_FOUND) {
643                         errno = 0;
644                         return GLOB_NOMATCH;
645                 } else {
646                         set_errno_from_win32_error(err);
647                         return GLOB_ABORTED;
648                 }
649         }
650         pglob->gl_pathc = 0;
651         pglob->gl_pathv = NULL;
652         nspaces = 0;
653         do {
654                 wchar_t *path;
655                 if (pglob->gl_pathc == nspaces) {
656                         size_t new_nspaces;
657                         wchar_t **pathv;
658
659                         new_nspaces = nspaces * 2 + 1;
660                         pathv = REALLOC(pglob->gl_pathv,
661                                         new_nspaces * sizeof(pglob->gl_pathv[0]));
662                         if (!pathv)
663                                 goto oom;
664                         pglob->gl_pathv = pathv;
665                         nspaces = new_nspaces;
666                 }
667                 size_t filename_len = wcslen(dat.cFileName);
668                 size_t len_needed = prefix_len + filename_len;
669
670                 path = MALLOC((len_needed + 1) * sizeof(wchar_t));
671                 if (!path)
672                         goto oom;
673
674                 wmemcpy(path, pattern, prefix_len);
675                 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
676                 pglob->gl_pathv[pglob->gl_pathc++] = path;
677         } while (FindNextFileW(hFind, &dat));
678         err = GetLastError();
679         FindClose(hFind);
680         if (err != ERROR_NO_MORE_FILES) {
681                 set_errno_from_win32_error(err);
682                 ret = GLOB_ABORTED;
683                 goto fail_globfree;
684         }
685         return 0;
686
687 oom:
688         FindClose(hFind);
689         errno = ENOMEM;
690         ret = GLOB_NOSPACE;
691 fail_globfree:
692         errno_save = errno;
693         globfree(pglob);
694         errno = errno_save;
695         return ret;
696 }
697
698 void
699 globfree(glob_t *pglob)
700 {
701         size_t i;
702         for (i = 0; i < pglob->gl_pathc; i++)
703                 FREE(pglob->gl_pathv[i]);
704         FREE(pglob->gl_pathv);
705 }
706
707 /* Replacement for fopen(path, "a") that doesn't prevent other processes from
708  * reading the file  */
709 FILE *
710 win32_open_logfile(const wchar_t *path)
711 {
712         HANDLE h;
713         int fd;
714         FILE *fp;
715
716         h = CreateFile(path, FILE_APPEND_DATA, FILE_SHARE_VALID_FLAGS,
717                        NULL, OPEN_ALWAYS, 0, NULL);
718         if (h == INVALID_HANDLE_VALUE)
719                 return NULL;
720
721         fd = _open_osfhandle((intptr_t)h, O_APPEND);
722         if (fd < 0) {
723                 CloseHandle(h);
724                 return NULL;
725         }
726
727         fp = fdopen(fd, "a");
728         if (!fp) {
729                 close(fd);
730                 return NULL;
731         }
732
733         return fp;
734 }
735
736 #define RtlGenRandom SystemFunction036
737 BOOLEAN WINAPI RtlGenRandom(PVOID RandomBuffer, ULONG RandomBufferLength);
738
739 /*
740  * Generate @n cryptographically secure random bytes (thread-safe)
741  *
742  * This is the Windows version.  It uses RtlGenRandom() (actually called
743  * SystemFunction036) from advapi32.dll.
744  */
745 void
746 get_random_bytes(void *p, size_t n)
747 {
748         while (n != 0) {
749                 u32 count = min(n, UINT32_MAX);
750
751                 if (!RtlGenRandom(p, count)) {
752                         win32_error(GetLastError(),
753                                     L"RtlGenRandom() failed (count=%u)", count);
754                         wimlib_assert(0);
755                         count = 0;
756                 }
757                 p += count;
758                 n -= count;
759         }
760 }
761
762 /* Retrieve the current time as a WIM timestamp.  */
763 u64
764 now_as_wim_timestamp(void)
765 {
766         FILETIME ft;
767
768         GetSystemTimeAsFileTime(&ft);
769
770         return ((u64)ft.dwHighDateTime << 32) | ft.dwLowDateTime;
771 }
772
773 #endif /* _WIN32 */