2 * win32_common.c - Windows code common to applying and capturing images, as
3 * well as replacements for various functions not available on Windows, such as
8 * Copyright (C) 2013 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
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)
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
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/.
28 #include <shlwapi.h> /* for PathMatchSpecW() */
32 #include "win32_common.h"
34 #ifdef ENABLE_ERROR_MESSAGES
36 win32_error(DWORD err_code)
40 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
41 FORMAT_MESSAGE_ALLOCATE_BUFFER,
43 (wchar_t*)&buffer, 0, NULL);
45 ERROR("Error printing error message! "
46 "Computer will self-destruct in 3 seconds.");
48 ERROR("Win32 error: %ls", buffer);
52 #endif /* ENABLE_ERROR_MESSAGES */
55 win32_error_to_errno(DWORD err_code)
57 /* This mapping is that used in Cygwin.
58 * Some of these choices are arbitrary. */
60 case ERROR_ACCESS_DENIED:
62 case ERROR_ACTIVE_CONNECTIONS:
64 case ERROR_ALREADY_EXISTS:
66 case ERROR_BAD_DEVICE:
68 case ERROR_BAD_EXE_FORMAT:
70 case ERROR_BAD_NETPATH:
72 case ERROR_BAD_NET_NAME:
74 case ERROR_BAD_NET_RESP:
76 case ERROR_BAD_PATHNAME:
82 case ERROR_BAD_USERNAME:
84 case ERROR_BEGINNING_OF_MEDIA:
86 case ERROR_BROKEN_PIPE:
92 case ERROR_CALL_NOT_IMPLEMENTED:
94 case ERROR_CANNOT_MAKE:
96 case ERROR_CHILD_NOT_COMPLETE:
98 case ERROR_COMMITMENT_LIMIT:
102 case ERROR_DEVICE_DOOR_OPEN:
104 case ERROR_DEVICE_IN_USE:
106 case ERROR_DEVICE_REQUIRES_CLEANING:
108 case ERROR_DIRECTORY:
110 case ERROR_DIR_NOT_EMPTY:
112 case ERROR_DISK_CORRUPT:
114 case ERROR_DISK_FULL:
120 case ERROR_EAS_DIDNT_FIT:
123 case ERROR_EAS_NOT_SUPPORTED:
126 case ERROR_EA_LIST_INCONSISTENT:
128 case ERROR_EA_TABLE_FULL:
130 case ERROR_END_OF_MEDIA:
132 case ERROR_EOM_OVERFLOW:
134 case ERROR_EXE_MACHINE_TYPE_MISMATCH:
136 case ERROR_EXE_MARKED_INVALID:
138 case ERROR_FILEMARK_DETECTED:
140 case ERROR_FILENAME_EXCED_RANGE:
142 case ERROR_FILE_CORRUPT:
144 case ERROR_FILE_EXISTS:
146 case ERROR_FILE_INVALID:
148 case ERROR_FILE_NOT_FOUND:
150 case ERROR_HANDLE_DISK_FULL:
153 case ERROR_HANDLE_EOF:
156 case ERROR_INVALID_ADDRESS:
158 case ERROR_INVALID_AT_INTERRUPT_TIME:
160 case ERROR_INVALID_BLOCK_LENGTH:
162 case ERROR_INVALID_DATA:
164 case ERROR_INVALID_DRIVE:
166 case ERROR_INVALID_EA_NAME:
168 case ERROR_INVALID_EXE_SIGNATURE:
171 case ERROR_INVALID_FUNCTION:
174 case ERROR_INVALID_HANDLE:
176 case ERROR_INVALID_NAME:
178 case ERROR_INVALID_PARAMETER:
180 case ERROR_INVALID_SIGNAL_NUMBER:
182 case ERROR_IOPL_NOT_ENABLED:
184 case ERROR_IO_DEVICE:
186 case ERROR_IO_INCOMPLETE:
188 case ERROR_IO_PENDING:
190 case ERROR_LOCK_VIOLATION:
192 case ERROR_MAX_THRDS_REACHED:
194 case ERROR_META_EXPANSION_TOO_LONG:
196 case ERROR_MOD_NOT_FOUND:
199 case ERROR_MORE_DATA:
202 case ERROR_NEGATIVE_SEEK:
204 case ERROR_NETNAME_DELETED:
208 case ERROR_NONE_MAPPED:
210 case ERROR_NONPAGED_SYSTEM_RESOURCES:
213 case ERROR_NOT_CONNECTED:
216 case ERROR_NOT_ENOUGH_MEMORY:
218 case ERROR_NOT_OWNER:
221 case ERROR_NOT_READY:
224 case ERROR_NOT_SAME_DEVICE:
226 case ERROR_NOT_SUPPORTED:
230 case ERROR_NO_DATA_DETECTED:
233 case ERROR_NO_MEDIA_IN_DRIVE:
237 case ERROR_NO_MORE_FILES:
241 case ERROR_NO_MORE_ITEMS:
244 case ERROR_NO_MORE_SEARCH_HANDLES:
246 case ERROR_NO_PROC_SLOTS:
248 case ERROR_NO_SIGNAL_SENT:
250 case ERROR_NO_SYSTEM_RESOURCES:
254 case ERROR_OPEN_FAILED:
256 case ERROR_OPEN_FILES:
258 case ERROR_OUTOFMEMORY:
260 case ERROR_PAGED_SYSTEM_RESOURCES:
262 case ERROR_PAGEFILE_QUOTA:
264 case ERROR_PATH_NOT_FOUND:
266 case ERROR_PIPE_BUSY:
268 case ERROR_PIPE_CONNECTED:
271 case ERROR_PIPE_LISTENING:
273 case ERROR_PIPE_NOT_CONNECTED:
276 case ERROR_POSSIBLE_DEADLOCK:
278 case ERROR_PRIVILEGE_NOT_HELD:
280 case ERROR_PROCESS_ABORTED:
282 case ERROR_PROC_NOT_FOUND:
285 case ERROR_REM_NOT_LIST:
288 case ERROR_SECTOR_NOT_FOUND:
292 case ERROR_SETMARK_DETECTED:
294 case ERROR_SHARING_BUFFER_EXCEEDED:
296 case ERROR_SHARING_VIOLATION:
298 case ERROR_SIGNAL_PENDING:
300 case ERROR_SIGNAL_REFUSED:
303 case ERROR_SXS_CANT_GEN_ACTCTX:
306 case ERROR_THREAD_1_INACTIVE:
308 case ERROR_TOO_MANY_LINKS:
310 case ERROR_TOO_MANY_OPEN_FILES:
312 case ERROR_WAIT_NO_CHILDREN:
314 case ERROR_WORKING_SET_QUOTA:
316 case ERROR_WRITE_PROTECT:
324 set_errno_from_GetLastError()
326 errno = win32_error_to_errno(GetLastError());
329 /* Replacement for POSIX fsync() */
335 h = (HANDLE)_get_osfhandle(fd);
336 if (h == INVALID_HANDLE_VALUE)
338 if (!FlushFileBuffers(h))
342 set_errno_from_GetLastError();
347 /* Use the Win32 API to get the number of processors */
349 win32_get_number_of_processors()
352 GetSystemInfo(&sysinfo);
353 return sysinfo.dwNumberOfProcessors;
356 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
357 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
358 * really does the right thing under all circumstances. */
360 realpath(const wchar_t *path, wchar_t *resolved_path)
364 wimlib_assert(resolved_path == NULL);
366 ret = GetFullPathNameW(path, 0, NULL, NULL);
368 err = GetLastError();
372 resolved_path = TMALLOC(ret);
375 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
377 err = GetLastError();
379 resolved_path = NULL;
384 errno = win32_error_to_errno(err);
386 return resolved_path;
389 /* rename() on Windows fails if the destination file exists. And we need to
390 * make it work on wide characters. Fix it. */
392 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
394 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
397 set_errno_from_GetLastError();
402 /* Replacement for POSIX fnmatch() (partial functionality only) */
404 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
406 if (PathMatchSpecW(string, pattern))
412 /* truncate() replacement */
414 win32_truncate_replacement(const wchar_t *path, off_t size)
416 DWORD err = NO_ERROR;
417 LARGE_INTEGER liOffset;
419 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
420 if (h == INVALID_HANDLE_VALUE)
423 liOffset.QuadPart = size;
424 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
425 goto fail_close_handle;
427 if (!SetEndOfFile(h))
428 goto fail_close_handle;
433 err = GetLastError();
437 err = GetLastError();
438 errno = win32_error_to_errno(err);
443 /* This really could be replaced with _wcserror_s, but this doesn't seem to
444 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
445 * linked in by Visual Studio...?). */
447 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
449 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
451 pthread_mutex_lock(&strerror_lock);
452 mbstowcs(buf, strerror(errnum), buflen);
453 buf[buflen - 1] = '\0';
454 pthread_mutex_unlock(&strerror_lock);
459 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
463 LARGE_INTEGER orig_offset;
464 DWORD bytes_read_or_written;
465 LARGE_INTEGER relative_offset;
466 OVERLAPPED overlapped;
469 wimlib_assert(count <= 0xffffffff);
471 h = (HANDLE)_get_osfhandle(fd);
472 if (h == INVALID_HANDLE_VALUE)
475 /* Get original position */
476 relative_offset.QuadPart = 0;
477 if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
480 memset(&overlapped, 0, sizeof(overlapped));
481 overlapped.Offset = offset;
482 overlapped.OffsetHigh = offset >> 32;
484 /* Do the read or write at the specified offset */
486 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
488 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
492 /* Restore the original position */
493 if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
496 return bytes_read_or_written;
498 set_errno_from_GetLastError();
503 /* Dumb Windows implementation of pread(). It temporarily changes the file
504 * offset, so it is not safe to use with readers/writers on the same file
507 win32_pread(int fd, void *buf, size_t count, off_t offset)
509 return do_pread_or_pwrite(fd, buf, count, offset, false);
512 /* Dumb Windows implementation of pwrite(). It temporarily changes the file
513 * offset, so it is not safe to use with readers/writers on the same file
516 win32_pwrite(int fd, const void *buf, size_t count, off_t offset)
518 return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
521 /* Dumb Windows implementation of writev(). It writes the vectors one at a
524 win32_writev(int fd, const struct iovec *iov, int iovcnt)
526 ssize_t total_bytes_written = 0;
532 for (int i = 0; i < iovcnt; i++) {
533 ssize_t bytes_written;
535 bytes_written = write(fd, iov[i].iov_base, iov[i].iov_len);
536 if (bytes_written >= 0)
537 total_bytes_written += bytes_written;
538 if (bytes_written != iov[i].iov_len) {
539 if (total_bytes_written == 0)
540 total_bytes_written = -1;
544 return total_bytes_written;
547 /* Given a path, which may not yet exist, get a set of flags that describe the
548 * features of the volume the path is on. */
550 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
556 if (path[0] != L'\0' && path[0] != L'\\' &&
557 path[0] != L'/' && path[1] == L':')
559 /* Path starts with a drive letter; use it. */
560 volume = alloca(4 * sizeof(wchar_t));
566 /* Path does not start with a drive letter; use the volume of
567 * the current working directory. */
570 bret = GetVolumeInformationW(volume, /* lpRootPathName */
571 NULL, /* lpVolumeNameBuffer */
572 0, /* nVolumeNameSize */
573 NULL, /* lpVolumeSerialNumber */
574 NULL, /* lpMaximumComponentLength */
575 &vol_flags, /* lpFileSystemFlags */
576 NULL, /* lpFileSystemNameBuffer */
577 0); /* nFileSystemNameSize */
579 DWORD err = GetLastError();
580 WARNING("Failed to get volume information for path \"%ls\"", path);
582 vol_flags = 0xffffffff;
585 DEBUG("using vol_flags = %x", vol_flags);
586 *vol_flags_ret = vol_flags;
591 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
593 return CreateFileW(path,
596 NULL, /* lpSecurityAttributes */
598 FILE_FLAG_BACKUP_SEMANTICS |
599 FILE_FLAG_OPEN_REPARSE_POINT,
600 NULL /* hTemplateFile */);
604 win32_open_file_data_only(const wchar_t *path)
606 return win32_open_existing_file(path, FILE_READ_DATA);
609 /* Pointers to functions that are not available on all targetted versions of
610 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
611 * assume it specifies a certain calling convention. */
613 /* Vista and later */
614 HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
615 STREAM_INFO_LEVELS InfoLevel,
616 LPVOID lpFindStreamData,
617 DWORD dwFlags) = NULL;
619 /* Vista and later */
620 BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
621 LPVOID lpFindStreamData) = NULL;
623 static OSVERSIONINFO windows_version_info = {
624 .dwOSVersionInfoSize = sizeof(OSVERSIONINFO),
627 static HMODULE hKernel32 = NULL;
630 windows_version_is_at_least(unsigned major, unsigned minor)
632 return windows_version_info.dwMajorVersion > major ||
633 (windows_version_info.dwMajorVersion == major &&
634 windows_version_info.dwMinorVersion >= minor);
637 /* Try to dynamically load some functions */
643 if (hKernel32 == NULL) {
644 DEBUG("Loading Kernel32.dll");
645 hKernel32 = LoadLibraryW(L"Kernel32.dll");
646 if (hKernel32 == NULL) {
647 err = GetLastError();
648 WARNING("Can't load Kernel32.dll");
654 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32,
656 if (win32func_FindFirstStreamW) {
657 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32,
659 if (!win32func_FindNextStreamW)
660 win32func_FindFirstStreamW = NULL;
664 GetVersionEx(&windows_version_info);
668 win32_global_cleanup()
670 if (hKernel32 != NULL) {
671 DEBUG("Closing Kernel32.dll");
672 FreeLibrary(hKernel32);
677 #endif /* __WIN32__ */