]> wimlib.net Git - wimlib/blob - src/win32.c
dfa92ffd01169c6b86a18ddd919f4be696be810e
[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 int
953 win32_extract_stream(const struct wim_inode *inode,
954                      const wchar_t *path,
955                      const wchar_t *stream_name_utf16,
956                      struct wim_lookup_table_entry *lte,
957                      const struct wim_security_data *security_data)
958 {
959         wchar_t *stream_path;
960         HANDLE h;
961         int ret;
962         DWORD err;
963         DWORD creationDisposition = CREATE_ALWAYS;
964
965         SECURITY_ATTRIBUTES *secattr;
966
967         if (security_data && inode->i_security_id != -1) {
968                 secattr = alloca(sizeof(*secattr));
969                 secattr->nLength = sizeof(*secattr);
970                 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
971                 secattr->bInheritHandle = FALSE;
972         } else {
973                 secattr = NULL;
974         }
975
976         if (stream_name_utf16) {
977                 /* Named stream.  Create a buffer that contains the UTF-16LE
978                  * string [.\]@path:@stream_name_utf16.  This is needed to
979                  * create and open the stream using CreateFileW().  I'm not
980                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
981                  * seems to be unneeded.  Additional note: a "./" prefix needs
982                  * to be added when the path is not absolute to avoid ambiguity
983                  * with drive letters. */
984                 size_t stream_path_nchars;
985                 size_t path_nchars;
986                 size_t stream_name_nchars;
987                 const wchar_t *prefix;
988
989                 path_nchars = wcslen(path);
990                 stream_name_nchars = wcslen(stream_name_utf16);
991                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
992                 if (path[0] != cpu_to_le16(L'\0') &&
993                     path[0] != cpu_to_le16(L'/') &&
994                     path[0] != cpu_to_le16(L'\\') &&
995                     path[1] != cpu_to_le16(L':'))
996                 {
997                         prefix = L"./";
998                         stream_path_nchars += 2;
999                 } else {
1000                         prefix = L"";
1001                 }
1002                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1003                 swprintf(stream_path, L"%ls%ls:%ls",
1004                          prefix, path, stream_name_utf16);
1005         } else {
1006                 /* Unnamed stream; its path is just the path to the file itself.
1007                  * */
1008                 stream_path = (wchar_t*)path;
1009
1010                 /* Directories must be created with CreateDirectoryW().  Then
1011                  * the call to CreateFileW() will merely open the directory that
1012                  * was already created rather than creating a new file. */
1013                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1014                         if (!CreateDirectoryW(stream_path, secattr)) {
1015                                 err = GetLastError();
1016                                 if (err != ERROR_ALREADY_EXISTS) {
1017                                         ERROR("Failed to create directory \"%ls\"",
1018                                               stream_path);
1019                                         win32_error(err);
1020                                         ret = WIMLIB_ERR_MKDIR;
1021                                         goto fail;
1022                                 }
1023                         }
1024                         DEBUG("Created directory \"%ls\"", stream_path);
1025                         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1026                                 ret = 0;
1027                                 goto out;
1028                         }
1029                         creationDisposition = OPEN_EXISTING;
1030                 }
1031         }
1032
1033         DEBUG("Opening \"%ls\"", stream_path);
1034         h = CreateFileW(stream_path,
1035                         GENERIC_WRITE,
1036                         0,
1037                         secattr,
1038                         creationDisposition,
1039                         FILE_FLAG_OPEN_REPARSE_POINT |
1040                             FILE_FLAG_BACKUP_SEMANTICS |
1041                             inode->i_attributes,
1042                         NULL);
1043         if (h == INVALID_HANDLE_VALUE) {
1044                 err = GetLastError();
1045                 ERROR("Failed to create \"%ls\"", stream_path);
1046                 win32_error(err);
1047                 ret = WIMLIB_ERR_OPEN;
1048                 goto fail;
1049         }
1050
1051         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1052             stream_name_utf16 == NULL)
1053         {
1054                 DEBUG("Setting reparse data on \"%ls\"", path);
1055                 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1056                 if (ret)
1057                         goto fail_close_handle;
1058         } else {
1059                 if (lte) {
1060                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1061                               stream_path, wim_resource_size(lte));
1062                         ret = do_win32_extract_stream(h, lte);
1063                         if (ret)
1064                                 goto fail_close_handle;
1065                 }
1066         }
1067
1068         DEBUG("Closing \"%ls\"", stream_path);
1069         if (!CloseHandle(h)) {
1070                 err = GetLastError();
1071                 ERROR("Failed to close \"%ls\"", stream_path);
1072                 win32_error(err);
1073                 ret = WIMLIB_ERR_WRITE;
1074                 goto fail;
1075         }
1076         ret = 0;
1077         goto out;
1078 fail_close_handle:
1079         CloseHandle(h);
1080 fail:
1081         ERROR("Error extracting %ls", stream_path);
1082 out:
1083         return ret;
1084 }
1085
1086 /*
1087  * Creates a file, directory, or reparse point and extracts all streams to it
1088  * (unnamed data stream and/or reparse point stream, plus any alternate data
1089  * streams).  This in Win32-specific code.
1090  *
1091  * @inode:      WIM inode for this file or directory.
1092  * @path:       UTF-16LE external path to extract the inode to.
1093  *
1094  * Returns 0 on success; nonzero on failure.
1095  */
1096 static int
1097 win32_extract_streams(const struct wim_inode *inode,
1098                       const wchar_t *path, u64 *completed_bytes_p,
1099                       const struct wim_security_data *security_data)
1100 {
1101         struct wim_lookup_table_entry *unnamed_lte;
1102         int ret;
1103
1104         unnamed_lte = inode_unnamed_lte_resolved(inode);
1105         ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1106                                    security_data);
1107         if (ret)
1108                 goto out;
1109         if (unnamed_lte)
1110                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1111         for (u16 i = 0; i < inode->i_num_ads; i++) {
1112                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1113                 if (ads_entry->stream_name_nbytes != 0) {
1114                         /* Skip special UNIX data entries (see documentation for
1115                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1116                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1117                             && !memcmp(ads_entry->stream_name,
1118                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1119                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1120                                 continue;
1121                         ret = win32_extract_stream(inode,
1122                                                    path,
1123                                                    ads_entry->stream_name,
1124                                                    ads_entry->lte,
1125                                                    NULL);
1126                         if (ret)
1127                                 break;
1128                         if (ads_entry->lte)
1129                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1130                 }
1131         }
1132 out:
1133         return ret;
1134 }
1135
1136 /* Extract a file, directory, reparse point, or hard link to an
1137  * already-extracted file using the Win32 API */
1138 int win32_do_apply_dentry(const wchar_t *output_path,
1139                           size_t output_path_num_chars,
1140                           struct wim_dentry *dentry,
1141                           struct apply_args *args)
1142 {
1143         int ret;
1144         struct wim_inode *inode = dentry->d_inode;
1145         DWORD err;
1146
1147         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1148                 /* Linked file, with another name already extracted.  Create a
1149                  * hard link. */
1150                 DEBUG("Creating hard link \"%ls => %ls\"",
1151                       output_path, inode->i_extracted_file);
1152                 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1153                         ret = 0;
1154                 } else {
1155                         err = GetLastError();
1156                         ERROR("Can't create hard link \"%ls => %ls\"",
1157                               output_path, inode->i_extracted_file);
1158                         ret = WIMLIB_ERR_LINK;
1159                         win32_error(err);
1160                 }
1161         } else {
1162                 /* Create the file, directory, or reparse point, and extract the
1163                  * data streams. */
1164                 const struct wim_security_data *security_data;
1165                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1166                         security_data = NULL;
1167                 else
1168                         security_data = wim_const_security_data(args->w);
1169
1170                 ret = win32_extract_streams(inode, output_path,
1171                                             &args->progress.extract.completed_bytes,
1172                                             security_data);
1173                 if (ret == 0 && inode->i_nlink > 1) {
1174                         /* Save extracted path for a later call to
1175                          * CreateHardLinkW() if this inode has multiple links.
1176                          * */
1177                         inode->i_extracted_file = WSTRDUP(output_path);
1178                         if (!inode->i_extracted_file)
1179                                 ret = WIMLIB_ERR_NOMEM;
1180                 }
1181         }
1182         return ret;
1183 }
1184
1185 /* Set timestamps on an extracted file using the Win32 API */
1186 int
1187 win32_do_apply_dentry_timestamps(const wchar_t *path,
1188                                  size_t path_num_chars,
1189                                  const struct wim_dentry *dentry,
1190                                  const struct apply_args *args)
1191 {
1192         DWORD err;
1193         HANDLE h;
1194         const struct wim_inode *inode = dentry->d_inode;
1195
1196         DEBUG("Opening \"%ls\" to set timestamps", path);
1197         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1198         if (h == INVALID_HANDLE_VALUE) {
1199                 err = GetLastError();
1200                 goto fail;
1201         }
1202
1203         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1204                                  .dwHighDateTime = inode->i_creation_time >> 32};
1205         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1206                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1207         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1208                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1209
1210         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1211         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1212                 err = GetLastError();
1213                 CloseHandle(h);
1214                 goto fail;
1215         }
1216         DEBUG("Closing \"%ls\"", path);
1217         if (!CloseHandle(h)) {
1218                 err = GetLastError();
1219                 goto fail;
1220         }
1221         goto out;
1222 fail:
1223         /* Only warn if setting timestamps failed; still return 0. */
1224         WARNING("Can't set timestamps on \"%ls\"", path);
1225         win32_error(err);
1226 out:
1227         return 0;
1228 }
1229
1230 /* Replacement for POSIX fsync() */
1231 int
1232 fsync(int fd)
1233 {
1234         HANDLE h = (HANDLE)_get_osfhandle(fd);
1235         if (h == INVALID_HANDLE_VALUE) {
1236                 ERROR("Could not get Windows handle for file descriptor");
1237                 win32_error(GetLastError());
1238                 errno = EBADF;
1239                 return -1;
1240         }
1241         if (!FlushFileBuffers(h)) {
1242                 ERROR("Could not flush file buffers to disk");
1243                 win32_error(GetLastError());
1244                 errno = EIO;
1245                 return -1;
1246         }
1247         return 0;
1248 }
1249
1250 /* Use the Win32 API to get the number of processors */
1251 unsigned
1252 win32_get_number_of_processors()
1253 {
1254         SYSTEM_INFO sysinfo;
1255         GetSystemInfo(&sysinfo);
1256         return sysinfo.dwNumberOfProcessors;
1257 }
1258
1259 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
1260  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
1261  * really does the right thing under all circumstances. */
1262 wchar_t *
1263 realpath(const wchar_t *path, wchar_t *resolved_path)
1264 {
1265         DWORD ret;
1266         wimlib_assert(resolved_path == NULL);
1267
1268         ret = GetFullPathNameW(path, 0, NULL, NULL);
1269         if (!ret)
1270                 goto fail_win32;
1271
1272         resolved_path = TMALLOC(ret);
1273         if (!resolved_path)
1274                 goto fail;
1275         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1276         if (!ret) {
1277                 free(resolved_path);
1278                 goto fail_win32;
1279         }
1280         return resolved_path;
1281 fail_win32:
1282         win32_error(GetLastError());
1283 fail:
1284         return NULL;
1285 }
1286
1287 char *
1288 nl_langinfo(nl_item item)
1289 {
1290         wimlib_assert(item == CODESET);
1291         static char buf[64];
1292         strcpy(buf, "Unknown");
1293         return buf;
1294 }
1295
1296 /* rename() on Windows fails if the destination file exists.  And we need to
1297  * make it work on wide characters.  Fix it. */
1298 int
1299 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1300 {
1301         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1302                 return 0;
1303         } else {
1304                 /* As usual, the possible error values are not documented */
1305                 DWORD err = GetLastError();
1306                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1307                       oldpath, newpath);
1308                 win32_error(err);
1309                 errno = 0;
1310                 return -1;
1311         }
1312 }
1313
1314 /* truncate() replacement */
1315 int
1316 win32_truncate_replacement(const wchar_t *path, off_t size)
1317 {
1318         DWORD err = NO_ERROR;
1319         LARGE_INTEGER liOffset;
1320
1321         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1322         if (h == INVALID_HANDLE_VALUE)
1323                 goto fail;
1324
1325         liOffset.QuadPart = size;
1326         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1327                 goto fail_close_handle;
1328
1329         if (!SetEndOfFile(h))
1330                 goto fail_close_handle;
1331         CloseHandle(h);
1332         return 0;
1333
1334 fail_close_handle:
1335         err = GetLastError();
1336         CloseHandle(h);
1337 fail:
1338         if (err == NO_ERROR)
1339                 err = GetLastError();
1340         ERROR("Can't truncate %ls to %"PRIu64" bytes", path, size);
1341         win32_error(err);
1342         errno = -1;
1343         return -1;
1344 }