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() */
31 #include "win32_common.h"
33 #ifdef ENABLE_ERROR_MESSAGES
35 win32_error(DWORD err_code)
39 nchars = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
40 FORMAT_MESSAGE_ALLOCATE_BUFFER,
42 (wchar_t*)&buffer, 0, NULL);
44 ERROR("Error printing error message! "
45 "Computer will self-destruct in 3 seconds.");
47 ERROR("Win32 error: %ls", buffer);
51 #endif /* ENABLE_ERROR_MESSAGES */
54 win32_error_to_errno(DWORD err_code)
56 /* This mapping is that used in Cygwin.
57 * Some of these choices are arbitrary. */
59 case ERROR_ACCESS_DENIED:
61 case ERROR_ACTIVE_CONNECTIONS:
63 case ERROR_ALREADY_EXISTS:
65 case ERROR_BAD_DEVICE:
67 case ERROR_BAD_EXE_FORMAT:
69 case ERROR_BAD_NETPATH:
71 case ERROR_BAD_NET_NAME:
73 case ERROR_BAD_NET_RESP:
75 case ERROR_BAD_PATHNAME:
81 case ERROR_BAD_USERNAME:
83 case ERROR_BEGINNING_OF_MEDIA:
85 case ERROR_BROKEN_PIPE:
91 case ERROR_CALL_NOT_IMPLEMENTED:
93 case ERROR_CANNOT_MAKE:
95 case ERROR_CHILD_NOT_COMPLETE:
97 case ERROR_COMMITMENT_LIMIT:
101 case ERROR_DEVICE_DOOR_OPEN:
103 case ERROR_DEVICE_IN_USE:
105 case ERROR_DEVICE_REQUIRES_CLEANING:
107 case ERROR_DIRECTORY:
109 case ERROR_DIR_NOT_EMPTY:
111 case ERROR_DISK_CORRUPT:
113 case ERROR_DISK_FULL:
119 case ERROR_EAS_DIDNT_FIT:
122 case ERROR_EAS_NOT_SUPPORTED:
125 case ERROR_EA_LIST_INCONSISTENT:
127 case ERROR_EA_TABLE_FULL:
129 case ERROR_END_OF_MEDIA:
131 case ERROR_EOM_OVERFLOW:
133 case ERROR_EXE_MACHINE_TYPE_MISMATCH:
135 case ERROR_EXE_MARKED_INVALID:
137 case ERROR_FILEMARK_DETECTED:
139 case ERROR_FILENAME_EXCED_RANGE:
141 case ERROR_FILE_CORRUPT:
143 case ERROR_FILE_EXISTS:
145 case ERROR_FILE_INVALID:
147 case ERROR_FILE_NOT_FOUND:
149 case ERROR_HANDLE_DISK_FULL:
152 case ERROR_HANDLE_EOF:
155 case ERROR_INVALID_ADDRESS:
157 case ERROR_INVALID_AT_INTERRUPT_TIME:
159 case ERROR_INVALID_BLOCK_LENGTH:
161 case ERROR_INVALID_DATA:
163 case ERROR_INVALID_DRIVE:
165 case ERROR_INVALID_EA_NAME:
167 case ERROR_INVALID_EXE_SIGNATURE:
170 case ERROR_INVALID_FUNCTION:
173 case ERROR_INVALID_HANDLE:
175 case ERROR_INVALID_NAME:
177 case ERROR_INVALID_PARAMETER:
179 case ERROR_INVALID_SIGNAL_NUMBER:
181 case ERROR_IOPL_NOT_ENABLED:
183 case ERROR_IO_DEVICE:
185 case ERROR_IO_INCOMPLETE:
187 case ERROR_IO_PENDING:
189 case ERROR_LOCK_VIOLATION:
191 case ERROR_MAX_THRDS_REACHED:
193 case ERROR_META_EXPANSION_TOO_LONG:
195 case ERROR_MOD_NOT_FOUND:
198 case ERROR_MORE_DATA:
201 case ERROR_NEGATIVE_SEEK:
203 case ERROR_NETNAME_DELETED:
207 case ERROR_NONE_MAPPED:
209 case ERROR_NONPAGED_SYSTEM_RESOURCES:
212 case ERROR_NOT_CONNECTED:
215 case ERROR_NOT_ENOUGH_MEMORY:
217 case ERROR_NOT_OWNER:
220 case ERROR_NOT_READY:
223 case ERROR_NOT_SAME_DEVICE:
225 case ERROR_NOT_SUPPORTED:
229 case ERROR_NO_DATA_DETECTED:
232 case ERROR_NO_MEDIA_IN_DRIVE:
236 case ERROR_NO_MORE_FILES:
240 case ERROR_NO_MORE_ITEMS:
243 case ERROR_NO_MORE_SEARCH_HANDLES:
245 case ERROR_NO_PROC_SLOTS:
247 case ERROR_NO_SIGNAL_SENT:
249 case ERROR_NO_SYSTEM_RESOURCES:
253 case ERROR_OPEN_FAILED:
255 case ERROR_OPEN_FILES:
257 case ERROR_OUTOFMEMORY:
259 case ERROR_PAGED_SYSTEM_RESOURCES:
261 case ERROR_PAGEFILE_QUOTA:
263 case ERROR_PATH_NOT_FOUND:
265 case ERROR_PIPE_BUSY:
267 case ERROR_PIPE_CONNECTED:
270 case ERROR_PIPE_LISTENING:
272 case ERROR_PIPE_NOT_CONNECTED:
275 case ERROR_POSSIBLE_DEADLOCK:
277 case ERROR_PRIVILEGE_NOT_HELD:
279 case ERROR_PROCESS_ABORTED:
281 case ERROR_PROC_NOT_FOUND:
284 case ERROR_REM_NOT_LIST:
287 case ERROR_SECTOR_NOT_FOUND:
291 case ERROR_SETMARK_DETECTED:
293 case ERROR_SHARING_BUFFER_EXCEEDED:
295 case ERROR_SHARING_VIOLATION:
297 case ERROR_SIGNAL_PENDING:
299 case ERROR_SIGNAL_REFUSED:
302 case ERROR_SXS_CANT_GEN_ACTCTX:
305 case ERROR_THREAD_1_INACTIVE:
307 case ERROR_TOO_MANY_LINKS:
309 case ERROR_TOO_MANY_OPEN_FILES:
311 case ERROR_WAIT_NO_CHILDREN:
313 case ERROR_WORKING_SET_QUOTA:
315 case ERROR_WRITE_PROTECT:
323 set_errno_from_GetLastError()
325 errno = win32_error_to_errno(GetLastError());
328 /* Replacement for POSIX fsync() */
334 h = (HANDLE)_get_osfhandle(fd);
335 if (h == INVALID_HANDLE_VALUE)
337 if (!FlushFileBuffers(h))
341 set_errno_from_GetLastError();
346 /* Use the Win32 API to get the number of processors */
348 win32_get_number_of_processors()
351 GetSystemInfo(&sysinfo);
352 return sysinfo.dwNumberOfProcessors;
355 /* Replacement for POSIX-2008 realpath(). Warning: partial functionality only
356 * (resolved_path must be NULL). Also I highly doubt that GetFullPathName
357 * really does the right thing under all circumstances. */
359 realpath(const wchar_t *path, wchar_t *resolved_path)
363 wimlib_assert(resolved_path == NULL);
365 ret = GetFullPathNameW(path, 0, NULL, NULL);
367 err = GetLastError();
371 resolved_path = TMALLOC(ret);
374 ret = GetFullPathNameW(path, ret, resolved_path, NULL);
376 err = GetLastError();
378 resolved_path = NULL;
383 errno = win32_error_to_errno(err);
385 return resolved_path;
388 /* rename() on Windows fails if the destination file exists. And we need to
389 * make it work on wide characters. Fix it. */
391 win32_rename_replacement(const wchar_t *oldpath, const wchar_t *newpath)
393 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING)) {
396 set_errno_from_GetLastError();
401 /* Replacement for POSIX fnmatch() (partial functionality only) */
403 fnmatch(const wchar_t *pattern, const wchar_t *string, int flags)
405 if (PathMatchSpecW(string, pattern))
411 /* truncate() replacement */
413 win32_truncate_replacement(const wchar_t *path, off_t size)
415 DWORD err = NO_ERROR;
416 LARGE_INTEGER liOffset;
418 HANDLE h = win32_open_existing_file(path, GENERIC_WRITE);
419 if (h == INVALID_HANDLE_VALUE)
422 liOffset.QuadPart = size;
423 if (!SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
424 goto fail_close_handle;
426 if (!SetEndOfFile(h))
427 goto fail_close_handle;
432 err = GetLastError();
436 err = GetLastError();
437 errno = win32_error_to_errno(err);
442 /* This really could be replaced with _wcserror_s, but this doesn't seem to
443 * actually be available in MSVCRT.DLL on Windows XP (perhaps it's statically
444 * linked in by Visual Studio...?). */
446 win32_strerror_r_replacement(int errnum, wchar_t *buf, size_t buflen)
448 static pthread_mutex_t strerror_lock = PTHREAD_MUTEX_INITIALIZER;
450 pthread_mutex_lock(&strerror_lock);
451 mbstowcs(buf, strerror(errnum), buflen);
452 buf[buflen - 1] = '\0';
453 pthread_mutex_unlock(&strerror_lock);
458 do_pread_or_pwrite(int fd, void *buf, size_t count, off_t offset,
462 LARGE_INTEGER orig_offset;
463 DWORD bytes_read_or_written;
464 LARGE_INTEGER relative_offset;
465 OVERLAPPED overlapped;
468 wimlib_assert(count <= 0xffffffff);
470 h = (HANDLE)_get_osfhandle(fd);
471 if (h == INVALID_HANDLE_VALUE)
474 /* Get original position */
475 relative_offset.QuadPart = 0;
476 if (!SetFilePointerEx(h, relative_offset, &orig_offset, FILE_CURRENT))
479 memset(&overlapped, 0, sizeof(overlapped));
480 overlapped.Offset = offset;
481 overlapped.OffsetHigh = offset >> 32;
483 /* Do the read or write at the specified offset */
485 bret = WriteFile(h, buf, count, &bytes_read_or_written, &overlapped);
487 bret = ReadFile(h, buf, count, &bytes_read_or_written, &overlapped);
491 /* Restore the original position */
492 if (!SetFilePointerEx(h, orig_offset, NULL, FILE_BEGIN))
495 return bytes_read_or_written;
497 set_errno_from_GetLastError();
502 /* Dumb Windows implementation of pread(). It temporarily changes the file
503 * offset, so it is not safe to use with readers/writers on the same file
506 win32_pread(int fd, void *buf, size_t count, off_t offset)
508 return do_pread_or_pwrite(fd, buf, count, offset, false);
511 /* Dumb Windows implementation of pwrite(). It temporarily changes the file
512 * offset, so it is not safe to use with readers/writers on the same file
515 win32_pwrite(int fd, const void *buf, size_t count, off_t offset)
517 return do_pread_or_pwrite(fd, (void*)buf, count, offset, true);
520 /* Dumb Windows implementation of writev(). It writes the vectors one at a
523 win32_writev(int fd, const struct iovec *iov, int iovcnt)
525 ssize_t total_bytes_written = 0;
531 for (int i = 0; i < iovcnt; i++) {
532 ssize_t bytes_written;
534 bytes_written = write(fd, iov[i].iov_base, iov[i].iov_len);
535 if (bytes_written >= 0)
536 total_bytes_written += bytes_written;
537 if (bytes_written != iov[i].iov_len) {
538 if (total_bytes_written == 0)
539 total_bytes_written = -1;
543 return total_bytes_written;
546 /* Given a path, which may not yet exist, get a set of flags that describe the
547 * features of the volume the path is on. */
549 win32_get_vol_flags(const wchar_t *path, unsigned *vol_flags_ret)
555 if (path[0] != L'\0' && path[0] != L'\\' &&
556 path[0] != L'/' && path[1] == L':')
558 /* Path starts with a drive letter; use it. */
559 volume = alloca(4 * sizeof(wchar_t));
565 /* Path does not start with a drive letter; use the volume of
566 * the current working directory. */
569 bret = GetVolumeInformationW(volume, /* lpRootPathName */
570 NULL, /* lpVolumeNameBuffer */
571 0, /* nVolumeNameSize */
572 NULL, /* lpVolumeSerialNumber */
573 NULL, /* lpMaximumComponentLength */
574 &vol_flags, /* lpFileSystemFlags */
575 NULL, /* lpFileSystemNameBuffer */
576 0); /* nFileSystemNameSize */
578 DWORD err = GetLastError();
579 WARNING("Failed to get volume information for path \"%ls\"", path);
581 vol_flags = 0xffffffff;
584 DEBUG("using vol_flags = %x", vol_flags);
585 *vol_flags_ret = vol_flags;
590 win32_open_existing_file(const wchar_t *path, DWORD dwDesiredAccess)
592 return CreateFileW(path,
595 NULL, /* lpSecurityAttributes */
597 FILE_FLAG_BACKUP_SEMANTICS |
598 FILE_FLAG_OPEN_REPARSE_POINT,
599 NULL /* hTemplateFile */);
603 win32_open_file_data_only(const wchar_t *path)
605 return win32_open_existing_file(path, FILE_READ_DATA);
608 /* Pointers to functions that are not available on all targetted versions of
609 * Windows (XP and later). NOTE: The WINAPI annotations seem to be important; I
610 * assume it specifies a certain calling convention. */
612 /* Vista and later */
613 HANDLE (WINAPI *win32func_FindFirstStreamW)(LPCWSTR lpFileName,
614 STREAM_INFO_LEVELS InfoLevel,
615 LPVOID lpFindStreamData,
616 DWORD dwFlags) = NULL;
618 /* Vista and later */
619 BOOL (WINAPI *win32func_FindNextStreamW)(HANDLE hFindStream,
620 LPVOID lpFindStreamData) = NULL;
622 static OSVERSIONINFO windows_version_info = {
623 .dwOSVersionInfoSize = sizeof(OSVERSIONINFO),
626 static HMODULE hKernel32 = NULL;
629 windows_version_is_at_least(unsigned major, unsigned minor)
631 return windows_version_info.dwMajorVersion > major ||
632 (windows_version_info.dwMajorVersion == major &&
633 windows_version_info.dwMinorVersion >= minor);
636 /* Try to dynamically load some functions */
642 if (hKernel32 == NULL) {
643 DEBUG("Loading Kernel32.dll");
644 hKernel32 = LoadLibraryW(L"Kernel32.dll");
645 if (hKernel32 == NULL) {
646 err = GetLastError();
647 WARNING("Can't load Kernel32.dll");
653 win32func_FindFirstStreamW = (void*)GetProcAddress(hKernel32,
655 if (win32func_FindFirstStreamW) {
656 win32func_FindNextStreamW = (void*)GetProcAddress(hKernel32,
658 if (!win32func_FindNextStreamW)
659 win32func_FindFirstStreamW = NULL;
663 GetVersionEx(&windows_version_info);
667 win32_global_cleanup()
669 if (hKernel32 != NULL) {
670 DEBUG("Closing Kernel32.dll");
671 FreeLibrary(hKernel32);
676 #endif /* __WIN32__ */