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) \
30 (pos & 0x00000000FFFFFFFF)
31 #define HIGHORDER_UINT64(pos) (PHYSFS_uint32) \
32 (((pos & 0xFFFFFFFF00000000) >> 32) & 0x00000000FFFFFFFF)
35 * Users without the platform SDK don't have this defined. The original docs
36 * for SetFilePointer() just said to compare with 0xFFFFFFFF, so this should
39 #define PHYSFS_INVALID_SET_FILE_POINTER 0xFFFFFFFF
42 #define PHYSFS_INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
44 /* Not defined before the Vista SDK. */
45 #define PHYSFS_IO_REPARSE_TAG_SYMLINK 0xA000000C
48 #define UTF8_TO_UNICODE_STACK_MACRO(w_assignto, str) { \
52 const PHYSFS_uint64 len = (PHYSFS_uint64) ((strlen(str) * 4) + 1); \
53 w_assignto = (WCHAR *) __PHYSFS_smallAlloc(len); \
54 if (w_assignto != NULL) \
55 PHYSFS_utf8ToUcs2(str, (PHYSFS_uint16 *) w_assignto, len); \
59 static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
61 PHYSFS_uint64 len = 0;
67 static char *unicodeToUtf8Heap(const WCHAR *w_str)
73 const PHYSFS_uint64 len = (wStrLen(w_str) * 4) + 1;
74 retval = allocator.Malloc(len);
75 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
76 PHYSFS_utf8FromUcs2((const PHYSFS_uint16 *) w_str, retval, len);
77 ptr = allocator.Realloc(retval, strlen(retval) + 1); /* shrink. */
79 retval = (char *) ptr;
82 } /* unicodeToUtf8Heap */
85 static char *codepageToUtf8Heap(const char *cpstr)
90 const int len = (int) (strlen(cpstr) + 1);
91 WCHAR *wbuf = (WCHAR *) __PHYSFS_smallAlloc(len * sizeof (WCHAR));
92 BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
93 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cpstr, len, wbuf, len);
94 retval = (char *) allocator.Malloc(len * 4);
96 __PHYSFS_setError(ERR_OUT_OF_MEMORY);
98 PHYSFS_utf8FromUcs2(wbuf, retval, len * 4);
99 __PHYSFS_smallFree(wbuf);
102 } /* codepageToUtf8Heap */
112 static char *userDir = NULL;
113 static int osHasUnicode = 0;
116 /* pointers for APIs that may not exist on some Windows versions... */
117 static HANDLE libKernel32 = NULL;
118 static HANDLE libUserEnv = NULL;
119 static HANDLE libAdvApi32 = NULL;
120 static DWORD (WINAPI *pGetModuleFileNameW)(HMODULE, LPWCH, DWORD);
121 static BOOL (WINAPI *pGetUserProfileDirectoryW)(HANDLE, LPWSTR, LPDWORD);
122 static BOOL (WINAPI *pGetUserNameW)(LPWSTR, LPDWORD);
123 static DWORD (WINAPI *pGetFileAttributesW)(LPCWSTR);
124 static HANDLE (WINAPI *pFindFirstFileW)(LPCWSTR, LPWIN32_FIND_DATAW);
125 static BOOL (WINAPI *pFindNextFileW)(HANDLE, LPWIN32_FIND_DATAW);
126 static DWORD (WINAPI *pGetCurrentDirectoryW)(DWORD, LPWSTR);
127 static BOOL (WINAPI *pDeleteFileW)(LPCWSTR);
128 static BOOL (WINAPI *pRemoveDirectoryW)(LPCWSTR);
129 static BOOL (WINAPI *pCreateDirectoryW)(LPCWSTR, LPSECURITY_ATTRIBUTES);
130 static BOOL (WINAPI *pGetFileAttributesExA)
131 (LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
132 static BOOL (WINAPI *pGetFileAttributesExW)
133 (LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
134 static DWORD (WINAPI *pFormatMessageW)
135 (DWORD, LPCVOID, DWORD, DWORD, LPWSTR, DWORD, va_list *);
136 static HANDLE (WINAPI *pCreateFileW)
137 (LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
141 * Fallbacks for missing Unicode functions on Win95/98/ME. These are filled
142 * into the function pointers if looking up the real Unicode entry points
143 * in the system DLLs fails, so they're never used on WinNT/XP/Vista/etc.
144 * They make an earnest effort to convert to/from UTF-8 and UCS-2 to
145 * the user's current codepage.
148 static BOOL WINAPI fallbackGetUserNameW(LPWSTR buf, LPDWORD len)
150 const DWORD cplen = *len;
151 char *cpstr = __PHYSFS_smallAlloc(cplen);
152 BOOL retval = GetUserNameA(cpstr, len);
154 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cpstr, cplen, buf, *len);
155 __PHYSFS_smallFree(cpstr);
157 } /* fallbackGetUserNameW */
159 static DWORD WINAPI fallbackFormatMessageW(DWORD dwFlags, LPCVOID lpSource,
160 DWORD dwMessageId, DWORD dwLangId,
161 LPWSTR lpBuf, DWORD nSize,
164 char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
165 DWORD retval = FormatMessageA(dwFlags, lpSource, dwMessageId, dwLangId,
166 cpbuf, nSize, Arguments);
168 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
169 __PHYSFS_smallFree(cpbuf);
171 } /* fallbackFormatMessageW */
173 static DWORD WINAPI fallbackGetModuleFileNameW(HMODULE hMod, LPWCH lpBuf,
176 char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
177 DWORD retval = GetModuleFileNameA(hMod, cpbuf, nSize);
179 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
180 __PHYSFS_smallFree(cpbuf);
182 } /* fallbackGetModuleFileNameW */
184 static DWORD WINAPI fallbackGetFileAttributesW(LPCWSTR fname)
187 const int buflen = (int) (wStrLen(fname) + 1);
188 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
189 WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
190 retval = GetFileAttributesA(cpstr);
191 __PHYSFS_smallFree(cpstr);
193 } /* fallbackGetFileAttributesW */
195 static DWORD WINAPI fallbackGetCurrentDirectoryW(DWORD buflen, LPWSTR buf)
200 cpbuf = (char *) __PHYSFS_smallAlloc(buflen);
201 retval = GetCurrentDirectoryA(buflen, cpbuf);
204 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,buf,buflen);
205 __PHYSFS_smallFree(cpbuf);
208 } /* fallbackGetCurrentDirectoryW */
210 static BOOL WINAPI fallbackRemoveDirectoryW(LPCWSTR dname)
213 const int buflen = (int) (wStrLen(dname) + 1);
214 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
215 WideCharToMultiByte(CP_ACP, 0, dname, buflen, cpstr, buflen, NULL, NULL);
216 retval = RemoveDirectoryA(cpstr);
217 __PHYSFS_smallFree(cpstr);
219 } /* fallbackRemoveDirectoryW */
221 static BOOL WINAPI fallbackCreateDirectoryW(LPCWSTR dname,
222 LPSECURITY_ATTRIBUTES attr)
225 const int buflen = (int) (wStrLen(dname) + 1);
226 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
227 WideCharToMultiByte(CP_ACP, 0, dname, buflen, cpstr, buflen, NULL, NULL);
228 retval = CreateDirectoryA(cpstr, attr);
229 __PHYSFS_smallFree(cpstr);
231 } /* fallbackCreateDirectoryW */
233 static BOOL WINAPI fallbackDeleteFileW(LPCWSTR fname)
236 const int buflen = (int) (wStrLen(fname) + 1);
237 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
238 WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
239 retval = DeleteFileA(cpstr);
240 __PHYSFS_smallFree(cpstr);
242 } /* fallbackDeleteFileW */
244 static HANDLE WINAPI fallbackCreateFileW(LPCWSTR fname,
245 DWORD dwDesiredAccess, DWORD dwShareMode,
246 LPSECURITY_ATTRIBUTES lpSecurityAttrs,
247 DWORD dwCreationDisposition,
248 DWORD dwFlagsAndAttrs, HANDLE hTemplFile)
251 const int buflen = (int) (wStrLen(fname) + 1);
252 char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
253 WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
254 retval = CreateFileA(cpstr, dwDesiredAccess, dwShareMode, lpSecurityAttrs,
255 dwCreationDisposition, dwFlagsAndAttrs, hTemplFile);
256 __PHYSFS_smallFree(cpstr);
258 } /* fallbackCreateFileW */
261 /* A blatant abuse of pointer casting... */
262 static int symLookup(HMODULE dll, void **addr, const char *sym)
264 return( (*addr = GetProcAddress(dll, sym)) != NULL );
268 static int findApiSymbols(void)
272 #define LOOKUP_NOFALLBACK(x, reallyLook) { \
274 symLookup(dll, (void **) &p##x, #x); \
279 #define LOOKUP(x, reallyLook) { \
280 if ((!reallyLook) || (!symLookup(dll, (void **) &p##x, #x))) \
281 p##x = fallback##x; \
284 /* Apparently Win9x HAS the Unicode entry points, they just don't WORK. */
285 /* ...so don't look them up unless we're on NT+. (see osHasUnicode.) */
287 dll = libUserEnv = LoadLibraryA("userenv.dll");
289 LOOKUP_NOFALLBACK(GetUserProfileDirectoryW, osHasUnicode);
291 /* !!! FIXME: what do they call advapi32.dll on Win64? */
292 dll = libAdvApi32 = LoadLibraryA("advapi32.dll");
294 LOOKUP(GetUserNameW, osHasUnicode);
296 /* !!! FIXME: what do they call kernel32.dll on Win64? */
297 dll = libKernel32 = LoadLibraryA("kernel32.dll");
300 LOOKUP_NOFALLBACK(GetFileAttributesExA, 1);
301 LOOKUP_NOFALLBACK(GetFileAttributesExW, osHasUnicode);
302 LOOKUP_NOFALLBACK(FindFirstFileW, osHasUnicode);
303 LOOKUP_NOFALLBACK(FindNextFileW, osHasUnicode);
304 LOOKUP(GetModuleFileNameW, osHasUnicode);
305 LOOKUP(FormatMessageW, osHasUnicode);
306 LOOKUP(GetFileAttributesW, osHasUnicode);
307 LOOKUP(GetCurrentDirectoryW, osHasUnicode);
308 LOOKUP(CreateDirectoryW, osHasUnicode);
309 LOOKUP(RemoveDirectoryW, osHasUnicode);
310 LOOKUP(CreateFileW, osHasUnicode);
311 LOOKUP(DeleteFileW, osHasUnicode);
314 #undef LOOKUP_NOFALLBACK
318 } /* findApiSymbols */
321 const char *__PHYSFS_platformDirSeparator = "\\";
325 * Figure out what the last failing Windows API call was, and
326 * generate a human-readable string for the error message.
328 * The return value is a static buffer that is overwritten with
329 * each call to this function.
331 static const char *winApiStrError(void)
333 static char utf8buf[255];
336 DWORD rc = pFormatMessageW(
337 FORMAT_MESSAGE_FROM_SYSTEM |
338 FORMAT_MESSAGE_IGNORE_INSERTS,
339 NULL, GetLastError(),
340 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
341 msgbuf, __PHYSFS_ARRAYLEN(msgbuf),
344 /* chop off newlines. */
345 for (ptr = msgbuf; *ptr; ptr++)
347 if ((*ptr == '\n') || (*ptr == '\r'))
354 /* may truncate, but oh well. */
355 PHYSFS_utf8FromUcs2((PHYSFS_uint16 *) msgbuf, utf8buf, sizeof (utf8buf));
356 return((const char *) utf8buf);
357 } /* winApiStrError */
360 static char *getExePath(void)
364 LPWSTR modpath = NULL;
372 if ( !(ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) )
374 allocator.Free(modpath);
375 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
377 modpath = (LPWSTR) ptr;
379 rc = pGetModuleFileNameW(NULL, modpath, buflen);
382 allocator.Free(modpath);
383 BAIL_MACRO(winApiStrError(), NULL);
395 if (buflen > 0) /* just in case... */
397 WCHAR *ptr = (modpath + buflen) - 1;
398 while (ptr != modpath)
405 if ((ptr == modpath) && (*ptr != '\\'))
406 __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
409 *(ptr + 1) = '\0'; /* chop off filename. */
410 retval = unicodeToUtf8Heap(modpath);
413 allocator.Free(modpath);
415 return(retval); /* w00t. */
420 * Try to make use of GetUserProfileDirectoryW(), which isn't available on
421 * some common variants of Win32. If we can't use this, we just punt and
422 * use the physfs base dir for the user dir, too.
424 * On success, module-scope variable (userDir) will have a pointer to
425 * a malloc()'d string of the user's profile dir, and a non-zero value is
426 * returned. If we can't determine the profile dir, (userDir) will
427 * be NULL, and zero is returned.
429 static int determineUserDir(void)
432 return(1); /* already good to go. */
435 * GetUserProfileDirectoryW() is only available on NT 4.0 and later.
436 * This means Win95/98/ME (and CE?) users have to do without, so for
437 * them, we'll default to the base directory when we can't get the
438 * function pointer. Since this is originally an NT API, we don't
439 * offer a non-Unicode fallback.
441 if (pGetUserProfileDirectoryW != NULL)
443 HANDLE accessToken = NULL; /* Security handle to process */
444 HANDLE processHandle = GetCurrentProcess();
445 if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
453 * Should fail. Will write the size of the profile path in
454 * psize. Also note that the second parameter can't be
455 * NULL or the function fails.
457 rc = pGetUserProfileDirectoryW(accessToken, &dummy, &psize);
458 assert(!rc); /* !!! FIXME: handle this gracefully. */
460 /* Allocate memory for the profile directory */
461 wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
464 if (pGetUserProfileDirectoryW(accessToken, wstr, &psize))
465 userDir = unicodeToUtf8Heap(wstr);
466 __PHYSFS_smallFree(wstr);
470 CloseHandle(accessToken);
473 if (userDir == NULL) /* couldn't get profile for some reason. */
475 /* Might just be a non-NT system; resort to the basedir. */
476 userDir = getExePath();
477 BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
480 return(1); /* We made it: hit the showers. */
481 } /* determineUserDir */
484 static BOOL mediaInDrive(const char *drive)
490 /* Prevent windows warning message appearing when checking media size */
491 oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
493 /* If this function succeeds, there's media in the drive */
494 retval = GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0);
496 /* Revert back to old windows error handler */
497 SetErrorMode(oldErrorMode);
503 void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
505 /* !!! FIXME: Can CD drives be non-drive letter paths? */
506 /* !!! FIXME: (so can they be Unicode paths?) */
507 char drive_str[4] = "x:\\";
509 for (ch = 'A'; ch <= 'Z'; ch++)
512 if (GetDriveType(drive_str) == DRIVE_CDROM && mediaInDrive(drive_str))
515 } /* __PHYSFS_platformDetectAvailableCDs */
518 char *__PHYSFS_platformCalcBaseDir(const char *argv0)
520 if ((argv0 != NULL) && (strchr(argv0, '\\') != NULL))
521 return(NULL); /* default behaviour can handle this. */
523 return(getExePath());
524 } /* __PHYSFS_platformCalcBaseDir */
527 char *__PHYSFS_platformGetUserName(void)
532 if (pGetUserNameW(NULL, &bufsize) == 0) /* This SHOULD fail. */
534 LPWSTR wbuf = (LPWSTR) __PHYSFS_smallAlloc(bufsize * sizeof (WCHAR));
535 BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
536 if (pGetUserNameW(wbuf, &bufsize) == 0) /* ?! */
537 __PHYSFS_setError(winApiStrError());
539 retval = unicodeToUtf8Heap(wbuf);
540 __PHYSFS_smallFree(wbuf);
544 } /* __PHYSFS_platformGetUserName */
547 char *__PHYSFS_platformGetUserDir(void)
549 char *retval = (char *) allocator.Malloc(strlen(userDir) + 1);
550 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
551 strcpy(retval, userDir); /* calculated at init time. */
553 } /* __PHYSFS_platformGetUserDir */
556 PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
558 return((PHYSFS_uint64) GetCurrentThreadId());
559 } /* __PHYSFS_platformGetThreadID */
562 static int doPlatformExists(LPWSTR wpath)
566 pGetFileAttributesW(wpath) == PHYSFS_INVALID_FILE_ATTRIBUTES,
570 } /* doPlatformExists */
573 int __PHYSFS_platformExists(const char *fname)
577 UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
578 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
579 retval = doPlatformExists(wpath);
580 __PHYSFS_smallFree(wpath);
582 } /* __PHYSFS_platformExists */
585 static int isSymlinkAttrs(const DWORD attr, const DWORD tag)
587 return ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) &&
588 (tag == PHYSFS_IO_REPARSE_TAG_SYMLINK) );
589 } /* isSymlinkAttrs */
592 int __PHYSFS_platformIsSymLink(const char *fname)
595 * Windows Vista can have NTFS symlinks. Can older Windows releases have
596 * them when talking to a network file server? What happens when you
597 * mount a NTFS partition on XP that was plugged into a Vista install
598 * that made a symlink?
604 WIN32_FIND_DATAW entw;
606 /* no unicode entry points? Probably no symlinks. */
607 BAIL_IF_MACRO(pFindFirstFileW == NULL, NULL, 0);
609 UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
610 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
612 /* !!! FIXME: filter wildcard chars? */
613 dir = pFindFirstFileW(wpath, &entw);
614 if (dir != INVALID_HANDLE_VALUE)
616 retval = isSymlinkAttrs(entw.dwFileAttributes, entw.dwReserved0);
620 __PHYSFS_smallFree(wpath);
622 } /* __PHYSFS_platformIsSymlink */
625 int __PHYSFS_platformIsDirectory(const char *fname)
629 UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
630 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
631 retval = ((pGetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY) != 0);
632 __PHYSFS_smallFree(wpath);
634 } /* __PHYSFS_platformIsDirectory */
637 char *__PHYSFS_platformCvtToDependent(const char *prepend,
641 int len = ((prepend) ? strlen(prepend) : 0) +
642 ((append) ? strlen(append) : 0) +
644 char *retval = (char *) allocator.Malloc(len);
647 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
650 strcpy(retval, prepend);
654 strcat(retval, dirName);
657 strcat(retval, append);
659 for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
663 } /* __PHYSFS_platformCvtToDependent */
666 void __PHYSFS_platformEnumerateFiles(const char *dirname,
668 PHYSFS_EnumFilesCallback callback,
672 const int unicode = (pFindFirstFileW != NULL) && (pFindNextFileW != NULL);
673 HANDLE dir = INVALID_HANDLE_VALUE;
675 WIN32_FIND_DATAW entw;
676 size_t len = strlen(dirname);
677 char *searchPath = NULL;
678 WCHAR *wSearchPath = NULL;
681 /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
682 searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
683 if (searchPath == NULL)
686 /* Copy current dirname */
687 strcpy(searchPath, dirname);
689 /* if there's no '\\' at the end of the path, stick one in there. */
690 if (searchPath[len - 1] != '\\')
692 searchPath[len++] = '\\';
693 searchPath[len] = '\0';
696 /* Append the "*" to the end of the string */
697 strcat(searchPath, "*");
699 UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
700 if (wSearchPath == NULL)
701 return; /* oh well. */
704 dir = pFindFirstFileW(wSearchPath, &entw);
707 const int len = (int) (wStrLen(wSearchPath) + 1);
708 char *cp = (char *) __PHYSFS_smallAlloc(len);
711 WideCharToMultiByte(CP_ACP, 0, wSearchPath, len, cp, len, 0, 0);
712 dir = FindFirstFileA(cp, &ent);
713 __PHYSFS_smallFree(cp);
717 __PHYSFS_smallFree(wSearchPath);
718 __PHYSFS_smallFree(searchPath);
719 if (dir == INVALID_HANDLE_VALUE)
726 const DWORD attr = entw.dwFileAttributes;
727 const DWORD tag = entw.dwReserved0;
728 const WCHAR *fn = entw.cFileName;
729 if ((fn[0] == '.') && (fn[1] == '\0'))
731 if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
733 if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
736 utf8 = unicodeToUtf8Heap(fn);
739 callback(callbackdata, origdir, utf8);
740 allocator.Free(utf8);
742 } while (pFindNextFileW(dir, &entw) != 0);
745 else /* ANSI fallback. */
749 const DWORD attr = ent.dwFileAttributes;
750 const DWORD tag = ent.dwReserved0;
751 const char *fn = ent.cFileName;
752 if ((fn[0] == '.') && (fn[1] == '\0'))
754 if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
756 if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
759 utf8 = codepageToUtf8Heap(fn);
762 callback(callbackdata, origdir, utf8);
763 allocator.Free(utf8);
765 } while (FindNextFileA(dir, &ent) != 0);
769 } /* __PHYSFS_platformEnumerateFiles */
772 char *__PHYSFS_platformCurrentDir(void)
778 buflen = pGetCurrentDirectoryW(buflen, NULL);
779 wbuf = (WCHAR *) __PHYSFS_smallAlloc((buflen + 2) * sizeof (WCHAR));
780 BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
781 pGetCurrentDirectoryW(buflen, wbuf);
783 if (wbuf[buflen - 2] == '\\')
784 wbuf[buflen-1] = '\0'; /* just in case... */
787 wbuf[buflen - 1] = '\\';
791 retval = unicodeToUtf8Heap(wbuf);
792 __PHYSFS_smallFree(wbuf);
794 } /* __PHYSFS_platformCurrentDir */
797 /* this could probably use a cleanup. */
798 char *__PHYSFS_platformRealPath(const char *path)
800 /* !!! FIXME: try GetFullPathName() instead? */
801 /* this function should be UTF-8 clean. */
805 BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
806 BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
808 retval = (char *) allocator.Malloc(MAX_PATH);
809 BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
812 * If in \\server\path format, it's already an absolute path.
813 * We'll need to check for "." and ".." dirs, though, just in case.
815 if ((path[0] == '\\') && (path[1] == '\\'))
816 strcpy(retval, path);
820 char *currentDir = __PHYSFS_platformCurrentDir();
821 if (currentDir == NULL)
823 allocator.Free(retval);
824 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
827 if (path[1] == ':') /* drive letter specified? */
830 * Apparently, "D:mypath" is the same as "D:\\mypath" if
831 * D: is not the current drive. However, if D: is the
832 * current drive, then "D:mypath" is a relative path. Ugh.
834 if (path[2] == '\\') /* maybe an absolute path? */
835 strcpy(retval, path);
836 else /* definitely an absolute path. */
838 if (path[0] == currentDir[0]) /* current drive; relative. */
840 strcpy(retval, currentDir);
841 strcat(retval, path + 2);
844 else /* not current drive; absolute. */
849 strcpy(retval + 3, path + 2);
854 else /* no drive letter specified. */
856 if (path[0] == '\\') /* absolute path. */
858 retval[0] = currentDir[0];
860 strcpy(retval + 2, path);
864 strcpy(retval, currentDir);
865 strcat(retval, path);
869 allocator.Free(currentDir);
872 /* (whew.) Ok, now take out "." and ".." path entries... */
875 while ( (p = strstr(p, "\\.")) != NULL)
877 /* it's a "." entry that doesn't end the string. */
879 memmove(p + 1, p + 3, strlen(p + 3) + 1);
881 /* it's a "." entry that ends the string. */
882 else if (p[2] == '\0')
885 /* it's a ".." entry. */
886 else if (p[2] == '.')
888 char *prevEntry = p - 1;
889 while ((prevEntry != retval) && (*prevEntry != '\\'))
892 if (prevEntry == retval) /* make it look like a "." entry. */
893 memmove(p + 1, p + 2, strlen(p + 2) + 1);
896 if (p[3] != '\0') /* doesn't end string. */
898 else /* ends string. */
899 memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
907 p++; /* look past current char. */
911 /* shrink the retval's memory block if possible... */
912 p = (char *) allocator.Realloc(retval, strlen(retval) + 1);
917 } /* __PHYSFS_platformRealPath */
920 int __PHYSFS_platformMkDir(const char *path)
924 UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
925 rc = pCreateDirectoryW(wpath, NULL);
926 __PHYSFS_smallFree(wpath);
927 BAIL_IF_MACRO(rc == 0, winApiStrError(), 0);
929 } /* __PHYSFS_platformMkDir */
933 * Get OS info and save the important parts.
935 * Returns non-zero if successful, otherwise it returns zero on failure.
937 static int getOSInfo(void)
939 OSVERSIONINFO osVerInfo; /* Information about the OS */
940 osVerInfo.dwOSVersionInfoSize = sizeof(osVerInfo);
941 BAIL_IF_MACRO(!GetVersionEx(&osVerInfo), winApiStrError(), 0);
942 osHasUnicode = (osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS);
947 int __PHYSFS_platformInit(void)
949 BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
950 BAIL_IF_MACRO(!findApiSymbols(), NULL, 0);
951 BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
952 return(1); /* It's all good */
953 } /* __PHYSFS_platformInit */
956 int __PHYSFS_platformDeinit(void)
958 HANDLE *libs[] = { &libKernel32, &libUserEnv, &libAdvApi32, NULL };
961 allocator.Free(userDir);
964 for (i = 0; libs[i] != NULL; i++)
966 const HANDLE lib = *(libs[i]);
972 return(1); /* It's all good */
973 } /* __PHYSFS_platformDeinit */
976 static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
982 UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
983 BAIL_IF_MACRO(wfname == NULL, ERR_OUT_OF_MEMORY, NULL);
984 fileHandle = pCreateFileW(wfname, mode, FILE_SHARE_READ, NULL,
985 creation, FILE_ATTRIBUTE_NORMAL, NULL);
986 __PHYSFS_smallFree(wfname);
990 fileHandle == INVALID_HANDLE_VALUE,
991 winApiStrError(), NULL
994 retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
997 CloseHandle(fileHandle);
998 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1001 retval->readonly = rdonly;
1002 retval->handle = fileHandle;
1007 void *__PHYSFS_platformOpenRead(const char *filename)
1009 return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
1010 } /* __PHYSFS_platformOpenRead */
1013 void *__PHYSFS_platformOpenWrite(const char *filename)
1015 return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
1016 } /* __PHYSFS_platformOpenWrite */
1019 void *__PHYSFS_platformOpenAppend(const char *filename)
1021 void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
1024 HANDLE h = ((WinApiFile *) retval)->handle;
1025 DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
1026 if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
1028 const char *err = winApiStrError();
1030 allocator.Free(retval);
1031 BAIL_MACRO(err, NULL);
1036 } /* __PHYSFS_platformOpenAppend */
1039 PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
1040 PHYSFS_uint32 size, PHYSFS_uint32 count)
1042 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1043 DWORD CountOfBytesRead;
1044 PHYSFS_sint64 retval;
1046 /* Read data from the file */
1047 /* !!! FIXME: uint32 might be a greater # than DWORD */
1048 if(!ReadFile(Handle, buffer, count * size, &CountOfBytesRead, NULL))
1050 BAIL_MACRO(winApiStrError(), -1);
1054 /* Return the number of "objects" read. */
1055 /* !!! FIXME: What if not the right amount of bytes was read to make an object? */
1056 retval = CountOfBytesRead / size;
1060 } /* __PHYSFS_platformRead */
1063 PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
1064 PHYSFS_uint32 size, PHYSFS_uint32 count)
1066 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1067 DWORD CountOfBytesWritten;
1068 PHYSFS_sint64 retval;
1070 /* Read data from the file */
1071 /* !!! FIXME: uint32 might be a greater # than DWORD */
1072 if(!WriteFile(Handle, buffer, count * size, &CountOfBytesWritten, NULL))
1074 BAIL_MACRO(winApiStrError(), -1);
1078 /* Return the number of "objects" read. */
1079 /* !!! FIXME: What if not the right number of bytes was written? */
1080 retval = CountOfBytesWritten / size;
1084 } /* __PHYSFS_platformWrite */
1087 int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
1089 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1091 DWORD *pHighOrderPos;
1094 /* Get the high order 32-bits of the position */
1095 HighOrderPos = HIGHORDER_UINT64(pos);
1098 * MSDN: "If you do not need the high-order 32 bits, this
1099 * pointer must be set to NULL."
1101 pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
1104 * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
1105 * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
1106 * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
1107 * !!! FIXME: the sign extension of the value of lDistanceToMove.
1108 * !!! FIXME: Any other value will be rejected."
1111 /* Move pointer "pos" count from start of file */
1112 rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
1113 pHighOrderPos, FILE_BEGIN);
1115 if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
1116 (GetLastError() != NO_ERROR) )
1118 BAIL_MACRO(winApiStrError(), 0);
1121 return(1); /* No error occured */
1122 } /* __PHYSFS_platformSeek */
1125 PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
1127 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1130 PHYSFS_sint64 retval;
1132 /* Get current position */
1133 LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
1134 if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
1135 (GetLastError() != NO_ERROR) )
1137 BAIL_MACRO(winApiStrError(), 0);
1141 /* Combine the high/low order to create the 64-bit position value */
1142 retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
1143 assert(retval >= 0);
1147 } /* __PHYSFS_platformTell */
1150 PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
1152 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1155 PHYSFS_sint64 retval;
1157 SizeLow = GetFileSize(Handle, &SizeHigh);
1158 if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
1159 (GetLastError() != NO_ERROR) )
1161 BAIL_MACRO(winApiStrError(), -1);
1165 /* Combine the high/low order to create the 64-bit position value */
1166 retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
1167 assert(retval >= 0);
1171 } /* __PHYSFS_platformFileLength */
1174 int __PHYSFS_platformEOF(void *opaque)
1176 PHYSFS_sint64 FilePosition;
1179 /* Get the current position in the file */
1180 if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
1182 /* Non-zero if EOF is equal to the file length */
1183 retval = FilePosition == __PHYSFS_platformFileLength(opaque);
1187 } /* __PHYSFS_platformEOF */
1190 int __PHYSFS_platformFlush(void *opaque)
1192 WinApiFile *fh = ((WinApiFile *) opaque);
1194 BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), winApiStrError(), 0);
1197 } /* __PHYSFS_platformFlush */
1200 int __PHYSFS_platformClose(void *opaque)
1202 HANDLE Handle = ((WinApiFile *) opaque)->handle;
1203 BAIL_IF_MACRO(!CloseHandle(Handle), winApiStrError(), 0);
1204 allocator.Free(opaque);
1206 } /* __PHYSFS_platformClose */
1209 static int doPlatformDelete(LPWSTR wpath)
1211 /* If filename is a folder */
1212 if (pGetFileAttributesW(wpath) == FILE_ATTRIBUTE_DIRECTORY)
1214 BAIL_IF_MACRO(!pRemoveDirectoryW(wpath), winApiStrError(), 0);
1218 BAIL_IF_MACRO(!pDeleteFileW(wpath), winApiStrError(), 0);
1221 return(1); /* if you made it here, it worked. */
1222 } /* doPlatformDelete */
1225 int __PHYSFS_platformDelete(const char *path)
1229 UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
1230 BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
1231 retval = doPlatformDelete(wpath);
1232 __PHYSFS_smallFree(wpath);
1234 } /* __PHYSFS_platformDelete */
1238 * !!! FIXME: why aren't we using Critical Sections instead of Mutexes?
1239 * !!! FIXME: mutexes on Windows are for cross-process sync. CritSects are
1240 * !!! FIXME: mutexes for threads in a single process and are faster.
1242 void *__PHYSFS_platformCreateMutex(void)
1244 return((void *) CreateMutex(NULL, FALSE, NULL));
1245 } /* __PHYSFS_platformCreateMutex */
1248 void __PHYSFS_platformDestroyMutex(void *mutex)
1250 CloseHandle((HANDLE) mutex);
1251 } /* __PHYSFS_platformDestroyMutex */
1254 int __PHYSFS_platformGrabMutex(void *mutex)
1256 return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
1257 } /* __PHYSFS_platformGrabMutex */
1260 void __PHYSFS_platformReleaseMutex(void *mutex)
1262 ReleaseMutex((HANDLE) mutex);
1263 } /* __PHYSFS_platformReleaseMutex */
1266 static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
1269 SYSTEMTIME st_localtz;
1270 TIME_ZONE_INFORMATION tzi;
1272 PHYSFS_sint64 retval;
1275 BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), winApiStrError(), -1);
1276 tzid = GetTimeZoneInformation(&tzi);
1277 BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, winApiStrError(), -1);
1279 /* (This API is unsupported and fails on non-NT systems. */
1280 if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
1282 /* do it by hand. Grumble... */
1283 ULARGE_INTEGER ui64;
1285 ui64.LowPart = ft->dwLowDateTime;
1286 ui64.HighPart = ft->dwHighDateTime;
1288 if (tzid == TIME_ZONE_ID_STANDARD)
1289 tzi.Bias += tzi.StandardBias;
1290 else if (tzid == TIME_ZONE_ID_DAYLIGHT)
1291 tzi.Bias += tzi.DaylightBias;
1293 /* convert from minutes to 100-nanosecond increments... */
1294 ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
1296 /* Move it back into a FILETIME structure... */
1297 new_ft.dwLowDateTime = ui64.LowPart;
1298 new_ft.dwHighDateTime = ui64.HighPart;
1300 /* Convert to something human-readable... */
1301 if (!FileTimeToSystemTime(&new_ft, &st_localtz))
1302 BAIL_MACRO(winApiStrError(), -1);
1305 /* Convert to a format that mktime() can grok... */
1306 tm.tm_sec = st_localtz.wSecond;
1307 tm.tm_min = st_localtz.wMinute;
1308 tm.tm_hour = st_localtz.wHour;
1309 tm.tm_mday = st_localtz.wDay;
1310 tm.tm_mon = st_localtz.wMonth - 1;
1311 tm.tm_year = st_localtz.wYear - 1900;
1312 tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
1316 /* Convert to a format PhysicsFS can grok... */
1317 retval = (PHYSFS_sint64) mktime(&tm);
1318 BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
1320 } /* FileTimeToPhysfsTime */
1323 PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
1325 PHYSFS_sint64 retval = -1;
1326 WIN32_FILE_ATTRIBUTE_DATA attr;
1329 memset(&attr, '\0', sizeof (attr));
1331 /* GetFileAttributesEx didn't show up until Win98 and NT4. */
1332 if ((pGetFileAttributesExW != NULL) || (pGetFileAttributesExA != NULL))
1335 UTF8_TO_UNICODE_STACK_MACRO(wstr, fname);
1336 if (wstr != NULL) /* if NULL, maybe the fallback will work. */
1338 if (pGetFileAttributesExW != NULL) /* NT/XP/Vista/etc system. */
1339 rc = pGetFileAttributesExW(wstr, GetFileExInfoStandard, &attr);
1340 else /* Win98/ME system */
1342 const int len = (int) (wStrLen(wstr) + 1);
1343 char *cp = (char *) __PHYSFS_smallAlloc(len);
1346 WideCharToMultiByte(CP_ACP, 0, wstr, len, cp, len, 0, 0);
1347 rc = pGetFileAttributesExA(cp, GetFileExInfoStandard, &attr);
1348 __PHYSFS_smallFree(cp);
1351 __PHYSFS_smallFree(wstr);
1355 if (rc) /* had API entry point and it worked. */
1357 /* 0 return value indicates an error or not supported */
1358 if ( (attr.ftLastWriteTime.dwHighDateTime != 0) ||
1359 (attr.ftLastWriteTime.dwLowDateTime != 0) )
1361 retval = FileTimeToPhysfsTime(&attr.ftLastWriteTime);
1365 /* GetFileTime() has been in the Win32 API since the start. */
1366 if (retval == -1) /* try a fallback... */
1371 WinApiFile *f = (WinApiFile *) __PHYSFS_platformOpenRead(fname);
1372 BAIL_IF_MACRO(f == NULL, NULL, -1)
1373 rc = GetFileTime(f->handle, NULL, NULL, &ft);
1374 err = winApiStrError();
1375 CloseHandle(f->handle);
1377 BAIL_IF_MACRO(!rc, err, -1);
1378 retval = FileTimeToPhysfsTime(&ft);
1382 } /* __PHYSFS_platformGetLastModTime */
1385 /* !!! FIXME: Don't use C runtime for allocators? */
1386 int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
1388 return(0); /* just use malloc() and friends. */
1389 } /* __PHYSFS_platformSetDefaultAllocator */
1391 #endif /* PHYSFS_PLATFORM_WINDOWS */
1393 /* end of windows.c ... */