2 * Windows support routines for PhysicsFS.
4 * Please see the file LICENSE.txt in the source's root directory.
6 * This file written by Ryan C. Gordon, and made sane by Gregory S. Read.
9 #define __PHYSICSFS_INTERNAL__
10 #include "physfs_platforms.h"
12 #ifdef PHYSFS_PLATFORM_WINDOWS
14 /* Forcibly disable UNICODE, since we manage this ourselves. */
27 #include "physfs_internal.h"
29 #define LOWORDER_UINT64(pos) ((PHYSFS_uint32) (pos & 0xFFFFFFFF))
30 #define HIGHORDER_UINT64(pos) ((PHYSFS_uint32) ((pos >> 32) & 0xFFFFFFFF))
33 * Users without the platform SDK don't have this defined. The original docs
34 * for SetFilePointer() just said to compare with 0xFFFFFFFF, so this should
37 #define PHYSFS_INVALID_SET_FILE_POINTER 0xFFFFFFFF
40 #define PHYSFS_INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
42 /* Not defined before the Vista SDK. */
43 #define PHYSFS_IO_REPARSE_TAG_SYMLINK 0xA000000C
46 #define UTF8_TO_UNICODE_STACK_MACRO(w_assignto, str) { \
50 const PHYSFS_uint64 len = (PHYSFS_uint64) ((strlen(str) + 1) * 2); \
51 w_assignto = (WCHAR *) __PHYSFS_smallAlloc(len); \
52 if (w_assignto != NULL) \
53 PHYSFS_utf8ToUcs2(str, (PHYSFS_uint16 *) w_assignto, len); \
57 static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
59 PHYSFS_uint64 len = 0;
65 static char *unicodeToUtf8Heap(const WCHAR *w_str)
71 const PHYSFS_uint64 len = (wStrLen(w_str) * 4) + 1;
72 retval = allocator.Malloc(len);
73 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
74 PHYSFS_utf8FromUcs2((const PHYSFS_uint16 *) w_str, retval, len);
75 ptr = allocator.Realloc(retval, strlen(retval) + 1); /* shrink. */
77 retval = (char *) ptr;
80 } /* unicodeToUtf8Heap */
83 static char *codepageToUtf8Heap(const char *cpstr)
88 const int len = (int) (strlen(cpstr) + 1);
89 WCHAR *wbuf = (WCHAR *) __PHYSFS_smallAlloc(len * sizeof (WCHAR));
90 BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
91 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cpstr, len, wbuf, len);
92 retval = (char *) allocator.Malloc(len * 4);
94 __PHYSFS_setError(ERR_OUT_OF_MEMORY);
96 PHYSFS_utf8FromUcs2(wbuf, retval, len * 4);
97 __PHYSFS_smallFree(wbuf);
100 } /* codepageToUtf8Heap */
110 static char *userDir = NULL;
111 static int osHasUnicode = 0;
114 /* pointers for APIs that may not exist on some Windows versions... */
115 static HANDLE libKernel32 = NULL;
116 static HANDLE libUserEnv = NULL;
117 static HANDLE libAdvApi32 = NULL;
118 static DWORD (WINAPI *pGetModuleFileNameW)(HMODULE, LPWCH, DWORD);
119 static BOOL (WINAPI *pGetUserProfileDirectoryW)(HANDLE, LPWSTR, LPDWORD);
120 static BOOL (WINAPI *pGetUserNameW)(LPWSTR, LPDWORD);
121 static DWORD (WINAPI *pGetFileAttributesW)(LPCWSTR);
122 static HANDLE (WINAPI *pFindFirstFileW)(LPCWSTR, LPWIN32_FIND_DATAW);
123 static BOOL (WINAPI *pFindNextFileW)(HANDLE, LPWIN32_FIND_DATAW);
124 static DWORD (WINAPI *pGetCurrentDirectoryW)(DWORD, LPWSTR);
125 static BOOL (WINAPI *pDeleteFileW)(LPCWSTR);
126 static BOOL (WINAPI *pRemoveDirectoryW)(LPCWSTR);
127 static BOOL (WINAPI *pCreateDirectoryW)(LPCWSTR, LPSECURITY_ATTRIBUTES);
128 static BOOL (WINAPI *pGetFileAttributesExA)
129 (LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
130 static BOOL (WINAPI *pGetFileAttributesExW)
131 (LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
132 static DWORD (WINAPI *pFormatMessageW)
133 (DWORD, LPCVOID, DWORD, DWORD, LPWSTR, DWORD, va_list *);
134 static HANDLE (WINAPI *pCreateFileW)
135 (LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
139 * Fallbacks for missing Unicode functions on Win95/98/ME. These are filled
140 * into the function pointers if looking up the real Unicode entry points
141 * in the system DLLs fails, so they're never used on WinNT/XP/Vista/etc.
142 * They make an earnest effort to convert to/from UTF-8 and UCS-2 to
143 * the user's current codepage.
146 static BOOL WINAPI fallbackGetUserNameW(LPWSTR buf, LPDWORD len)
148 const DWORD cplen = *len;
149 char *cpstr = __PHYSFS_smallAlloc(cplen);
150 BOOL retval = GetUserNameA(cpstr, len);
152 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cpstr, cplen, buf, *len);
153 __PHYSFS_smallFree(cpstr);
155 } /* fallbackGetUserNameW */
157 static DWORD WINAPI fallbackFormatMessageW(DWORD dwFlags, LPCVOID lpSource,
158 DWORD dwMessageId, DWORD dwLangId,
159 LPWSTR lpBuf, DWORD nSize,
162 char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
163 DWORD retval = FormatMessageA(dwFlags, lpSource, dwMessageId, dwLangId,
164 cpbuf, nSize, Arguments);
166 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
167 __PHYSFS_smallFree(cpbuf);
169 } /* fallbackFormatMessageW */
171 static DWORD WINAPI fallbackGetModuleFileNameW(HMODULE hMod, LPWCH lpBuf,
174 char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
175 DWORD retval = GetModuleFileNameA(hMod, cpbuf, nSize);
177 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
178 __PHYSFS_smallFree(cpbuf);
180 } /* fallbackGetModuleFileNameW */
182 static DWORD WINAPI fallbackGetFileAttributesW(LPCWSTR fname)
185 const int buflen = (int) (wStrLen(fname) + 1);
186 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
187 WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
188 retval = GetFileAttributesA(cpstr);
189 __PHYSFS_smallFree(cpstr);
191 } /* fallbackGetFileAttributesW */
193 static DWORD WINAPI fallbackGetCurrentDirectoryW(DWORD buflen, LPWSTR buf)
198 cpbuf = (char *) __PHYSFS_smallAlloc(buflen);
199 retval = GetCurrentDirectoryA(buflen, cpbuf);
202 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,buf,buflen);
203 __PHYSFS_smallFree(cpbuf);
206 } /* fallbackGetCurrentDirectoryW */
208 static BOOL WINAPI fallbackRemoveDirectoryW(LPCWSTR dname)
211 const int buflen = (int) (wStrLen(dname) + 1);
212 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
213 WideCharToMultiByte(CP_ACP, 0, dname, buflen, cpstr, buflen, NULL, NULL);
214 retval = RemoveDirectoryA(cpstr);
215 __PHYSFS_smallFree(cpstr);
217 } /* fallbackRemoveDirectoryW */
219 static BOOL WINAPI fallbackCreateDirectoryW(LPCWSTR dname,
220 LPSECURITY_ATTRIBUTES attr)
223 const int buflen = (int) (wStrLen(dname) + 1);
224 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
225 WideCharToMultiByte(CP_ACP, 0, dname, buflen, cpstr, buflen, NULL, NULL);
226 retval = CreateDirectoryA(cpstr, attr);
227 __PHYSFS_smallFree(cpstr);
229 } /* fallbackCreateDirectoryW */
231 static BOOL WINAPI fallbackDeleteFileW(LPCWSTR fname)
234 const int buflen = (int) (wStrLen(fname) + 1);
235 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
236 WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
237 retval = DeleteFileA(cpstr);
238 __PHYSFS_smallFree(cpstr);
240 } /* fallbackDeleteFileW */
242 static HANDLE WINAPI fallbackCreateFileW(LPCWSTR fname,
243 DWORD dwDesiredAccess, DWORD dwShareMode,
244 LPSECURITY_ATTRIBUTES lpSecurityAttrs,
245 DWORD dwCreationDisposition,
246 DWORD dwFlagsAndAttrs, HANDLE hTemplFile)
249 const int buflen = (int) (wStrLen(fname) + 1);
250 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
251 WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
252 retval = CreateFileA(cpstr, dwDesiredAccess, dwShareMode, lpSecurityAttrs,
253 dwCreationDisposition, dwFlagsAndAttrs, hTemplFile);
254 __PHYSFS_smallFree(cpstr);
256 } /* fallbackCreateFileW */
259 #if (PHYSFS_MINIMUM_GCC_VERSION(3,3))
260 typedef FARPROC __attribute__((__may_alias__)) PHYSFS_FARPROC;
262 typedef FARPROC PHYSFS_FARPROC;
266 static void symLookup(HMODULE dll, PHYSFS_FARPROC *addr, const char *sym,
267 int reallyLook, PHYSFS_FARPROC fallback)
270 proc = (PHYSFS_FARPROC) ((reallyLook) ? GetProcAddress(dll, sym) : NULL);
272 proc = fallback; /* may also be NULL. */
277 static int findApiSymbols(void)
281 #define LOOKUP_NOFALLBACK(x, reallyLook) \
282 symLookup(dll, (PHYSFS_FARPROC *) &p##x, #x, reallyLook, NULL)
284 #define LOOKUP(x, reallyLook) \
285 symLookup(dll, (PHYSFS_FARPROC *) &p##x, #x, \
286 reallyLook, (PHYSFS_FARPROC) fallback##x)
288 /* Apparently Win9x HAS the Unicode entry points, they just don't WORK. */
289 /* ...so don't look them up unless we're on NT+. (see osHasUnicode.) */
291 dll = libUserEnv = LoadLibraryA("userenv.dll");
293 LOOKUP_NOFALLBACK(GetUserProfileDirectoryW, osHasUnicode);
295 /* !!! FIXME: what do they call advapi32.dll on Win64? */
296 dll = libAdvApi32 = LoadLibraryA("advapi32.dll");
298 LOOKUP(GetUserNameW, osHasUnicode);
300 /* !!! FIXME: what do they call kernel32.dll on Win64? */
301 dll = libKernel32 = LoadLibraryA("kernel32.dll");
304 LOOKUP_NOFALLBACK(GetFileAttributesExA, 1);
305 LOOKUP_NOFALLBACK(GetFileAttributesExW, osHasUnicode);
306 LOOKUP_NOFALLBACK(FindFirstFileW, osHasUnicode);
307 LOOKUP_NOFALLBACK(FindNextFileW, osHasUnicode);
308 LOOKUP(GetModuleFileNameW, osHasUnicode);
309 LOOKUP(FormatMessageW, osHasUnicode);
310 LOOKUP(GetFileAttributesW, osHasUnicode);
311 LOOKUP(GetCurrentDirectoryW, osHasUnicode);
312 LOOKUP(CreateDirectoryW, osHasUnicode);
313 LOOKUP(RemoveDirectoryW, osHasUnicode);
314 LOOKUP(CreateFileW, osHasUnicode);
315 LOOKUP(DeleteFileW, osHasUnicode);
318 #undef LOOKUP_NOFALLBACK
322 } /* findApiSymbols */
325 const char *__PHYSFS_platformDirSeparator = "\\";
329 * Figure out what the last failing Windows API call was, and
330 * generate a human-readable string for the error message.
332 * The return value is a static buffer that is overwritten with
333 * each call to this function.
335 static const char *winApiStrError(void)
337 static char utf8buf[255];
340 DWORD rc = pFormatMessageW(
341 FORMAT_MESSAGE_FROM_SYSTEM |
342 FORMAT_MESSAGE_IGNORE_INSERTS,
343 NULL, GetLastError(),
344 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
345 msgbuf, __PHYSFS_ARRAYLEN(msgbuf),
349 msgbuf[0] = '\0'; /* oh well. */
351 /* chop off newlines. */
352 for (ptr = msgbuf; *ptr; ptr++)
354 if ((*ptr == '\n') || (*ptr == '\r'))
361 /* may truncate, but oh well. */
362 PHYSFS_utf8FromUcs2((PHYSFS_uint16 *) msgbuf, utf8buf, sizeof (utf8buf));
363 return((const char *) utf8buf);
364 } /* winApiStrError */
367 static char *getExePath(void)
370 LPWSTR modpath = NULL;
378 if ( !(ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) )
380 allocator.Free(modpath);
381 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
383 modpath = (LPWSTR) ptr;
385 rc = pGetModuleFileNameW(NULL, modpath, buflen);
388 allocator.Free(modpath);
389 BAIL_MACRO(winApiStrError(), NULL);
401 if (buflen > 0) /* just in case... */
403 WCHAR *ptr = (modpath + buflen) - 1;
404 while (ptr != modpath)
411 if ((ptr == modpath) && (*ptr != '\\'))
412 __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
415 *(ptr + 1) = '\0'; /* chop off filename. */
416 retval = unicodeToUtf8Heap(modpath);
419 allocator.Free(modpath);
421 return(retval); /* w00t. */
426 * Try to make use of GetUserProfileDirectoryW(), which isn't available on
427 * some common variants of Win32. If we can't use this, we just punt and
428 * use the physfs base dir for the user dir, too.
430 * On success, module-scope variable (userDir) will have a pointer to
431 * a malloc()'d string of the user's profile dir, and a non-zero value is
432 * returned. If we can't determine the profile dir, (userDir) will
433 * be NULL, and zero is returned.
435 static int determineUserDir(void)
438 return(1); /* already good to go. */
441 * GetUserProfileDirectoryW() is only available on NT 4.0 and later.
442 * This means Win95/98/ME (and CE?) users have to do without, so for
443 * them, we'll default to the base directory when we can't get the
444 * function pointer. Since this is originally an NT API, we don't
445 * offer a non-Unicode fallback.
447 if (pGetUserProfileDirectoryW != NULL)
449 HANDLE accessToken = NULL; /* Security handle to process */
450 HANDLE processHandle = GetCurrentProcess();
451 if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
459 * Should fail. Will write the size of the profile path in
460 * psize. Also note that the second parameter can't be
461 * NULL or the function fails.
463 rc = pGetUserProfileDirectoryW(accessToken, &dummy, &psize);
464 assert(!rc); /* !!! FIXME: handle this gracefully. */
466 /* Allocate memory for the profile directory */
467 wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
470 if (pGetUserProfileDirectoryW(accessToken, wstr, &psize))
471 userDir = unicodeToUtf8Heap(wstr);
472 __PHYSFS_smallFree(wstr);
476 CloseHandle(accessToken);
479 if (userDir == NULL) /* couldn't get profile for some reason. */
481 /* Might just be a non-NT system; resort to the basedir. */
482 userDir = getExePath();
483 BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
486 return(1); /* We made it: hit the showers. */
487 } /* determineUserDir */
490 static BOOL mediaInDrive(const char *drive)
496 /* Prevent windows warning message appearing when checking media size */
497 oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
499 /* If this function succeeds, there's media in the drive */
500 retval = GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0);
502 /* Revert back to old windows error handler */
503 SetErrorMode(oldErrorMode);
509 void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
511 /* !!! FIXME: Can CD drives be non-drive letter paths? */
512 /* !!! FIXME: (so can they be Unicode paths?) */
513 char drive_str[4] = "x:\\";
515 for (ch = 'A'; ch <= 'Z'; ch++)
518 if (GetDriveType(drive_str) == DRIVE_CDROM && mediaInDrive(drive_str))
521 } /* __PHYSFS_platformDetectAvailableCDs */
524 char *__PHYSFS_platformCalcBaseDir(const char *argv0)
526 if ((argv0 != NULL) && (strchr(argv0, '\\') != NULL))
527 return(NULL); /* default behaviour can handle this. */
529 return(getExePath());
530 } /* __PHYSFS_platformCalcBaseDir */
533 char *__PHYSFS_platformGetUserName(void)
538 if (pGetUserNameW(NULL, &bufsize) == 0) /* This SHOULD fail. */
540 LPWSTR wbuf = (LPWSTR) __PHYSFS_smallAlloc(bufsize * sizeof (WCHAR));
541 BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
542 if (pGetUserNameW(wbuf, &bufsize) == 0) /* ?! */
543 __PHYSFS_setError(winApiStrError());
545 retval = unicodeToUtf8Heap(wbuf);
546 __PHYSFS_smallFree(wbuf);
550 } /* __PHYSFS_platformGetUserName */
553 char *__PHYSFS_platformGetUserDir(void)
555 char *retval = (char *) allocator.Malloc(strlen(userDir) + 1);
556 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
557 strcpy(retval, userDir); /* calculated at init time. */
559 } /* __PHYSFS_platformGetUserDir */
562 PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
564 return((PHYSFS_uint64) GetCurrentThreadId());
565 } /* __PHYSFS_platformGetThreadID */
568 static int doPlatformExists(LPWSTR wpath)
572 pGetFileAttributesW(wpath) == PHYSFS_INVALID_FILE_ATTRIBUTES,
576 } /* doPlatformExists */
579 int __PHYSFS_platformExists(const char *fname)
583 UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
584 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
585 retval = doPlatformExists(wpath);
586 __PHYSFS_smallFree(wpath);
588 } /* __PHYSFS_platformExists */
591 static int isSymlinkAttrs(const DWORD attr, const DWORD tag)
593 return ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) &&
594 (tag == PHYSFS_IO_REPARSE_TAG_SYMLINK) );
595 } /* isSymlinkAttrs */
598 int __PHYSFS_platformIsSymLink(const char *fname)
601 * Windows Vista can have NTFS symlinks. Can older Windows releases have
602 * them when talking to a network file server? What happens when you
603 * mount a NTFS partition on XP that was plugged into a Vista install
604 * that made a symlink?
610 WIN32_FIND_DATAW entw;
612 /* no unicode entry points? Probably no symlinks. */
613 BAIL_IF_MACRO(pFindFirstFileW == NULL, NULL, 0);
615 UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
616 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
618 /* !!! FIXME: filter wildcard chars? */
619 dir = pFindFirstFileW(wpath, &entw);
620 if (dir != INVALID_HANDLE_VALUE)
622 retval = isSymlinkAttrs(entw.dwFileAttributes, entw.dwReserved0);
626 __PHYSFS_smallFree(wpath);
628 } /* __PHYSFS_platformIsSymlink */
631 int __PHYSFS_platformIsDirectory(const char *fname)
635 UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
636 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
637 retval = ((pGetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY) != 0);
638 __PHYSFS_smallFree(wpath);
640 } /* __PHYSFS_platformIsDirectory */
643 char *__PHYSFS_platformCvtToDependent(const char *prepend,
647 int len = ((prepend) ? strlen(prepend) : 0) +
648 ((append) ? strlen(append) : 0) +
650 char *retval = (char *) allocator.Malloc(len);
653 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
656 strcpy(retval, prepend);
660 strcat(retval, dirName);
663 strcat(retval, append);
665 for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
669 } /* __PHYSFS_platformCvtToDependent */
672 void __PHYSFS_platformEnumerateFiles(const char *dirname,
674 PHYSFS_EnumFilesCallback callback,
678 const int unicode = (pFindFirstFileW != NULL) && (pFindNextFileW != NULL);
679 HANDLE dir = INVALID_HANDLE_VALUE;
681 WIN32_FIND_DATAW entw;
682 size_t len = strlen(dirname);
683 char *searchPath = NULL;
684 WCHAR *wSearchPath = NULL;
687 /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
688 searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
689 if (searchPath == NULL)
692 /* Copy current dirname */
693 strcpy(searchPath, dirname);
695 /* if there's no '\\' at the end of the path, stick one in there. */
696 if (searchPath[len - 1] != '\\')
698 searchPath[len++] = '\\';
699 searchPath[len] = '\0';
702 /* Append the "*" to the end of the string */
703 strcat(searchPath, "*");
705 UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
706 if (wSearchPath == NULL)
707 return; /* oh well. */
710 dir = pFindFirstFileW(wSearchPath, &entw);
713 const int len = (int) (wStrLen(wSearchPath) + 1);
714 char *cp = (char *) __PHYSFS_smallAlloc(len);
717 WideCharToMultiByte(CP_ACP, 0, wSearchPath, len, cp, len, 0, 0);
718 dir = FindFirstFileA(cp, &ent);
719 __PHYSFS_smallFree(cp);
723 __PHYSFS_smallFree(wSearchPath);
724 __PHYSFS_smallFree(searchPath);
725 if (dir == INVALID_HANDLE_VALUE)
732 const DWORD attr = entw.dwFileAttributes;
733 const DWORD tag = entw.dwReserved0;
734 const WCHAR *fn = entw.cFileName;
735 if ((fn[0] == '.') && (fn[1] == '\0'))
737 if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
739 if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
742 utf8 = unicodeToUtf8Heap(fn);
745 callback(callbackdata, origdir, utf8);
746 allocator.Free(utf8);
748 } while (pFindNextFileW(dir, &entw) != 0);
751 else /* ANSI fallback. */
755 const DWORD attr = ent.dwFileAttributes;
756 const DWORD tag = ent.dwReserved0;
757 const char *fn = ent.cFileName;
758 if ((fn[0] == '.') && (fn[1] == '\0'))
760 if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
762 if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
765 utf8 = codepageToUtf8Heap(fn);
768 callback(callbackdata, origdir, utf8);
769 allocator.Free(utf8);
771 } while (FindNextFileA(dir, &ent) != 0);
775 } /* __PHYSFS_platformEnumerateFiles */
778 char *__PHYSFS_platformCurrentDir(void)
784 buflen = pGetCurrentDirectoryW(buflen, NULL);
785 wbuf = (WCHAR *) __PHYSFS_smallAlloc((buflen + 2) * sizeof (WCHAR));
786 BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
787 pGetCurrentDirectoryW(buflen, wbuf);
789 if (wbuf[buflen - 2] == '\\')
790 wbuf[buflen-1] = '\0'; /* just in case... */
793 wbuf[buflen - 1] = '\\';
797 retval = unicodeToUtf8Heap(wbuf);
798 __PHYSFS_smallFree(wbuf);
800 } /* __PHYSFS_platformCurrentDir */
803 /* this could probably use a cleanup. */
804 char *__PHYSFS_platformRealPath(const char *path)
806 /* !!! FIXME: this should return NULL if (path) doesn't exist? */
807 /* !!! FIXME: Need to handle symlinks in Vista... */
808 /* !!! FIXME: try GetFullPathName() instead? */
809 /* this function should be UTF-8 clean. */
813 BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
814 BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
816 retval = (char *) allocator.Malloc(MAX_PATH);
817 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
820 * If in \\server\path format, it's already an absolute path.
821 * We'll need to check for "." and ".." dirs, though, just in case.
823 if ((path[0] == '\\') && (path[1] == '\\'))
824 strcpy(retval, path);
828 char *currentDir = __PHYSFS_platformCurrentDir();
829 if (currentDir == NULL)
831 allocator.Free(retval);
832 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
835 if (path[1] == ':') /* drive letter specified? */
838 * Apparently, "D:mypath" is the same as "D:\\mypath" if
839 * D: is not the current drive. However, if D: is the
840 * current drive, then "D:mypath" is a relative path. Ugh.
842 if (path[2] == '\\') /* maybe an absolute path? */
843 strcpy(retval, path);
844 else /* definitely an absolute path. */
846 if (path[0] == currentDir[0]) /* current drive; relative. */
848 strcpy(retval, currentDir);
849 strcat(retval, path + 2);
852 else /* not current drive; absolute. */
857 strcpy(retval + 3, path + 2);
862 else /* no drive letter specified. */
864 if (path[0] == '\\') /* absolute path. */
866 retval[0] = currentDir[0];
868 strcpy(retval + 2, path);
872 strcpy(retval, currentDir);
873 strcat(retval, path);
877 allocator.Free(currentDir);
880 /* (whew.) Ok, now take out "." and ".." path entries... */
883 while ( (p = strstr(p, "\\.")) != NULL)
885 /* it's a "." entry that doesn't end the string. */
887 memmove(p + 1, p + 3, strlen(p + 3) + 1);
889 /* it's a "." entry that ends the string. */
890 else if (p[2] == '\0')
893 /* it's a ".." entry. */
894 else if (p[2] == '.')
896 char *prevEntry = p - 1;
897 while ((prevEntry != retval) && (*prevEntry != '\\'))
900 if (prevEntry == retval) /* make it look like a "." entry. */
901 memmove(p + 1, p + 2, strlen(p + 2) + 1);
904 if (p[3] != '\0') /* doesn't end string. */
906 else /* ends string. */
907 memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
915 p++; /* look past current char. */
919 /* shrink the retval's memory block if possible... */
920 p = (char *) allocator.Realloc(retval, strlen(retval) + 1);
925 } /* __PHYSFS_platformRealPath */
928 int __PHYSFS_platformMkDir(const char *path)
932 UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
933 rc = pCreateDirectoryW(wpath, NULL);
934 __PHYSFS_smallFree(wpath);
935 BAIL_IF_MACRO(rc == 0, winApiStrError(), 0);
937 } /* __PHYSFS_platformMkDir */
941 * Get OS info and save the important parts.
943 * Returns non-zero if successful, otherwise it returns zero on failure.
945 static int getOSInfo(void)
947 OSVERSIONINFO osVerInfo; /* Information about the OS */
948 osVerInfo.dwOSVersionInfoSize = sizeof(osVerInfo);
949 BAIL_IF_MACRO(!GetVersionEx(&osVerInfo), winApiStrError(), 0);
950 osHasUnicode = (osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS);
955 int __PHYSFS_platformInit(void)
957 BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
958 BAIL_IF_MACRO(!findApiSymbols(), NULL, 0);
959 BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
960 return(1); /* It's all good */
961 } /* __PHYSFS_platformInit */
964 int __PHYSFS_platformDeinit(void)
966 HANDLE *libs[] = { &libKernel32, &libUserEnv, &libAdvApi32, NULL };
969 allocator.Free(userDir);
972 for (i = 0; libs[i] != NULL; i++)
974 const HANDLE lib = *(libs[i]);
980 return(1); /* It's all good */
981 } /* __PHYSFS_platformDeinit */
984 static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
990 UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
991 BAIL_IF_MACRO(wfname == NULL, ERR_OUT_OF_MEMORY, NULL);
992 fileHandle = pCreateFileW(wfname, mode, FILE_SHARE_READ | FILE_SHARE_WRITE,
993 NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
994 __PHYSFS_smallFree(wfname);
998 fileHandle == INVALID_HANDLE_VALUE,
999 winApiStrError(), NULL
1002 retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
1005 CloseHandle(fileHandle);
1006 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1009 retval->readonly = rdonly;
1010 retval->handle = fileHandle;
1015 void *__PHYSFS_platformOpenRead(const char *filename)
1017 return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
1018 } /* __PHYSFS_platformOpenRead */
1021 void *__PHYSFS_platformOpenWrite(const char *filename)
1023 return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
1024 } /* __PHYSFS_platformOpenWrite */
1027 void *__PHYSFS_platformOpenAppend(const char *filename)
1029 void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
1032 HANDLE h = ((WinApiFile *) retval)->handle;
1033 DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
1034 if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
1036 const char *err = winApiStrError();
1038 allocator.Free(retval);
1039 BAIL_MACRO(err, NULL);
1044 } /* __PHYSFS_platformOpenAppend */
1047 PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
1048 PHYSFS_uint32 size, PHYSFS_uint32 count)
1050 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1051 DWORD CountOfBytesRead;
1052 PHYSFS_sint64 retval;
1054 /* Read data from the file */
1055 /* !!! FIXME: uint32 might be a greater # than DWORD */
1056 if(!ReadFile(Handle, buffer, count * size, &CountOfBytesRead, NULL))
1058 BAIL_MACRO(winApiStrError(), -1);
1062 /* Return the number of "objects" read. */
1063 /* !!! FIXME: What if not the right amount of bytes was read to make an object? */
1064 retval = CountOfBytesRead / size;
1068 } /* __PHYSFS_platformRead */
1071 PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
1072 PHYSFS_uint32 size, PHYSFS_uint32 count)
1074 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1075 DWORD CountOfBytesWritten;
1076 PHYSFS_sint64 retval;
1078 /* Read data from the file */
1079 /* !!! FIXME: uint32 might be a greater # than DWORD */
1080 if(!WriteFile(Handle, buffer, count * size, &CountOfBytesWritten, NULL))
1082 BAIL_MACRO(winApiStrError(), -1);
1086 /* Return the number of "objects" read. */
1087 /* !!! FIXME: What if not the right number of bytes was written? */
1088 retval = CountOfBytesWritten / size;
1092 } /* __PHYSFS_platformWrite */
1095 int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
1097 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1099 PLONG pHighOrderPos;
1102 /* Get the high order 32-bits of the position */
1103 HighOrderPos = HIGHORDER_UINT64(pos);
1106 * MSDN: "If you do not need the high-order 32 bits, this
1107 * pointer must be set to NULL."
1109 pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
1112 * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
1113 * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
1114 * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
1115 * !!! FIXME: the sign extension of the value of lDistanceToMove.
1116 * !!! FIXME: Any other value will be rejected."
1119 /* Move pointer "pos" count from start of file */
1120 rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
1121 pHighOrderPos, FILE_BEGIN);
1123 if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
1124 (GetLastError() != NO_ERROR) )
1126 BAIL_MACRO(winApiStrError(), 0);
1129 return(1); /* No error occured */
1130 } /* __PHYSFS_platformSeek */
1133 PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
1135 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1138 PHYSFS_sint64 retval;
1140 /* Get current position */
1141 LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
1142 if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
1143 (GetLastError() != NO_ERROR) )
1145 BAIL_MACRO(winApiStrError(), 0);
1149 /* Combine the high/low order to create the 64-bit position value */
1150 retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
1151 assert(retval >= 0);
1155 } /* __PHYSFS_platformTell */
1158 PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
1160 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1163 PHYSFS_sint64 retval;
1165 SizeLow = GetFileSize(Handle, &SizeHigh);
1166 if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
1167 (GetLastError() != NO_ERROR) )
1169 BAIL_MACRO(winApiStrError(), -1);
1173 /* Combine the high/low order to create the 64-bit position value */
1174 retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
1175 assert(retval >= 0);
1179 } /* __PHYSFS_platformFileLength */
1182 int __PHYSFS_platformEOF(void *opaque)
1184 PHYSFS_sint64 FilePosition;
1187 /* Get the current position in the file */
1188 if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
1190 /* Non-zero if EOF is equal to the file length */
1191 retval = FilePosition == __PHYSFS_platformFileLength(opaque);
1195 } /* __PHYSFS_platformEOF */
1198 int __PHYSFS_platformFlush(void *opaque)
1200 WinApiFile *fh = ((WinApiFile *) opaque);
1202 BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), winApiStrError(), 0);
1205 } /* __PHYSFS_platformFlush */
1208 int __PHYSFS_platformClose(void *opaque)
1210 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1211 BAIL_IF_MACRO(!CloseHandle(Handle), winApiStrError(), 0);
1212 allocator.Free(opaque);
1214 } /* __PHYSFS_platformClose */
1217 static int doPlatformDelete(LPWSTR wpath)
1219 /* If filename is a folder */
1220 if (pGetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)
1222 BAIL_IF_MACRO(!pRemoveDirectoryW(wpath), winApiStrError(), 0);
1226 BAIL_IF_MACRO(!pDeleteFileW(wpath), winApiStrError(), 0);
1229 return(1); /* if you made it here, it worked. */
1230 } /* doPlatformDelete */
1233 int __PHYSFS_platformDelete(const char *path)
1237 UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
1238 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
1239 retval = doPlatformDelete(wpath);
1240 __PHYSFS_smallFree(wpath);
1242 } /* __PHYSFS_platformDelete */
1246 * !!! FIXME: why aren't we using Critical Sections instead of Mutexes?
1247 * !!! FIXME: mutexes on Windows are for cross-process sync. CritSects are
1248 * !!! FIXME: mutexes for threads in a single process and are faster.
1250 void *__PHYSFS_platformCreateMutex(void)
1252 return((void *) CreateMutex(NULL, FALSE, NULL));
1253 } /* __PHYSFS_platformCreateMutex */
1256 void __PHYSFS_platformDestroyMutex(void *mutex)
1258 CloseHandle((HANDLE) mutex);
1259 } /* __PHYSFS_platformDestroyMutex */
1262 int __PHYSFS_platformGrabMutex(void *mutex)
1264 return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
1265 } /* __PHYSFS_platformGrabMutex */
1268 void __PHYSFS_platformReleaseMutex(void *mutex)
1270 ReleaseMutex((HANDLE) mutex);
1271 } /* __PHYSFS_platformReleaseMutex */
1274 static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
1277 SYSTEMTIME st_localtz;
1278 TIME_ZONE_INFORMATION tzi;
1280 PHYSFS_sint64 retval;
1283 BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), winApiStrError(), -1);
1284 tzid = GetTimeZoneInformation(&tzi);
1285 BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, winApiStrError(), -1);
1287 /* (This API is unsupported and fails on non-NT systems. */
1288 if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
1290 /* do it by hand. Grumble... */
1291 ULARGE_INTEGER ui64;
1293 ui64.LowPart = ft->dwLowDateTime;
1294 ui64.HighPart = ft->dwHighDateTime;
1296 if (tzid == TIME_ZONE_ID_STANDARD)
1297 tzi.Bias += tzi.StandardBias;
1298 else if (tzid == TIME_ZONE_ID_DAYLIGHT)
1299 tzi.Bias += tzi.DaylightBias;
1301 /* convert from minutes to 100-nanosecond increments... */
1302 ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
1304 /* Move it back into a FILETIME structure... */
1305 new_ft.dwLowDateTime = ui64.LowPart;
1306 new_ft.dwHighDateTime = ui64.HighPart;
1308 /* Convert to something human-readable... */
1309 if (!FileTimeToSystemTime(&new_ft, &st_localtz))
1310 BAIL_MACRO(winApiStrError(), -1);
1313 /* Convert to a format that mktime() can grok... */
1314 tm.tm_sec = st_localtz.wSecond;
1315 tm.tm_min = st_localtz.wMinute;
1316 tm.tm_hour = st_localtz.wHour;
1317 tm.tm_mday = st_localtz.wDay;
1318 tm.tm_mon = st_localtz.wMonth - 1;
1319 tm.tm_year = st_localtz.wYear - 1900;
1320 tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
1324 /* Convert to a format PhysicsFS can grok... */
1325 retval = (PHYSFS_sint64) mktime(&tm);
1326 BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
1328 } /* FileTimeToPhysfsTime */
1331 PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
1333 PHYSFS_sint64 retval = -1;
1334 WIN32_FILE_ATTRIBUTE_DATA attr;
1337 memset(&attr, '\0', sizeof (attr));
1339 /* GetFileAttributesEx didn't show up until Win98 and NT4. */
1340 if ((pGetFileAttributesExW != NULL) || (pGetFileAttributesExA != NULL))
1343 UTF8_TO_UNICODE_STACK_MACRO(wstr, fname);
1344 if (wstr != NULL) /* if NULL, maybe the fallback will work. */
1346 if (pGetFileAttributesExW != NULL) /* NT/XP/Vista/etc system. */
1347 rc = pGetFileAttributesExW(wstr, GetFileExInfoStandard, &attr);
1348 else /* Win98/ME system */
1350 const int len = (int) (wStrLen(wstr) + 1);
1351 char *cp = (char *) __PHYSFS_smallAlloc(len);
1354 WideCharToMultiByte(CP_ACP, 0, wstr, len, cp, len, 0, 0);
1355 rc = pGetFileAttributesExA(cp, GetFileExInfoStandard, &attr);
1356 __PHYSFS_smallFree(cp);
1359 __PHYSFS_smallFree(wstr);
1363 if (rc) /* had API entry point and it worked. */
1365 /* 0 return value indicates an error or not supported */
1366 if ( (attr.ftLastWriteTime.dwHighDateTime != 0) ||
1367 (attr.ftLastWriteTime.dwLowDateTime != 0) )
1369 retval = FileTimeToPhysfsTime(&attr.ftLastWriteTime);
1373 /* GetFileTime() has been in the Win32 API since the start. */
1374 if (retval == -1) /* try a fallback... */
1379 WinApiFile *f = (WinApiFile *) __PHYSFS_platformOpenRead(fname);
1380 BAIL_IF_MACRO(f == NULL, NULL, -1)
1381 rc = GetFileTime(f->handle, NULL, NULL, &ft);
1382 err = winApiStrError();
1383 CloseHandle(f->handle);
1385 BAIL_IF_MACRO(!rc, err, -1);
1386 retval = FileTimeToPhysfsTime(&ft);
1390 } /* __PHYSFS_platformGetLastModTime */
1393 /* !!! FIXME: Don't use C runtime for allocators? */
1394 int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
1396 return(0); /* just use malloc() and friends. */
1397 } /* __PHYSFS_platformSetDefaultAllocator */
1399 #endif /* PHYSFS_PLATFORM_WINDOWS */
1401 /* end of windows.c ... */