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