]> wimlib.net Git - wimlib/blob - src/win32.c
Win32 fixes
[wimlib] / src / win32.c
1 /*
2  * win32.c
3  *
4  * All the library code specific to native Windows builds is in here.
5  */
6
7 /*
8  * Copyright (C) 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifndef __WIN32__
27 #  error "This file contains Windows code"
28 #endif
29
30 #include "config.h"
31 #include <windows.h>
32 #include <ntdef.h>
33 #include <wchar.h>
34 #include <shlwapi.h> /* shlwapi.h for PathMatchSpecW() */
35 #ifdef ERROR /* windows.h defines this */
36 #  undef ERROR
37 #endif
38
39 #include "win32.h"
40 #include "dentry.h"
41 #include "lookup_table.h"
42 #include "security.h"
43 #include "endianness.h"
44
45 #include <errno.h>
46
47
48
49 /* Pointers to functions that are not available on all targetted versions of
50  * Windows (XP and later).  NOTE: The WINAPI annotations seem to be important; I
51  * assume it specifies a certain calling convention. */
52
53 /* Vista and later */
54 static HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
55                                             STREAM_INFO_LEVELS InfoLevel,
56                                             LPVOID lpFindStreamData,
57                                             DWORD dwFlags) = NULL;
58
59 /* Vista and later */
60 static BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
61                                          LPVOID lpFindStreamData) = NULL;
62
63 static HMODULE hKernel32 = NULL;
64
65 /* Try to dynamically load some functions */
66 void
67 win32_global_init()
68 {
69         DWORD err;
70
71         if (hKernel32 == NULL) {
72                 DEBUG("Loading Kernel32.dll");
73                 hKernel32 = LoadLibraryW(L"Kernel32.dll");
74                 if (hKernel32 == NULL) {
75                         err = GetLastError();
76                         WARNING("Can't load Kernel32.dll");
77                         win32_error(err);
78                         return;
79                 }
80         }
81
82         DEBUG("Looking for FindFirstStreamW");
83         win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32, "FindFirstStreamW");
84         if (!win32func_FindFirstStreamW) {
85                 WARNING("Could not find function FindFirstStreamW() in Kernel32.dll!");
86                 WARNING("Capturing alternate data streams will not be supported.");
87                 return;
88         }
89
90         DEBUG("Looking for FindNextStreamW");
91         win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32, "FindNextStreamW");
92         if (!win32func_FindNextStreamW) {
93                 WARNING("Could not find function FindNextStreamW() in Kernel32.dll!");
94                 WARNING("Capturing alternate data streams will not be supported.");
95                 win32func_FindFirstStreamW = NULL;
96         }
97 }
98
99 void
100 win32_global_cleanup()
101 {
102         if (hKernel32 != NULL) {
103                 DEBUG("Closing Kernel32.dll");
104                 FreeLibrary(hKernel32);
105                 hKernel32 = NULL;
106         }
107 }
108
109 static const wchar_t *access_denied_msg =
110 L"         If you are not running this program as the administrator, you may\n"
111  "         need to do so, so that all data and metadata can be backed up.\n"
112  "         Otherwise, there may be no way to access the desired data or\n"
113  "         metadata without taking ownership of the file or directory.\n"
114  ;
115
116 #ifdef ENABLE_ERROR_MESSAGES
117 void
118 win32_error(u32 err_code)
119 {
120         wchar_t *buffer;
121         DWORD nchars;
122         nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
123                                     FORMAT_MESSAGE_ALLOCATE_BUFFER,
124                                 NULL, err_code, 0,
125                                 (wchar_t*)&buffer, 0, NULL);
126         if (nchars == 0) {
127                 ERROR("Error printing error message! "
128                       "Computer will self-destruct in 3 seconds.");
129         } else {
130                 ERROR("Win32 error: %ls", buffer);
131                 LocalFree(buffer);
132         }
133 }
134
135 void
136 win32_error_last()
137 {
138         win32_error(GetLastError());
139 }
140 #endif
141
142 static HANDLE
143 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
144 {
145         return CreateFileW(path,
146                            dwDesiredAccess,
147                            FILE_SHARE_READ,
148                            NULL, /* lpSecurityAttributes */
149                            OPEN_EXISTING,
150                            FILE_FLAG_BACKUP_SEMANTICS |
151                                FILE_FLAG_OPEN_REPARSE_POINT,
152                            NULL /* hTemplateFile */);
153 }
154
155 HANDLE
156 win32_open_file_data_only(const wchar_t *path)
157 {
158         return win32_open_existing_file(path, FILE_READ_DATA);
159 }
160
161 int
162 win32_read_file(const wchar_t *filename,
163                 void *handle, u64 offset, size_t size, void *buf)
164 {
165         HANDLE h = handle;
166         DWORD err;
167         DWORD bytesRead;
168         LARGE_INTEGER liOffset = {.QuadPart = offset};
169
170         wimlib_assert(size <= 0xffffffff);
171
172         if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
173                 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
174                         return 0;
175         err = GetLastError();
176         ERROR("Error reading \"%ls\"", filename);
177         win32_error(err);
178         return WIMLIB_ERR_READ;
179 }
180
181 void
182 win32_close_file(void *handle)
183 {
184         CloseHandle((HANDLE)handle);
185 }
186
187 static u64
188 FILETIME_to_u64(const FILETIME *ft)
189 {
190         return ((u64)ft->dwHighDateTime << 32) | (u64)ft->dwLowDateTime;
191 }
192
193 static int
194 win32_get_short_name(struct wim_dentry *dentry, const wchar_t *path)
195 {
196         WIN32_FIND_DATAW dat;
197         if (FindFirstFileW(path, &dat) && dat.cAlternateFileName[0] != L'\0') {
198                 size_t short_name_nbytes = wcslen(dat.cAlternateFileName) *
199                                            sizeof(wchar_t);
200                 size_t n = short_name_nbytes + sizeof(wchar_t);
201                 dentry->short_name = MALLOC(n);
202                 if (!dentry->short_name)
203                         return WIMLIB_ERR_NOMEM;
204                 memcpy(dentry->short_name, dat.cAlternateFileName, n);
205                 dentry->short_name_nbytes = short_name_nbytes;
206         }
207         return 0;
208 }
209
210 static int
211 win32_get_security_descriptor(struct wim_dentry *dentry,
212                               struct sd_set *sd_set,
213                               const wchar_t *path)
214 {
215         SECURITY_INFORMATION requestedInformation;
216         DWORD lenNeeded = 0;
217         BOOL status;
218         DWORD err;
219
220         requestedInformation = DACL_SECURITY_INFORMATION |
221                                SACL_SECURITY_INFORMATION |
222                                OWNER_SECURITY_INFORMATION |
223                                GROUP_SECURITY_INFORMATION;
224         /* Request length of security descriptor */
225         status = GetFileSecurityW(path, requestedInformation,
226                                   NULL, 0, &lenNeeded);
227         err = GetLastError();
228         if (!status && err == ERROR_INSUFFICIENT_BUFFER) {
229                 DWORD len = lenNeeded;
230                 char buf[len];
231                 if (GetFileSecurityW(path, requestedInformation,
232                                      (PSECURITY_DESCRIPTOR)buf, len, &lenNeeded))
233                 {
234                         int security_id = sd_set_add_sd(sd_set, buf, len);
235                         if (security_id < 0)
236                                 return WIMLIB_ERR_NOMEM;
237                         else {
238                                 dentry->d_inode->i_security_id = security_id;
239                                 return 0;
240                         }
241                 } else {
242                         err = GetLastError();
243                 }
244         }
245
246         if (err == ERROR_ACCESS_DENIED) {
247                 WARNING("Failed to read security descriptor of \"%ls\": "
248                         "Access denied!\n%ls", path, access_denied_msg);
249                 return 0;
250         } else {
251                 ERROR("Failed to read security descriptor of \"%ls\"", path);
252                 win32_error(err);
253                 return WIMLIB_ERR_READ;
254         }
255 }
256
257 static int
258 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
259                                   const wchar_t *path,
260                                   const size_t path_num_chars,
261                                   struct wim_lookup_table *lookup_table,
262                                   struct sd_set *sd_set,
263                                   const struct capture_config *config,
264                                   int add_image_flags,
265                                   wimlib_progress_func_t progress_func);
266
267 /* Reads the directory entries of directory using a Win32 API and recursively
268  * calls win32_build_dentry_tree() on them. */
269 static int
270 win32_recurse_directory(struct wim_dentry *root,
271                         const wchar_t *dir_path,
272                         const size_t dir_path_num_chars,
273                         struct wim_lookup_table *lookup_table,
274                         struct sd_set *sd_set,
275                         const struct capture_config *config,
276                         int add_image_flags,
277                         wimlib_progress_func_t progress_func)
278 {
279         WIN32_FIND_DATAW dat;
280         HANDLE hFind;
281         DWORD err;
282         int ret;
283
284         {
285                 /* Begin reading the directory by calling FindFirstFileW.
286                  * Unlike UNIX opendir(), FindFirstFileW has file globbing built
287                  * into it.  But this isn't what we actually want, so just add a
288                  * dummy glob to get all entries. */
289                 wchar_t pattern_buf[dir_path_num_chars + 3];
290                 swprintf(pattern_buf, L"%ls/*", dir_path);
291                 hFind = FindFirstFileW(pattern_buf, &dat);
292         }
293         if (hFind == INVALID_HANDLE_VALUE) {
294                 err = GetLastError();
295                 if (err == ERROR_FILE_NOT_FOUND) {
296                         return 0;
297                 } else {
298                         ERROR("Failed to read directory \"%ls\"", dir_path);
299                         win32_error(err);
300                         return WIMLIB_ERR_READ;
301                 }
302         }
303         ret = 0;
304         do {
305                 /* Skip . and .. entries */
306                 if (wcscmp(dat.cFileName, L".") && wcscmp(dat.cFileName, L".."))
307                 {
308                         size_t filename_num_chars = wcslen(dat.cFileName);
309                         size_t new_path_num_chars = dir_path_num_chars + 1 +
310                                                     filename_num_chars;
311                         wchar_t new_path[new_path_num_chars + 1];
312
313                         swprintf(new_path, L"%ls/%ls", dir_path, dat.cFileName);
314
315                         struct wim_dentry *child;
316                         ret = win32_build_dentry_tree_recursive(&child,
317                                                                 new_path,
318                                                                 new_path_num_chars,
319                                                                 lookup_table,
320                                                                 sd_set,
321                                                                 config,
322                                                                 add_image_flags,
323                                                                 progress_func);
324                         if (ret)
325                                 goto out_find_close;
326                         if (child)
327                                 dentry_add_child(root, child);
328                 }
329         } while (FindNextFileW(hFind, &dat));
330         err = GetLastError();
331         if (err != ERROR_NO_MORE_FILES) {
332                 ERROR("Failed to read directory \"%ls\"", dir_path);
333                 win32_error(err);
334                 if (ret == 0)
335                         ret = WIMLIB_ERR_READ;
336         }
337 out_find_close:
338         FindClose(hFind);
339         return ret;
340 }
341
342 /* Load a reparse point into a WIM inode.  It is just stored in memory.
343  *
344  * @hFile:  Open handle to a reparse point, with permission to read the reparse
345  *          data.
346  *
347  * @inode:  WIM inode for the reparse point.
348  *
349  * @lookup_table:  Stream lookup table for the WIM; an entry will be added to it
350  *                 for the reparse point unless an entry already exists for
351  *                 the exact same data stream.
352  *
353  * @path:  External path to the reparse point.  Used for error messages only.
354  *
355  * Returns 0 on success; nonzero on failure. */
356 static int
357 win32_capture_reparse_point(HANDLE hFile,
358                             struct wim_inode *inode,
359                             struct wim_lookup_table *lookup_table,
360                             const wchar_t *path)
361 {
362         /* "Reparse point data, including the tag and optional GUID,
363          * cannot exceed 16 kilobytes." - MSDN  */
364         char reparse_point_buf[16 * 1024];
365         DWORD bytesReturned;
366
367         if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT,
368                              NULL, /* "Not used with this operation; set to NULL" */
369                              0, /* "Not used with this operation; set to 0" */
370                              reparse_point_buf, /* "A pointer to a buffer that
371                                                    receives the reparse point data */
372                              sizeof(reparse_point_buf), /* "The size of the output
373                                                            buffer, in bytes */
374                              &bytesReturned,
375                              NULL))
376         {
377                 DWORD err = GetLastError();
378                 ERROR("Failed to get reparse data of \"%ls\"", path);
379                 win32_error(err);
380                 return WIMLIB_ERR_READ;
381         }
382         if (bytesReturned < 8) {
383                 ERROR("Reparse data on \"%ls\" is invalid", path);
384                 return WIMLIB_ERR_READ;
385         }
386         inode->i_reparse_tag = le32_to_cpu(*(u32*)reparse_point_buf);
387         return inode_add_ads_with_data(inode, L"",
388                                        reparse_point_buf + 8,
389                                        bytesReturned - 8, lookup_table);
390 }
391
392 /* Calculate the SHA1 message digest of a Win32 data stream, which may be either
393  * an unnamed or named data stream.
394  *
395  * @path:       Path to the file, with the stream noted at the end for named
396  *              streams.  UTF-16LE encoding.
397  *
398  * @hash:       On success, the SHA1 message digest of the stream is written to
399  *              this location.
400  *
401  * Returns 0 on success; nonzero on failure.
402  */
403 static int
404 win32_sha1sum(const wchar_t *path, u8 hash[SHA1_HASH_SIZE])
405 {
406         HANDLE hFile;
407         SHA_CTX ctx;
408         u8 buf[32768];
409         DWORD bytesRead;
410         int ret;
411
412         hFile = win32_open_file_data_only(path);
413         if (hFile == INVALID_HANDLE_VALUE)
414                 return WIMLIB_ERR_OPEN;
415
416         sha1_init(&ctx);
417         for (;;) {
418                 if (!ReadFile(hFile, buf, sizeof(buf), &bytesRead, NULL)) {
419                         ret = WIMLIB_ERR_READ;
420                         goto out_close_handle;
421                 }
422                 if (bytesRead == 0)
423                         break;
424                 sha1_update(&ctx, buf, bytesRead);
425         }
426         ret = 0;
427         sha1_final(hash, &ctx);
428 out_close_handle:
429         CloseHandle(hFile);
430         return ret;
431 }
432
433 /* Scans an unnamed or named stream of a Win32 file (not a reparse point
434  * stream); calculates its SHA1 message digest and either creates a `struct
435  * wim_lookup_table_entry' in memory for it, or uses an existing 'struct
436  * wim_lookup_table_entry' for an identical stream.
437  *
438  * @path:               Path to the file (UTF-16LE).
439  *
440  * @path_num_chars:     Number of 2-byte characters in @path.
441  *
442  * @inode:              WIM inode to save the stream into.
443  *
444  * @lookup_table:       Stream lookup table for the WIM.
445  *
446  * @dat:                A `WIN32_FIND_STREAM_DATA' structure that specifies the
447  *                      stream name.
448  *
449  * Returns 0 on success; nonzero on failure.
450  */
451 static int
452 win32_capture_stream(const wchar_t *path,
453                      size_t path_num_chars,
454                      struct wim_inode *inode,
455                      struct wim_lookup_table *lookup_table,
456                      WIN32_FIND_STREAM_DATA *dat)
457 {
458         struct wim_ads_entry *ads_entry;
459         u8 hash[SHA1_HASH_SIZE];
460         struct wim_lookup_table_entry *lte;
461         int ret;
462         wchar_t *stream_name, *colon;
463         size_t stream_name_nchars;
464         bool is_named_stream;
465         wchar_t *spath;
466         size_t spath_nchars;
467         DWORD err;
468         size_t spath_buf_nbytes;
469         const wchar_t *relpath_prefix;
470         const wchar_t *colonchar;
471
472         /* The stream name should be returned as :NAME:TYPE */
473         stream_name = dat->cStreamName;
474         if (*stream_name != L':')
475                 goto out_invalid_stream_name;
476         stream_name += 1;
477         colon = wcschr(stream_name, L':');
478         if (colon == NULL)
479                 goto out_invalid_stream_name;
480
481         if (wcscmp(colon + 1, L"$DATA")) {
482                 /* Not a DATA stream */
483                 ret = 0;
484                 goto out;
485         }
486
487         *colon = '\0';
488
489         stream_name_nchars = colon - stream_name;
490         is_named_stream = (stream_name_nchars != 0);
491
492         if (is_named_stream) {
493                 /* Allocate an ADS entry for the named stream. */
494                 ads_entry = inode_add_ads_utf16le(inode, stream_name,
495                                                   stream_name_nchars * sizeof(wchar_t));
496                 if (!ads_entry) {
497                         ret = WIMLIB_ERR_NOMEM;
498                         goto out;
499                 }
500         }
501
502         /* Create a UTF-16LE string @spath that gives the filename, then a
503          * colon, then the stream name.  Or, if it's an unnamed stream, just the
504          * filename.  It is MALLOC()'ed so that it can be saved in the
505          * wim_lookup_table_entry if needed.
506          *
507          * As yet another special case, relative paths need to be changed to
508          * begin with an explicit "./" so that, for example, a file t:ads, where
509          * :ads is the part we added, is not interpreted as a file on the t:
510          * drive. */
511         spath_nchars = path_num_chars;
512         relpath_prefix = L"";
513         colonchar = L"";
514         if (is_named_stream) {
515                 spath_nchars += 1 + stream_name_nchars;
516                 colonchar = L":";
517                 if (path_num_chars == 1 &&
518                     path[0] != L'/' &&
519                     path[0] != L'\\')
520                 {
521                         spath_nchars += 2;
522                         relpath_prefix = L"./";
523                 }
524         }
525
526         spath_buf_nbytes = (spath_nchars + 1) * sizeof(wchar_t);
527         spath = MALLOC(spath_buf_nbytes);
528
529         swprintf(spath, L"%ls%ls%ls%ls",
530                  relpath_prefix, path, colonchar, stream_name);
531
532         ret = win32_sha1sum(spath, hash);
533         if (ret) {
534                 err = GetLastError();
535                 ERROR("Failed to read \"%ls\" to calculate SHA1sum", spath);
536                 win32_error(err);
537                 goto out_free_spath;
538         }
539
540         lte = __lookup_resource(lookup_table, hash);
541         if (lte) {
542                 /* Use existing wim_lookup_table_entry that has the same SHA1
543                  * message digest */
544                 lte->refcnt++;
545         } else {
546                 /* Make a new wim_lookup_table_entry */
547                 lte = new_lookup_table_entry();
548                 if (!lte) {
549                         ret = WIMLIB_ERR_NOMEM;
550                         goto out_free_spath;
551                 }
552                 lte->file_on_disk = spath;
553                 lte->win32_file_on_disk_fp = INVALID_HANDLE_VALUE;
554                 spath = NULL;
555                 lte->resource_location = RESOURCE_WIN32;
556                 lte->resource_entry.original_size = (uint64_t)dat->StreamSize.QuadPart;
557                 lte->resource_entry.size = (uint64_t)dat->StreamSize.QuadPart;
558                 copy_hash(lte->hash, hash);
559                 lookup_table_insert(lookup_table, lte);
560         }
561         if (is_named_stream)
562                 ads_entry->lte = lte;
563         else
564                 inode->i_lte = lte;
565 out_free_spath:
566         FREE(spath);
567 out:
568         return ret;
569 out_invalid_stream_name:
570         ERROR("Invalid stream name: \"%ls:%ls\"", path, dat->cStreamName);
571         ret = WIMLIB_ERR_READ;
572         goto out;
573 }
574
575 /* Scans a Win32 file for unnamed and named data streams (not reparse point
576  * streams).
577  *
578  * @path:               Path to the file (UTF-16LE).
579  *
580  * @path_num_chars:     Number of 2-byte characters in @path.
581  *
582  * @inode:              WIM inode to save the stream into.
583  *
584  * @lookup_table:       Stream lookup table for the WIM.
585  *
586  * @file_size:          Size of unnamed data stream.  (Used only if alternate
587  *                      data streams API appears to be unavailable.)
588  *
589  * Returns 0 on success; nonzero on failure.
590  */
591 static int
592 win32_capture_streams(const wchar_t *path,
593                       size_t path_num_chars,
594                       struct wim_inode *inode,
595                       struct wim_lookup_table *lookup_table,
596                       u64 file_size)
597 {
598         WIN32_FIND_STREAM_DATA dat;
599         int ret;
600         HANDLE hFind;
601         DWORD err;
602
603         if (win32func_FindFirstStreamW == NULL)
604                 goto unnamed_only;
605
606         hFind = win32func_FindFirstStreamW(path, FindStreamInfoStandard, &dat, 0);
607         if (hFind == INVALID_HANDLE_VALUE) {
608                 err = GetLastError();
609
610                 if (err == ERROR_CALL_NOT_IMPLEMENTED)
611                         goto unnamed_only;
612
613                 /* Seems legal for this to return ERROR_HANDLE_EOF on reparse
614                  * points and directories */
615                 if ((inode->i_attributes &
616                     (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
617                     && err == ERROR_HANDLE_EOF)
618                 {
619                         return 0;
620                 } else {
621                         if (err == ERROR_ACCESS_DENIED) {
622                                 WARNING("Failed to look up data streams "
623                                         "of \"%ls\": Access denied!\n%ls",
624                                         path, access_denied_msg);
625                                 return 0;
626                         } else {
627                                 ERROR("Failed to look up data streams "
628                                       "of \"%ls\"", path);
629                                 win32_error(err);
630                                 return WIMLIB_ERR_READ;
631                         }
632                 }
633         }
634         do {
635                 ret = win32_capture_stream(path,
636                                            path_num_chars,
637                                            inode, lookup_table,
638                                            &dat);
639                 if (ret)
640                         goto out_find_close;
641         } while (win32func_FindNextStreamW(hFind, &dat));
642         err = GetLastError();
643         if (err != ERROR_HANDLE_EOF) {
644                 ERROR("Win32 API: Error reading data streams from \"%ls\"", path);
645                 win32_error(err);
646                 ret = WIMLIB_ERR_READ;
647         }
648 out_find_close:
649         FindClose(hFind);
650         return ret;
651 unnamed_only:
652         if (inode->i_attributes &
653              (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
654         {
655                 ret = 0;
656         } else {
657                 wcscpy(dat.cStreamName, L"::$DATA");
658                 dat.StreamSize.QuadPart = file_size;
659                 ret = win32_capture_stream(path,
660                                            path_num_chars,
661                                            inode, lookup_table,
662                                            &dat);
663         }
664         return ret;
665 }
666
667 static int
668 win32_build_dentry_tree_recursive(struct wim_dentry **root_ret,
669                                   const wchar_t *path,
670                                   const size_t path_num_chars,
671                                   struct wim_lookup_table *lookup_table,
672                                   struct sd_set *sd_set,
673                                   const struct capture_config *config,
674                                   int add_image_flags,
675                                   wimlib_progress_func_t progress_func)
676 {
677         struct wim_dentry *root = NULL;
678         struct wim_inode *inode;
679         DWORD err;
680         u64 file_size;
681         int ret = 0;
682
683         if (exclude_path(path, config, true)) {
684                 if (add_image_flags & WIMLIB_ADD_IMAGE_FLAG_ROOT) {
685                         ERROR("Cannot exclude the root directory from capture");
686                         ret = WIMLIB_ERR_INVALID_CAPTURE_CONFIG;
687                         goto out;
688                 }
689                 if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
690                     && progress_func)
691                 {
692                         union wimlib_progress_info info;
693                         info.scan.cur_path = path;
694                         info.scan.excluded = true;
695                         progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
696                 }
697                 goto out;
698         }
699
700         if ((add_image_flags & WIMLIB_ADD_IMAGE_FLAG_VERBOSE)
701             && progress_func)
702         {
703                 union wimlib_progress_info info;
704                 info.scan.cur_path = path;
705                 info.scan.excluded = false;
706                 progress_func(WIMLIB_PROGRESS_MSG_SCAN_DENTRY, &info);
707         }
708
709         HANDLE hFile = win32_open_existing_file(path,
710                                                 FILE_READ_DATA | FILE_READ_ATTRIBUTES);
711         if (hFile == INVALID_HANDLE_VALUE) {
712                 err = GetLastError();
713                 ERROR("Win32 API: Failed to open \"%ls\"", path);
714                 win32_error(err);
715                 ret = WIMLIB_ERR_OPEN;
716                 goto out;
717         }
718
719         BY_HANDLE_FILE_INFORMATION file_info;
720         if (!GetFileInformationByHandle(hFile, &file_info)) {
721                 err = GetLastError();
722                 ERROR("Win32 API: Failed to get file information for \"%ls\"",
723                       path);
724                 win32_error(err);
725                 ret = WIMLIB_ERR_STAT;
726                 goto out_close_handle;
727         }
728
729         /* Create a WIM dentry */
730         ret = new_dentry_with_timeless_inode(path_basename_with_len(path, path_num_chars),
731                                              &root);
732         if (ret)
733                 goto out_close_handle;
734
735         /* Start preparing the associated WIM inode */
736         inode = root->d_inode;
737
738         inode->i_attributes = file_info.dwFileAttributes;
739         inode->i_creation_time = FILETIME_to_u64(&file_info.ftCreationTime);
740         inode->i_last_write_time = FILETIME_to_u64(&file_info.ftLastWriteTime);
741         inode->i_last_access_time = FILETIME_to_u64(&file_info.ftLastAccessTime);
742         inode->i_ino = ((u64)file_info.nFileIndexHigh << 32) |
743                         (u64)file_info.nFileIndexLow;
744
745         inode->i_resolved = 1;
746         add_image_flags &= ~(WIMLIB_ADD_IMAGE_FLAG_ROOT | WIMLIB_ADD_IMAGE_FLAG_SOURCE);
747
748         /* Get DOS name and security descriptor (if any). */
749         ret = win32_get_short_name(root, path);
750         if (ret)
751                 goto out_close_handle;
752
753         if (!(add_image_flags & WIMLIB_ADD_IMAGE_FLAG_NO_ACLS)) {
754                 ret = win32_get_security_descriptor(root, sd_set, path);
755                 if (ret)
756                         goto out_close_handle;
757         }
758
759         file_size = ((u64)file_info.nFileSizeHigh << 32) |
760                      (u64)file_info.nFileSizeLow;
761
762         if (inode_is_directory(inode)) {
763                 /* Directory (not a reparse point) --- recurse to children */
764
765                 /* But first... directories may have alternate data streams that
766                  * need to be captured. */
767                 ret = win32_capture_streams(path,
768                                             path_num_chars,
769                                             inode,
770                                             lookup_table,
771                                             file_size);
772                 if (ret)
773                         goto out_close_handle;
774                 ret = win32_recurse_directory(root,
775                                               path,
776                                               path_num_chars,
777                                               lookup_table,
778                                               sd_set,
779                                               config,
780                                               add_image_flags,
781                                               progress_func);
782         } else if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
783                 /* Reparse point: save the reparse tag and data */
784                 ret = win32_capture_reparse_point(hFile,
785                                                   inode,
786                                                   lookup_table,
787                                                   path);
788         } else {
789                 /* Not a directory, not a reparse point; capture the default
790                  * file contents and any alternate data streams. */
791                 ret = win32_capture_streams(path,
792                                             path_num_chars,
793                                             inode,
794                                             lookup_table,
795                                             file_size);
796         }
797 out_close_handle:
798         CloseHandle(hFile);
799 out:
800         if (ret == 0)
801                 *root_ret = root;
802         else
803                 free_dentry_tree(root, lookup_table);
804         return ret;
805 }
806
807 /* Win32 version of capturing a directory tree */
808 int
809 win32_build_dentry_tree(struct wim_dentry **root_ret,
810                         const wchar_t *root_disk_path,
811                         struct wim_lookup_table *lookup_table,
812                         struct sd_set *sd_set,
813                         const struct capture_config *config,
814                         int add_image_flags,
815                         wimlib_progress_func_t progress_func,
816                         void *extra_arg)
817 {
818         size_t path_nchars;
819         wchar_t *path;
820         int ret;
821
822         path_nchars = wcslen(root_disk_path);
823         if (path_nchars > 32767)
824                 return WIMLIB_ERR_INVALID_PARAM;
825
826         /* There is no check for overflow later when this buffer is being used!
827          * But the max path length on NTFS is 32767 characters, and paths need
828          * to be written specially to even go past 260 characters, so we should
829          * be okay with 32770 characters. */
830         path = MALLOC(32770 * sizeof(wchar_t));
831         if (!path)
832                 return WIMLIB_ERR_NOMEM;
833
834         wmemcpy(path, root_disk_path, path_nchars + 1);
835
836         ret = win32_build_dentry_tree_recursive(root_ret,
837                                                 path,
838                                                 path_nchars,
839                                                 lookup_table,
840                                                 sd_set,
841                                                 config,
842                                                 add_image_flags,
843                                                 progress_func);
844         FREE(path);
845         return ret;
846 }
847
848 /* Replacement for POSIX fnmatch() (partial functionality only) */
849 int
850 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
851 {
852         if (PathMatchSpecW(string, pattern))
853                 return 0;
854         else
855                 return FNM_NOMATCH;
856 }
857
858 static int
859 win32_set_reparse_data(HANDLE h,
860                        u32 reparse_tag,
861                        const struct wim_lookup_table_entry *lte,
862                        const wchar_t *path)
863 {
864         int ret;
865         u8 *buf;
866         size_t len;
867
868         if (!lte) {
869                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
870                         path);
871                 return 0;
872         }
873         len = wim_resource_size(lte);
874         if (len > 16 * 1024 - 8) {
875                 WARNING("\"%ls\": reparse data too long!", path);
876                 return 0;
877         }
878
879         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
880          * leave 8 bytes of space for them at the beginning of the buffer, then
881          * set them manually. */
882         buf = alloca(len + 8);
883         ret = read_full_wim_resource(lte, buf + 8, 0);
884         if (ret)
885                 return ret;
886         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
887         *(u16*)(buf + 4) = cpu_to_le16(len);
888         *(u16*)(buf + 6) = 0;
889
890         /* Set the reparse data on the open file using the
891          * FSCTL_SET_REPARSE_POINT ioctl.
892          *
893          * There are contradictions in Microsoft's documentation for this:
894          *
895          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
896          * lpOverlapped is ignored."
897          *
898          * --- So setting lpOverlapped to NULL is okay since it's ignored.
899          *
900          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
901          * operation returns no output data and lpOutBuffer is NULL,
902          * DeviceIoControl makes use of lpBytesReturned. After such an
903          * operation, the value of lpBytesReturned is meaningless."
904          *
905          * --- So lpOverlapped not really ignored, as it affects another
906          *  parameter.  This is the actual behavior: lpBytesReturned must be
907          *  specified, even though lpBytesReturned is documented as:
908          *
909          *  "Not used with this operation; set to NULL."
910          */
911         DWORD bytesReturned;
912         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
913                              NULL, 0,
914                              &bytesReturned /* lpBytesReturned */,
915                              NULL /* lpOverlapped */))
916         {
917                 DWORD err = GetLastError();
918                 ERROR("Failed to set reparse data on \"%ls\"", path);
919                 win32_error(err);
920                 return WIMLIB_ERR_WRITE;
921         }
922         return 0;
923 }
924
925
926 static int
927 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
928 {
929         HANDLE hStream = arg;
930
931         DWORD nbytes_written;
932         wimlib_assert(len <= 0xffffffff);
933
934         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
935             nbytes_written != len)
936         {
937                 DWORD err = GetLastError();
938                 ERROR("WriteFile(): write error");
939                 win32_error(err);
940                 return WIMLIB_ERR_WRITE;
941         }
942         return 0;
943 }
944
945 static int
946 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
947 {
948         return extract_wim_resource(lte, wim_resource_size(lte),
949                                     win32_extract_chunk, hStream);
950 }
951
952 static bool
953 path_is_root_of_drive(const wchar_t *path)
954 {
955         if (!*path)
956                 return false;
957
958         if (*path != L'/' && *path != L'\\') {
959                 if (*(path + 1) == L':')
960                         path += 2;
961                 else
962                         return false;
963         }
964         while (*path == L'/' || *path == L'\\')
965                 path++;
966         return (*path == L'\0');
967 }
968
969 static int
970 win32_extract_stream(const struct wim_inode *inode,
971                      const wchar_t *path,
972                      const wchar_t *stream_name_utf16,
973                      struct wim_lookup_table_entry *lte,
974                      const struct wim_security_data *security_data)
975 {
976         wchar_t *stream_path;
977         HANDLE h;
978         int ret;
979         DWORD err;
980         DWORD creationDisposition = CREATE_ALWAYS;
981
982         SECURITY_ATTRIBUTES *secattr;
983
984         if (security_data && inode->i_security_id != -1) {
985                 secattr = alloca(sizeof(*secattr));
986                 secattr->nLength = sizeof(*secattr);
987                 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
988                 secattr->bInheritHandle = FALSE;
989         } else {
990                 secattr = NULL;
991         }
992
993         if (stream_name_utf16) {
994                 /* Named stream.  Create a buffer that contains the UTF-16LE
995                  * string [.\]@path:@stream_name_utf16.  This is needed to
996                  * create and open the stream using CreateFileW().  I'm not
997                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
998                  * seems to be unneeded.  Additional note: a "./" prefix needs
999                  * to be added when the path is not absolute to avoid ambiguity
1000                  * with drive letters. */
1001                 size_t stream_path_nchars;
1002                 size_t path_nchars;
1003                 size_t stream_name_nchars;
1004                 const wchar_t *prefix;
1005
1006                 path_nchars = wcslen(path);
1007                 stream_name_nchars = wcslen(stream_name_utf16);
1008                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
1009                 if (path[0] != cpu_to_le16(L'\0') &&
1010                     path[0] != cpu_to_le16(L'/') &&
1011                     path[0] != cpu_to_le16(L'\\') &&
1012                     path[1] != cpu_to_le16(L':'))
1013                 {
1014                         prefix = L"./";
1015                         stream_path_nchars += 2;
1016                 } else {
1017                         prefix = L"";
1018                 }
1019                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1020                 swprintf(stream_path, L"%ls%ls:%ls",
1021                          prefix, path, stream_name_utf16);
1022         } else {
1023                 /* Unnamed stream; its path is just the path to the file itself.
1024                  * */
1025                 stream_path = (wchar_t*)path;
1026
1027                 /* Directories must be created with CreateDirectoryW().  Then
1028                  * the call to CreateFileW() will merely open the directory that
1029                  * was already created rather than creating a new file. */
1030                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1031                         if (!CreateDirectoryW(stream_path, secattr)) {
1032                                 err = GetLastError();
1033                                 switch (err) {
1034                                 case ERROR_ALREADY_EXISTS:
1035                                         break;
1036                                 case ERROR_ACCESS_DENIED:
1037                                         if (path_is_root_of_drive(path))
1038                                                 break;
1039                                         /* Fall through */
1040                                 default:
1041                                         ERROR("Failed to create directory \"%ls\"",
1042                                               stream_path);
1043                                         win32_error(err);
1044                                         ret = WIMLIB_ERR_MKDIR;
1045                                         goto fail;
1046                                 }
1047                         }
1048                         DEBUG("Created directory \"%ls\"", stream_path);
1049                         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1050                                 ret = 0;
1051                                 goto out;
1052                         }
1053                         creationDisposition = OPEN_EXISTING;
1054                 }
1055         }
1056
1057         DEBUG("Opening \"%ls\"", stream_path);
1058         h = CreateFileW(stream_path,
1059                         GENERIC_WRITE,
1060                         0,
1061                         secattr,
1062                         creationDisposition,
1063                         FILE_FLAG_OPEN_REPARSE_POINT |
1064                             FILE_FLAG_BACKUP_SEMANTICS |
1065                             inode->i_attributes,
1066                         NULL);
1067         if (h == INVALID_HANDLE_VALUE) {
1068                 err = GetLastError();
1069                 ERROR("Failed to create \"%ls\"", stream_path);
1070                 win32_error(err);
1071                 ret = WIMLIB_ERR_OPEN;
1072                 goto fail;
1073         }
1074
1075         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1076             stream_name_utf16 == NULL)
1077         {
1078                 DEBUG("Setting reparse data on \"%ls\"", path);
1079                 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1080                 if (ret)
1081                         goto fail_close_handle;
1082         } else {
1083                 if (lte) {
1084                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1085                               stream_path, wim_resource_size(lte));
1086                         ret = do_win32_extract_stream(h, lte);
1087                         if (ret)
1088                                 goto fail_close_handle;
1089                 }
1090         }
1091
1092         DEBUG("Closing \"%ls\"", stream_path);
1093         if (!CloseHandle(h)) {
1094                 err = GetLastError();
1095                 ERROR("Failed to close \"%ls\"", stream_path);
1096                 win32_error(err);
1097                 ret = WIMLIB_ERR_WRITE;
1098                 goto fail;
1099         }
1100         ret = 0;
1101         goto out;
1102 fail_close_handle:
1103         CloseHandle(h);
1104 fail:
1105         ERROR("Error extracting %ls", stream_path);
1106 out:
1107         return ret;
1108 }
1109
1110 /*
1111  * Creates a file, directory, or reparse point and extracts all streams to it
1112  * (unnamed data stream and/or reparse point stream, plus any alternate data
1113  * streams).  This in Win32-specific code.
1114  *
1115  * @inode:      WIM inode for this file or directory.
1116  * @path:       UTF-16LE external path to extract the inode to.
1117  *
1118  * Returns 0 on success; nonzero on failure.
1119  */
1120 static int
1121 win32_extract_streams(const struct wim_inode *inode,
1122                       const wchar_t *path, u64 *completed_bytes_p,
1123                       const struct wim_security_data *security_data)
1124 {
1125         struct wim_lookup_table_entry *unnamed_lte;
1126         int ret;
1127
1128         unnamed_lte = inode_unnamed_lte_resolved(inode);
1129         ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1130                                    security_data);
1131         if (ret)
1132                 goto out;
1133         if (unnamed_lte)
1134                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1135         for (u16 i = 0; i < inode->i_num_ads; i++) {
1136                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1137                 if (ads_entry->stream_name_nbytes != 0) {
1138                         /* Skip special UNIX data entries (see documentation for
1139                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1140                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1141                             && !memcmp(ads_entry->stream_name,
1142                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1143                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1144                                 continue;
1145                         ret = win32_extract_stream(inode,
1146                                                    path,
1147                                                    ads_entry->stream_name,
1148                                                    ads_entry->lte,
1149                                                    NULL);
1150                         if (ret)
1151                                 break;
1152                         if (ads_entry->lte)
1153                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1154                 }
1155         }
1156 out:
1157         return ret;
1158 }
1159
1160 /* Extract a file, directory, reparse point, or hard link to an
1161  * already-extracted file using the Win32 API */
1162 int win32_do_apply_dentry(const wchar_t *output_path,
1163                           size_t output_path_num_chars,
1164                           struct wim_dentry *dentry,
1165                           struct apply_args *args)
1166 {
1167         int ret;
1168         struct wim_inode *inode = dentry->d_inode;
1169         DWORD err;
1170
1171         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1172                 /* Linked file, with another name already extracted.  Create a
1173                  * hard link. */
1174                 DEBUG("Creating hard link \"%ls => %ls\"",
1175                       output_path, inode->i_extracted_file);
1176                 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1177                         ret = 0;
1178                 } else {
1179                         err = GetLastError();
1180                         ERROR("Can't create hard link \"%ls => %ls\"",
1181                               output_path, inode->i_extracted_file);
1182                         ret = WIMLIB_ERR_LINK;
1183                         win32_error(err);
1184                 }
1185         } else {
1186                 /* Create the file, directory, or reparse point, and extract the
1187                  * data streams. */
1188                 const struct wim_security_data *security_data;
1189                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1190                         security_data = NULL;
1191                 else
1192                         security_data = wim_const_security_data(args->w);
1193
1194                 ret = win32_extract_streams(inode, output_path,
1195                                             &args->progress.extract.completed_bytes,
1196                                             security_data);
1197                 if (ret == 0 && inode->i_nlink > 1) {
1198                         /* Save extracted path for a later call to
1199                          * CreateHardLinkW() if this inode has multiple links.
1200                          * */
1201                         inode->i_extracted_file = WSTRDUP(output_path);
1202                         if (!inode->i_extracted_file)
1203                                 ret = WIMLIB_ERR_NOMEM;
1204                 }
1205         }
1206         return ret;
1207 }
1208
1209 /* Set timestamps on an extracted file using the Win32 API */
1210 int
1211 win32_do_apply_dentry_timestamps(const wchar_t *path,
1212                                  size_t path_num_chars,
1213                                  const struct wim_dentry *dentry,
1214                                  const struct apply_args *args)
1215 {
1216         DWORD err;
1217         HANDLE h;
1218         const struct wim_inode *inode = dentry->d_inode;
1219
1220         DEBUG("Opening \"%ls\" to set timestamps", path);
1221         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1222         if (h == INVALID_HANDLE_VALUE) {
1223                 err = GetLastError();
1224                 goto fail;
1225         }
1226
1227         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1228                                  .dwHighDateTime = inode->i_creation_time >> 32};
1229         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1230                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1231         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1232                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1233
1234         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1235         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1236                 err = GetLastError();
1237                 CloseHandle(h);
1238                 goto fail;
1239         }
1240         DEBUG("Closing \"%ls\"", path);
1241         if (!CloseHandle(h)) {
1242                 err = GetLastError();
1243                 goto fail;
1244         }
1245         goto out;
1246 fail:
1247         /* Only warn if setting timestamps failed; still return 0. */
1248         WARNING("Can't set timestamps on \"%ls\"", path);
1249         win32_error(err);
1250 out:
1251         return 0;
1252 }
1253
1254 /* Replacement for POSIX fsync() */
1255 int
1256 fsync(int fd)
1257 {
1258         HANDLE h = (HANDLE)_get_osfhandle(fd);
1259         if (h == INVALID_HANDLE_VALUE) {
1260                 ERROR("Could not get Windows handle for file descriptor");
1261                 win32_error(GetLastError());
1262                 errno = EBADF;
1263                 return -1;
1264         }
1265         if (!FlushFileBuffers(h)) {
1266                 ERROR("Could not flush file buffers to disk");
1267                 win32_error(GetLastError());
1268                 errno = EIO;
1269                 return -1;
1270         }
1271         return 0;
1272 }
1273
1274 /* Use the Win32 API to get the number of processors */
1275 unsigned
1276 win32_get_number_of_processors()
1277 {
1278         SYSTEM_INFO sysinfo;
1279         GetSystemInfo(&sysinfo);
1280         return sysinfo.dwNumberOfProcessors;
1281 }
1282
1283 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
1284  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
1285  * really does the right thing under all circumstances. */
1286 wchar_t *
1287 realpath(const wchar_t *path, wchar_t *resolved_path)
1288 {
1289         DWORD ret;
1290         wimlib_assert(resolved_path == NULL);
1291
1292         ret = GetFullPathNameW(path, 0, NULL, NULL);
1293         if (!ret)
1294                 goto fail_win32;
1295
1296         resolved_path = TMALLOC(ret);
1297         if (!resolved_path)
1298                 goto fail;
1299         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1300         if (!ret) {
1301                 free(resolved_path);
1302                 goto fail_win32;
1303         }
1304         return resolved_path;
1305 fail_win32:
1306         win32_error(GetLastError());
1307 fail:
1308         return NULL;
1309 }
1310
1311 char *
1312 nl_langinfo(nl_item item)
1313 {
1314         wimlib_assert(item == CODESET);
1315         static char buf[64];
1316         strcpy(buf, "Unknown");
1317         return buf;
1318 }
1319
1320 /* rename() on Windows fails if the destination file exists.  And we need to
1321  * make it work on wide characters.  Fix it. */
1322 int
1323 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1324 {
1325         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1326                 return 0;
1327         } else {
1328                 /* As usual, the possible error values are not documented */
1329                 DWORD err = GetLastError();
1330                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1331                       oldpath, newpath);
1332                 win32_error(err);
1333                 errno = 0;
1334                 return -1;
1335         }
1336 }
1337
1338 /* truncate() replacement */
1339 int
1340 win32_truncate_replacement(const wchar_t *path, off_t size)
1341 {
1342         DWORD err = NO_ERROR;
1343         LARGE_INTEGER liOffset;
1344
1345         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1346         if (h == INVALID_HANDLE_VALUE)
1347                 goto fail;
1348
1349         liOffset.QuadPart = size;
1350         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1351                 goto fail_close_handle;
1352
1353         if (!SetEndOfFile(h))
1354                 goto fail_close_handle;
1355         CloseHandle(h);
1356         return 0;
1357
1358 fail_close_handle:
1359         err = GetLastError();
1360         CloseHandle(h);
1361 fail:
1362         if (err == NO_ERROR)
1363                 err = GetLastError();
1364         ERROR("Can't truncate %ls to %"PRIu64" bytes", path, size);
1365         win32_error(err);
1366         errno = -1;
1367         return -1;
1368 }