1 /* Windows-specific code for wimlib-imagex. */
4 # error "This file contains Windows code"
7 #include "imagex-win32.h"
16 /* Replacement for glob() in Windows native builds that operates on wide
19 win32_wglob(const wchar_t *pattern, int flags,
20 int (*errfunc)(const wchar_t *epath, int eerrno),
29 const wchar_t *backslash, *end_slash;
32 backslash = wcsrchr(pattern, L'\\');
33 end_slash = wcsrchr(pattern, L'/');
35 if (backslash > end_slash)
36 end_slash = backslash;
39 prefix_len = end_slash - pattern + 1;
43 /* This function does not support all functionality of the POSIX glob(),
44 * so make sure the parameters are consistent with supported
46 assert(errfunc == NULL);
47 assert((flags & GLOB_ERR) == GLOB_ERR);
48 assert((flags & ~(GLOB_NOSORT | GLOB_ERR)) == 0);
50 hFind = FindFirstFileW(pattern, &dat);
51 if (hFind == INVALID_HANDLE_VALUE) {
53 if (err == ERROR_FILE_NOT_FOUND) {
57 /* The other possible error codes for FindFirstFile()
58 * are undocumented. */
64 pglob->gl_pathv = NULL;
68 if (pglob->gl_pathc == nspaces) {
72 new_nspaces = nspaces * 2 + 1;
73 pathv = realloc(pglob->gl_pathv,
74 new_nspaces * sizeof(pglob->gl_pathv[0]));
77 pglob->gl_pathv = pathv;
78 nspaces = new_nspaces;
80 size_t filename_len = wcslen(dat.cFileName);
81 size_t len_needed = prefix_len + filename_len;
83 path = malloc((len_needed + 1) * sizeof(wchar_t));
87 wmemcpy(path, pattern, prefix_len);
88 wmemcpy(path + prefix_len, dat.cFileName, filename_len + 1);
89 pglob->gl_pathv[pglob->gl_pathc++] = path;
90 } while (FindNextFileW(hFind, &dat));
93 if (err == ERROR_NO_MORE_FILES) {
97 /* Other possible error codes for FindNextFile() are
113 globfree(glob_t *pglob)
116 for (i = 0; i < pglob->gl_pathc; i++)
117 free(pglob->gl_pathv[i]);
118 free(pglob->gl_pathv);
121 /* Convert a string from the "current Windows codepage" to UTF-16LE. */
123 win32_mbs_to_wcs(const char *mbs, size_t mbs_nbytes, size_t *num_wchars_ret)
125 if (mbs_nbytes > INT_MAX) {
126 fwprintf(stderr, L"ERROR: too much data (%zu bytes)!\n",
130 if (mbs_nbytes == 0) {
132 return (wchar_t*)mbs;
134 int len = MultiByteToWideChar(CP_ACP,
135 MB_ERR_INVALID_CHARS,
142 wchar_t *wcs = malloc(len * sizeof(wchar_t));
144 fwprintf(stderr, L"ERROR: out of memory!\n");
147 int len2 = MultiByteToWideChar(CP_ACP,
148 MB_ERR_INVALID_CHARS,
157 *num_wchars_ret = len;
161 L"ERROR: Invalid multi-byte string in the text file you provided as input!\n"
162 L" Maybe try converting your text file to UTF-16LE?\n"
168 is_path_separator(wchar_t c)
170 return c == L'/' || c == L'\\';
173 /* basename() (modifying, trailing-slash stripping version) for wide-character
174 * strings. Understands both forward and backward slashes. */
176 win32_wbasename(wchar_t *path)
178 wchar_t *p = wcschr(path, L'\0');
181 while (p >= path && is_path_separator(*p))
183 while (p >= path && !is_path_separator(*p))
189 /* Set a file descriptor to binary mode. */
190 void set_fd_to_binary_mode(int fd)
192 _setmode(fd, _O_BINARY);