]> wimlib.net Git - wimlib/blob - src/win32.c
2b26e1cdbdebd72fe9b7c72475fad79d2b98245f
[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 PathMatchSpecA() */
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 = LoadLibraryA("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 \"%s\"", 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         ret = win32_build_dentry_tree_recursive(root_ret,
835                                                 path,
836                                                 path_nchars,
837                                                 lookup_table,
838                                                 sd_set,
839                                                 config,
840                                                 add_image_flags,
841                                                 progress_func);
842         FREE(path);
843         return ret;
844 }
845
846 /* Replacement for POSIX fnmatch() (partial functionality only) */
847 int
848 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
849 {
850         if (PathMatchSpecW(string, pattern))
851                 return 0;
852         else
853                 return FNM_NOMATCH;
854 }
855
856 static int
857 win32_set_reparse_data(HANDLE h,
858                        u32 reparse_tag,
859                        const struct wim_lookup_table_entry *lte,
860                        const wchar_t *path)
861 {
862         int ret;
863         u8 *buf;
864         size_t len;
865
866         if (!lte) {
867                 WARNING("\"%ls\" is marked as a reparse point but had no reparse data",
868                         path);
869                 return 0;
870         }
871         len = wim_resource_size(lte);
872         if (len > 16 * 1024 - 8) {
873                 WARNING("\"%ls\": reparse data too long!", path);
874                 return 0;
875         }
876
877         /* The WIM stream omits the ReparseTag and ReparseDataLength fields, so
878          * leave 8 bytes of space for them at the beginning of the buffer, then
879          * set them manually. */
880         buf = alloca(len + 8);
881         ret = read_full_wim_resource(lte, buf + 8, 0);
882         if (ret)
883                 return ret;
884         *(u32*)(buf + 0) = cpu_to_le32(reparse_tag);
885         *(u16*)(buf + 4) = cpu_to_le16(len);
886         *(u16*)(buf + 6) = 0;
887
888         /* Set the reparse data on the open file using the
889          * FSCTL_SET_REPARSE_POINT ioctl.
890          *
891          * There are contradictions in Microsoft's documentation for this:
892          *
893          * "If hDevice was opened without specifying FILE_FLAG_OVERLAPPED,
894          * lpOverlapped is ignored."
895          *
896          * --- So setting lpOverlapped to NULL is okay since it's ignored.
897          *
898          * "If lpOverlapped is NULL, lpBytesReturned cannot be NULL. Even when an
899          * operation returns no output data and lpOutBuffer is NULL,
900          * DeviceIoControl makes use of lpBytesReturned. After such an
901          * operation, the value of lpBytesReturned is meaningless."
902          *
903          * --- So lpOverlapped not really ignored, as it affects another
904          *  parameter.  This is the actual behavior: lpBytesReturned must be
905          *  specified, even though lpBytesReturned is documented as:
906          *
907          *  "Not used with this operation; set to NULL."
908          */
909         DWORD bytesReturned;
910         if (!DeviceIoControl(h, FSCTL_SET_REPARSE_POINT, buf, len + 8,
911                              NULL, 0,
912                              &bytesReturned /* lpBytesReturned */,
913                              NULL /* lpOverlapped */))
914         {
915                 DWORD err = GetLastError();
916                 ERROR("Failed to set reparse data on \"%ls\"", path);
917                 win32_error(err);
918                 return WIMLIB_ERR_WRITE;
919         }
920         return 0;
921 }
922
923
924 static int
925 win32_extract_chunk(const void *buf, size_t len, u64 offset, void *arg)
926 {
927         HANDLE hStream = arg;
928
929         DWORD nbytes_written;
930         wimlib_assert(len <= 0xffffffff);
931
932         if (!WriteFile(hStream, buf, len, &nbytes_written, NULL) ||
933             nbytes_written != len)
934         {
935                 DWORD err = GetLastError();
936                 ERROR("WriteFile(): write error");
937                 win32_error(err);
938                 return WIMLIB_ERR_WRITE;
939         }
940         return 0;
941 }
942
943 static int
944 do_win32_extract_stream(HANDLE hStream, struct wim_lookup_table_entry *lte)
945 {
946         return extract_wim_resource(lte, wim_resource_size(lte),
947                                     win32_extract_chunk, hStream);
948 }
949
950 static int
951 win32_extract_stream(const struct wim_inode *inode,
952                      const wchar_t *path,
953                      const wchar_t *stream_name_utf16,
954                      struct wim_lookup_table_entry *lte,
955                      const struct wim_security_data *security_data)
956 {
957         wchar_t *stream_path;
958         HANDLE h;
959         int ret;
960         DWORD err;
961         DWORD creationDisposition = CREATE_ALWAYS;
962
963         SECURITY_ATTRIBUTES *secattr;
964
965         if (security_data && inode->i_security_id != -1) {
966                 secattr = alloca(sizeof(*secattr));
967                 secattr->nLength = sizeof(*secattr);
968                 secattr->lpSecurityDescriptor = security_data->descriptors[inode->i_security_id];
969                 secattr->bInheritHandle = FALSE;
970         } else {
971                 secattr = NULL;
972         }
973
974         if (stream_name_utf16) {
975                 /* Named stream.  Create a buffer that contains the UTF-16LE
976                  * string [.\]@path:@stream_name_utf16.  This is needed to
977                  * create and open the stream using CreateFileW().  I'm not
978                  * aware of any other APIs to do this.  Note: the '$DATA' suffix
979                  * seems to be unneeded.  Additional note: a "./" prefix needs
980                  * to be added when the path is not absolute to avoid ambiguity
981                  * with drive letters. */
982                 size_t stream_path_nchars;
983                 size_t path_nchars;
984                 size_t stream_name_nchars;
985                 const wchar_t *prefix;
986
987                 path_nchars = wcslen(path);
988                 stream_name_nchars = wcslen(stream_name_utf16);
989                 stream_path_nchars = path_nchars + 1 + stream_name_nchars;
990                 if (path[0] != cpu_to_le16(L'\0') &&
991                     path[0] != cpu_to_le16(L'/') &&
992                     path[0] != cpu_to_le16(L'\\') &&
993                     path[1] != cpu_to_le16(L':'))
994                 {
995                         prefix = L"./";
996                         stream_path_nchars += 2;
997                 } else {
998                         prefix = L"";
999                 }
1000                 stream_path = alloca((stream_path_nchars + 1) * sizeof(wchar_t));
1001                 swprintf(stream_path, L"%ls%ls:%ls",
1002                          prefix, path, stream_name_utf16);
1003         } else {
1004                 /* Unnamed stream; its path is just the path to the file itself.
1005                  * */
1006                 stream_path = (wchar_t*)path;
1007
1008                 /* Directories must be created with CreateDirectoryW().  Then
1009                  * the call to CreateFileW() will merely open the directory that
1010                  * was already created rather than creating a new file. */
1011                 if (inode->i_attributes & FILE_ATTRIBUTE_DIRECTORY) {
1012                         if (!CreateDirectoryW(stream_path, secattr)) {
1013                                 err = GetLastError();
1014                                 if (err != ERROR_ALREADY_EXISTS) {
1015                                         ERROR("Failed to create directory \"%ls\"",
1016                                               stream_path);
1017                                         win32_error(err);
1018                                         ret = WIMLIB_ERR_MKDIR;
1019                                         goto fail;
1020                                 }
1021                         }
1022                         DEBUG("Created directory \"%ls\"", stream_path);
1023                         if (!(inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
1024                                 ret = 0;
1025                                 goto out;
1026                         }
1027                         creationDisposition = OPEN_EXISTING;
1028                 }
1029         }
1030
1031         DEBUG("Opening \"%ls\"", stream_path);
1032         h = CreateFileW(stream_path,
1033                         GENERIC_WRITE,
1034                         0,
1035                         secattr,
1036                         creationDisposition,
1037                         FILE_FLAG_OPEN_REPARSE_POINT |
1038                             FILE_FLAG_BACKUP_SEMANTICS |
1039                             inode->i_attributes,
1040                         NULL);
1041         if (h == INVALID_HANDLE_VALUE) {
1042                 err = GetLastError();
1043                 ERROR("Failed to create \"%ls\"", stream_path);
1044                 win32_error(err);
1045                 ret = WIMLIB_ERR_OPEN;
1046                 goto fail;
1047         }
1048
1049         if (inode->i_attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
1050             stream_name_utf16 == NULL)
1051         {
1052                 DEBUG("Setting reparse data on \"%ls\"", path);
1053                 ret = win32_set_reparse_data(h, inode->i_reparse_tag, lte, path);
1054                 if (ret)
1055                         goto fail_close_handle;
1056         } else {
1057                 if (lte) {
1058                         DEBUG("Extracting \"%ls\" (len = %"PRIu64")",
1059                               stream_path, wim_resource_size(lte));
1060                         ret = do_win32_extract_stream(h, lte);
1061                         if (ret)
1062                                 goto fail_close_handle;
1063                 }
1064         }
1065
1066         DEBUG("Closing \"%ls\"", stream_path);
1067         if (!CloseHandle(h)) {
1068                 err = GetLastError();
1069                 ERROR("Failed to close \"%ls\"", stream_path);
1070                 win32_error(err);
1071                 ret = WIMLIB_ERR_WRITE;
1072                 goto fail;
1073         }
1074         ret = 0;
1075         goto out;
1076 fail_close_handle:
1077         CloseHandle(h);
1078 fail:
1079         ERROR("Error extracting %ls", stream_path);
1080 out:
1081         return ret;
1082 }
1083
1084 /*
1085  * Creates a file, directory, or reparse point and extracts all streams to it
1086  * (unnamed data stream and/or reparse point stream, plus any alternate data
1087  * streams).  This in Win32-specific code.
1088  *
1089  * @inode:      WIM inode for this file or directory.
1090  * @path:       UTF-16LE external path to extract the inode to.
1091  *
1092  * Returns 0 on success; nonzero on failure.
1093  */
1094 static int
1095 win32_extract_streams(const struct wim_inode *inode,
1096                       const wchar_t *path, u64 *completed_bytes_p,
1097                       const struct wim_security_data *security_data)
1098 {
1099         struct wim_lookup_table_entry *unnamed_lte;
1100         int ret;
1101
1102         unnamed_lte = inode_unnamed_lte_resolved(inode);
1103         ret = win32_extract_stream(inode, path, NULL, unnamed_lte,
1104                                    security_data);
1105         if (ret)
1106                 goto out;
1107         if (unnamed_lte)
1108                 *completed_bytes_p += wim_resource_size(unnamed_lte);
1109         for (u16 i = 0; i < inode->i_num_ads; i++) {
1110                 const struct wim_ads_entry *ads_entry = &inode->i_ads_entries[i];
1111                 if (ads_entry->stream_name_nbytes != 0) {
1112                         /* Skip special UNIX data entries (see documentation for
1113                          * WIMLIB_ADD_IMAGE_FLAG_UNIX_DATA) */
1114                         if (ads_entry->stream_name_nbytes == WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES
1115                             && !memcmp(ads_entry->stream_name,
1116                                        WIMLIB_UNIX_DATA_TAG_UTF16LE,
1117                                        WIMLIB_UNIX_DATA_TAG_UTF16LE_NBYTES))
1118                                 continue;
1119                         ret = win32_extract_stream(inode,
1120                                                    path,
1121                                                    ads_entry->stream_name,
1122                                                    ads_entry->lte,
1123                                                    NULL);
1124                         if (ret)
1125                                 break;
1126                         if (ads_entry->lte)
1127                                 *completed_bytes_p += wim_resource_size(ads_entry->lte);
1128                 }
1129         }
1130 out:
1131         return ret;
1132 }
1133
1134 /* Extract a file, directory, reparse point, or hard link to an
1135  * already-extracted file using the Win32 API */
1136 int win32_do_apply_dentry(const wchar_t *output_path,
1137                           size_t output_path_num_chars,
1138                           struct wim_dentry *dentry,
1139                           struct apply_args *args)
1140 {
1141         int ret;
1142         struct wim_inode *inode = dentry->d_inode;
1143         DWORD err;
1144
1145         if (inode->i_nlink > 1 && inode->i_extracted_file != NULL) {
1146                 /* Linked file, with another name already extracted.  Create a
1147                  * hard link. */
1148                 DEBUG("Creating hard link \"%ls => %ls\"",
1149                       output_path, inode->i_extracted_file);
1150                 if (CreateHardLinkW(output_path, inode->i_extracted_file, NULL)) {
1151                         ret = 0;
1152                 } else {
1153                         err = GetLastError();
1154                         ERROR("Can't create hard link \"%ls => %ls\"",
1155                               output_path, inode->i_extracted_file);
1156                         ret = WIMLIB_ERR_LINK;
1157                         win32_error(err);
1158                 }
1159         } else {
1160                 /* Create the file, directory, or reparse point, and extract the
1161                  * data streams. */
1162                 const struct wim_security_data *security_data;
1163                 if (args->extract_flags & WIMLIB_EXTRACT_FLAG_NOACLS)
1164                         security_data = NULL;
1165                 else
1166                         security_data = wim_const_security_data(args->w);
1167
1168                 ret = win32_extract_streams(inode, output_path,
1169                                             &args->progress.extract.completed_bytes,
1170                                             security_data);
1171                 if (ret == 0 && inode->i_nlink > 1) {
1172                         /* Save extracted path for a later call to
1173                          * CreateHardLinkW() if this inode has multiple links.
1174                          * */
1175                         inode->i_extracted_file = WSTRDUP(output_path);
1176                         if (!inode->i_extracted_file)
1177                                 ret = WIMLIB_ERR_NOMEM;
1178                 }
1179         }
1180         return ret;
1181 }
1182
1183 /* Set timestamps on an extracted file using the Win32 API */
1184 int
1185 win32_do_apply_dentry_timestamps(const wchar_t *path,
1186                                  size_t path_num_chars,
1187                                  const struct wim_dentry *dentry,
1188                                  const struct apply_args *args)
1189 {
1190         DWORD err;
1191         HANDLE h;
1192         int ret;
1193         const struct wim_inode *inode = dentry->d_inode;
1194
1195         DEBUG("Opening \"%ls\" to set timestamps", path);
1196         h = win32_open_existing_file(path, FILE_WRITE_ATTRIBUTES);
1197         if (h == INVALID_HANDLE_VALUE) {
1198                 err = GetLastError();
1199                 goto fail;
1200         }
1201
1202         FILETIME creationTime = {.dwLowDateTime = inode->i_creation_time & 0xffffffff,
1203                                  .dwHighDateTime = inode->i_creation_time >> 32};
1204         FILETIME lastAccessTime = {.dwLowDateTime = inode->i_last_access_time & 0xffffffff,
1205                                   .dwHighDateTime = inode->i_last_access_time >> 32};
1206         FILETIME lastWriteTime = {.dwLowDateTime = inode->i_last_write_time & 0xffffffff,
1207                                   .dwHighDateTime = inode->i_last_write_time >> 32};
1208
1209         DEBUG("Calling SetFileTime() on \"%ls\"", path);
1210         if (!SetFileTime(h, &creationTime, &lastAccessTime, &lastWriteTime)) {
1211                 err = GetLastError();
1212                 CloseHandle(h);
1213                 goto fail;
1214         }
1215         DEBUG("Closing \"%ls\"", path);
1216         if (!CloseHandle(h)) {
1217                 err = GetLastError();
1218                 goto fail;
1219         }
1220         goto out;
1221 fail:
1222         /* Only warn if setting timestamps failed; still return 0. */
1223         WARNING("Can't set timestamps on \"%ls\"", path);
1224         win32_error(err);
1225 out:
1226         return 0;
1227 }
1228
1229 /* Replacement for POSIX fsync() */
1230 int
1231 fsync(int fd)
1232 {
1233         HANDLE h = (HANDLE)_get_osfhandle(fd);
1234         if (h == INVALID_HANDLE_VALUE) {
1235                 ERROR("Could not get Windows handle for file descriptor");
1236                 win32_error(GetLastError());
1237                 errno = EBADF;
1238                 return -1;
1239         }
1240         if (!FlushFileBuffers(h)) {
1241                 ERROR("Could not flush file buffers to disk");
1242                 win32_error(GetLastError());
1243                 errno = EIO;
1244                 return -1;
1245         }
1246         return 0;
1247 }
1248
1249 /* Use the Win32 API to get the number of processors */
1250 unsigned
1251 win32_get_number_of_processors()
1252 {
1253         SYSTEM_INFO sysinfo;
1254         GetSystemInfo(&sysinfo);
1255         return sysinfo.dwNumberOfProcessors;
1256 }
1257
1258 /* Replacement for POSIX-2008 realpath().  Warning: partial functionality only
1259  * (resolved_path must be NULL).   Also I highly doubt that GetFullPathName
1260  * really does the right thing under all circumstances. */
1261 wchar_t *
1262 realpath(const wchar_t *path, wchar_t *resolved_path)
1263 {
1264         DWORD ret;
1265         wimlib_assert(resolved_path == NULL);
1266
1267         ret = GetFullPathNameW(path, 0, NULL, NULL);
1268         if (!ret)
1269                 goto fail_win32;
1270
1271         resolved_path = TMALLOC(ret);
1272         if (!resolved_path)
1273                 goto fail;
1274         ret = GetFullPathNameW(path, ret, resolved_path, NULL);
1275         if (!ret) {
1276                 free(resolved_path);
1277                 goto fail_win32;
1278         }
1279         return resolved_path;
1280 fail_win32:
1281         win32_error(GetLastError());
1282 fail:
1283         return NULL;
1284 }
1285
1286 char *
1287 nl_langinfo(nl_item item)
1288 {
1289         wimlib_assert(item == CODESET);
1290         static char buf[64];
1291         strcpy(buf, "Unknown");
1292         return buf;
1293 }
1294
1295 /* rename() on Windows fails if the destination file exists.  And we need to
1296  * make it work on wide characters.  Fix it. */
1297 int
1298 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
1299 {
1300         if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
1301                 return 0;
1302         } else {
1303                 /* As usual, the possible error values are not documented */
1304                 DWORD err = GetLastError();
1305                 ERROR("MoveFileEx(): Can't rename \"%ls\" to \"%ls\"",
1306                       oldpath, newpath);
1307                 win32_error(err);
1308                 errno = 0;
1309                 return -1;
1310         }
1311 }
1312
1313 /* truncate() replacement */
1314 int
1315 win32_truncate_replacement(const wchar_t *path, off_t size)
1316 {
1317         DWORD err = NO_ERROR;
1318         LARGE_INTEGER liOffset;
1319
1320         HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
1321         if (h == INVALID_HANDLE_VALUE)
1322                 goto fail;
1323
1324         liOffset.QuadPart = size;
1325         if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
1326                 goto fail_close_handle;
1327
1328         if (!SetEndOfFile(h))
1329                 goto fail_close_handle;
1330         CloseHandle(h);
1331         return 0;
1332
1333 fail_close_handle:
1334         err = GetLastError();
1335         CloseHandle(h);
1336 fail:
1337         if (err == NO_ERROR)
1338                 err = GetLastError();
1339         ERROR("Can't truncate %ls to %"PRIu64" bytes", path, size);
1340         win32_error(err);
1341         errno = -1;
1342         return -1;
1343 }