Upload 2.0.2
[physicsfs] / platform / windows.c
1 /*
2  * Windows support routines for PhysicsFS.
3  *
4  * Please see the file LICENSE.txt in the source's root directory.
5  *
6  *  This file written by Ryan C. Gordon, and made sane by Gregory S. Read.
7  */
8
9 #define __PHYSICSFS_INTERNAL__
10 #include "physfs_platforms.h"
11
12 #ifdef PHYSFS_PLATFORM_WINDOWS
13
14 /* Forcibly disable UNICODE, since we manage this ourselves. */
15 #ifdef UNICODE
16 #undef UNICODE
17 #endif
18
19 #include <windows.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <time.h>
26
27 #include "physfs_internal.h"
28
29 #define LOWORDER_UINT64(pos) ((PHYSFS_uint32) (pos & 0xFFFFFFFF))
30 #define HIGHORDER_UINT64(pos) ((PHYSFS_uint32) ((pos >> 32) & 0xFFFFFFFF))
31
32 /*
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
35  *  work as desired.
36  */
37 #define PHYSFS_INVALID_SET_FILE_POINTER  0xFFFFFFFF
38
39 /* just in case... */
40 #define PHYSFS_INVALID_FILE_ATTRIBUTES   0xFFFFFFFF
41
42 /* Not defined before the Vista SDK. */
43 #define PHYSFS_IO_REPARSE_TAG_SYMLINK    0xA000000C
44
45
46 #define UTF8_TO_UNICODE_STACK_MACRO(w_assignto, str) { \
47     if (str == NULL) \
48         w_assignto = NULL; \
49     else { \
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); \
54     } \
55 } \
56
57 static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
58 {
59     PHYSFS_uint64 len = 0;
60     while (*(wstr++))
61         len++;
62     return(len);
63 } /* wStrLen */
64
65 static char *unicodeToUtf8Heap(const WCHAR *w_str)
66 {
67     char *retval = NULL;
68     if (w_str != NULL)
69     {
70         void *ptr = NULL;
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. */
76         if (ptr != NULL)
77             retval = (char *) ptr;
78     } /* if */
79     return(retval);
80 } /* unicodeToUtf8Heap */
81
82
83 static char *codepageToUtf8Heap(const char *cpstr)
84 {
85     char *retval = NULL;
86     if (cpstr != NULL)
87     {
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);
93         if (retval == NULL)
94             __PHYSFS_setError(ERR_OUT_OF_MEMORY);
95         else
96             PHYSFS_utf8FromUcs2(wbuf, retval, len * 4);
97         __PHYSFS_smallFree(wbuf);
98     } /* if */
99     return(retval);
100 } /* codepageToUtf8Heap */
101
102
103 typedef struct
104 {
105     HANDLE handle;
106     int readonly;
107 } WinApiFile;
108
109
110 static char *userDir = NULL;
111 static int osHasUnicode = 0;
112
113
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);
136
137
138 /*
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.
144  */
145
146 static BOOL WINAPI fallbackGetUserNameW(LPWSTR buf, LPDWORD len)
147 {
148     const DWORD cplen = *len;
149     char *cpstr = __PHYSFS_smallAlloc(cplen);
150     BOOL retval = GetUserNameA(cpstr, len);
151     if (buf != NULL)
152         MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cpstr, cplen, buf, *len);
153     __PHYSFS_smallFree(cpstr);
154     return(retval);
155 } /* fallbackGetUserNameW */
156
157 static DWORD WINAPI fallbackFormatMessageW(DWORD dwFlags, LPCVOID lpSource,
158                                            DWORD dwMessageId, DWORD dwLangId,
159                                            LPWSTR lpBuf, DWORD nSize,
160                                            va_list *Arguments)
161 {
162     char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
163     DWORD retval = FormatMessageA(dwFlags, lpSource, dwMessageId, dwLangId,
164                                   cpbuf, nSize, Arguments);
165     if (retval > 0)
166         MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
167     __PHYSFS_smallFree(cpbuf);
168     return(retval);
169 } /* fallbackFormatMessageW */
170
171 static DWORD WINAPI fallbackGetModuleFileNameW(HMODULE hMod, LPWCH lpBuf,
172                                                DWORD nSize)
173 {
174     char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
175     DWORD retval = GetModuleFileNameA(hMod, cpbuf, nSize);
176     if (retval > 0)
177         MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
178     __PHYSFS_smallFree(cpbuf);
179     return(retval);
180 } /* fallbackGetModuleFileNameW */
181
182 static DWORD WINAPI fallbackGetFileAttributesW(LPCWSTR fname)
183 {
184     DWORD retval = 0;
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);
190     return(retval);
191 } /* fallbackGetFileAttributesW */
192
193 static DWORD WINAPI fallbackGetCurrentDirectoryW(DWORD buflen, LPWSTR buf)
194 {
195     DWORD retval = 0;
196     char *cpbuf = NULL;
197     if (buf != NULL)
198         cpbuf = (char *) __PHYSFS_smallAlloc(buflen);
199     retval = GetCurrentDirectoryA(buflen, cpbuf);
200     if (cpbuf != NULL)
201     {
202         MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,buf,buflen);
203         __PHYSFS_smallFree(cpbuf);
204     } /* if */
205     return(retval);
206 } /* fallbackGetCurrentDirectoryW */
207
208 static BOOL WINAPI fallbackRemoveDirectoryW(LPCWSTR dname)
209 {
210     BOOL retval = 0;
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);
216     return(retval);
217 } /* fallbackRemoveDirectoryW */
218
219 static BOOL WINAPI fallbackCreateDirectoryW(LPCWSTR dname, 
220                                             LPSECURITY_ATTRIBUTES attr)
221 {
222     BOOL retval = 0;
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);
228     return(retval);
229 } /* fallbackCreateDirectoryW */
230
231 static BOOL WINAPI fallbackDeleteFileW(LPCWSTR fname)
232 {
233     BOOL retval = 0;
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);
239     return(retval);
240 } /* fallbackDeleteFileW */
241
242 static HANDLE WINAPI fallbackCreateFileW(LPCWSTR fname, 
243                 DWORD dwDesiredAccess, DWORD dwShareMode,
244                 LPSECURITY_ATTRIBUTES lpSecurityAttrs,
245                 DWORD dwCreationDisposition,
246                 DWORD dwFlagsAndAttrs, HANDLE hTemplFile)
247 {
248     HANDLE retval;
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);
255     return(retval);
256 } /* fallbackCreateFileW */
257
258
259 #if (PHYSFS_MINIMUM_GCC_VERSION(3,3))
260     typedef FARPROC __attribute__((__may_alias__)) PHYSFS_FARPROC;
261 #else
262     typedef FARPROC PHYSFS_FARPROC;
263 #endif
264
265
266 static void symLookup(HMODULE dll, PHYSFS_FARPROC *addr, const char *sym,
267                       int reallyLook, PHYSFS_FARPROC fallback)
268 {
269     PHYSFS_FARPROC proc;
270     proc = (PHYSFS_FARPROC) ((reallyLook) ? GetProcAddress(dll, sym) : NULL);
271     if (proc == NULL)
272         proc = fallback;  /* may also be NULL. */
273     *addr = proc;
274 } /* symLookup */
275
276
277 static int findApiSymbols(void)
278 {
279     HMODULE dll = NULL;
280
281     #define LOOKUP_NOFALLBACK(x, reallyLook) \
282         symLookup(dll, (PHYSFS_FARPROC *) &p##x, #x, reallyLook, NULL)
283
284     #define LOOKUP(x, reallyLook) \
285         symLookup(dll, (PHYSFS_FARPROC *) &p##x, #x, \
286                   reallyLook, (PHYSFS_FARPROC) fallback##x)
287
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.) */
290
291     dll = libUserEnv = LoadLibraryA("userenv.dll");
292     if (dll != NULL)
293         LOOKUP_NOFALLBACK(GetUserProfileDirectoryW, osHasUnicode);
294
295     /* !!! FIXME: what do they call advapi32.dll on Win64? */
296     dll = libAdvApi32 = LoadLibraryA("advapi32.dll");
297     if (dll != NULL)
298         LOOKUP(GetUserNameW, osHasUnicode);
299
300     /* !!! FIXME: what do they call kernel32.dll on Win64? */
301     dll = libKernel32 = LoadLibraryA("kernel32.dll");
302     if (dll != NULL)
303     {
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);
316     } /* if */
317
318     #undef LOOKUP_NOFALLBACK
319     #undef LOOKUP
320
321     return(1);
322 } /* findApiSymbols */
323
324
325 const char *__PHYSFS_platformDirSeparator = "\\";
326
327
328 /*
329  * Figure out what the last failing Windows API call was, and
330  *  generate a human-readable string for the error message.
331  *
332  * The return value is a static buffer that is overwritten with
333  *  each call to this function.
334  */
335 static const char *winApiStrError(void)
336 {
337     static char utf8buf[255];
338     WCHAR msgbuf[255];
339     WCHAR *ptr;
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),
346                     NULL);
347
348     if (rc == 0)
349         msgbuf[0] = '\0';  /* oh well. */
350
351     /* chop off newlines. */
352     for (ptr = msgbuf; *ptr; ptr++)
353     {
354         if ((*ptr == '\n') || (*ptr == '\r'))
355         {
356             *ptr = '\0';
357             break;
358         } /* if */
359     } /* for */
360
361     /* may truncate, but oh well. */
362     PHYSFS_utf8FromUcs2((PHYSFS_uint16 *) msgbuf, utf8buf, sizeof (utf8buf));
363     return((const char *) utf8buf);
364 } /* winApiStrError */
365
366
367 static char *getExePath(void)
368 {
369     DWORD buflen = 64;
370     LPWSTR modpath = NULL;
371     char *retval = NULL;
372
373     while (1)
374     {
375         DWORD rc;
376         void *ptr;
377
378         if ( !(ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) )
379         {
380             allocator.Free(modpath);
381             BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
382         } /* if */
383         modpath = (LPWSTR) ptr;
384
385         rc = pGetModuleFileNameW(NULL, modpath, buflen);
386         if (rc == 0)
387         {
388             allocator.Free(modpath);
389             BAIL_MACRO(winApiStrError(), NULL);
390         } /* if */
391
392         if (rc < buflen)
393         {
394             buflen = rc;
395             break;
396         } /* if */
397
398         buflen *= 2;
399     } /* while */
400
401     if (buflen > 0)  /* just in case... */
402     {
403         WCHAR *ptr = (modpath + buflen) - 1;
404         while (ptr != modpath)
405         {
406             if (*ptr == '\\')
407                 break;
408             ptr--;
409         } /* while */
410
411         if ((ptr == modpath) && (*ptr != '\\'))
412             __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
413         else
414         {
415             *(ptr + 1) = '\0';  /* chop off filename. */
416             retval = unicodeToUtf8Heap(modpath);
417         } /* else */
418     } /* else */
419     allocator.Free(modpath);
420
421     return(retval);   /* w00t. */
422 } /* getExePath */
423
424
425 /*
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.
429  *
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.
434  */
435 static int determineUserDir(void)
436 {
437     if (userDir != NULL)
438         return(1);  /* already good to go. */
439
440     /*
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.
446      */
447     if (pGetUserProfileDirectoryW != NULL)
448     {
449         HANDLE accessToken = NULL;       /* Security handle to process */
450         HANDLE processHandle = GetCurrentProcess();
451         if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
452         {
453             DWORD psize = 0;
454             WCHAR dummy = 0;
455             LPWSTR wstr = NULL;
456             BOOL rc = 0;
457
458             /*
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.
462              */ 
463                 rc = pGetUserProfileDirectoryW(accessToken, &dummy, &psize);
464             assert(!rc);  /* !!! FIXME: handle this gracefully. */
465
466             /* Allocate memory for the profile directory */
467             wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
468             if (wstr != NULL)
469             {
470                 if (pGetUserProfileDirectoryW(accessToken, wstr, &psize))
471                     userDir = unicodeToUtf8Heap(wstr);
472                 __PHYSFS_smallFree(wstr);
473             } /* else */
474         } /* if */
475
476         CloseHandle(accessToken);
477     } /* if */
478
479     if (userDir == NULL)  /* couldn't get profile for some reason. */
480     {
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?! */
484     } /* if */
485
486     return(1);  /* We made it: hit the showers. */
487 } /* determineUserDir */
488
489
490 static BOOL mediaInDrive(const char *drive)
491 {
492     UINT oldErrorMode;
493     DWORD tmp;
494     BOOL retval;
495
496     /* Prevent windows warning message appearing when checking media size */
497     oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
498     
499     /* If this function succeeds, there's media in the drive */
500     retval = GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0);
501
502     /* Revert back to old windows error handler */
503     SetErrorMode(oldErrorMode);
504
505     return(retval);
506 } /* mediaInDrive */
507
508
509 void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
510 {
511     /* !!! FIXME: Can CD drives be non-drive letter paths? */
512     /* !!! FIXME:  (so can they be Unicode paths?) */
513     char drive_str[4] = "x:\\";
514     char ch;
515     for (ch = 'A'; ch <= 'Z'; ch++)
516     {
517         drive_str[0] = ch;
518         if (GetDriveType(drive_str) == DRIVE_CDROM && mediaInDrive(drive_str))
519             cb(data, drive_str);
520     } /* for */
521 } /* __PHYSFS_platformDetectAvailableCDs */
522
523
524 char *__PHYSFS_platformCalcBaseDir(const char *argv0)
525 {
526     if ((argv0 != NULL) && (strchr(argv0, '\\') != NULL))
527         return(NULL); /* default behaviour can handle this. */
528
529     return(getExePath());
530 } /* __PHYSFS_platformCalcBaseDir */
531
532
533 char *__PHYSFS_platformGetUserName(void)
534 {
535     DWORD bufsize = 0;
536     char *retval = NULL;
537     
538     if (pGetUserNameW(NULL, &bufsize) == 0)  /* This SHOULD fail. */
539     {
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());
544         else
545             retval = unicodeToUtf8Heap(wbuf);
546         __PHYSFS_smallFree(wbuf);
547     } /* if */
548
549     return(retval);
550 } /* __PHYSFS_platformGetUserName */
551
552
553 char *__PHYSFS_platformGetUserDir(void)
554 {
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. */
558     return(retval);
559 } /* __PHYSFS_platformGetUserDir */
560
561
562 PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
563 {
564     return((PHYSFS_uint64) GetCurrentThreadId());
565 } /* __PHYSFS_platformGetThreadID */
566
567
568 static int doPlatformExists(LPWSTR wpath)
569 {
570     BAIL_IF_MACRO
571     (
572         pGetFileAttributesW(wpath) == PHYSFS_INVALID_FILE_ATTRIBUTES,
573         winApiStrError(), 0
574     );
575     return(1);
576 } /* doPlatformExists */
577
578
579 int __PHYSFS_platformExists(const char *fname)
580 {
581     int retval = 0;
582     LPWSTR wpath;
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);
587     return(retval);
588 } /* __PHYSFS_platformExists */
589
590
591 static int isSymlinkAttrs(const DWORD attr, const DWORD tag)
592 {
593     return ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) && 
594              (tag == PHYSFS_IO_REPARSE_TAG_SYMLINK) );
595 } /* isSymlinkAttrs */
596
597
598 int __PHYSFS_platformIsSymLink(const char *fname)
599 {
600     /* !!! FIXME:
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?
605      */
606
607     int retval = 0;
608     LPWSTR wpath;
609     HANDLE dir;
610     WIN32_FIND_DATAW entw;
611
612     /* no unicode entry points? Probably no symlinks. */
613     BAIL_IF_MACRO(pFindFirstFileW == NULL, NULL, 0);
614
615     UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
616     BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
617
618     /* !!! FIXME: filter wildcard chars? */
619     dir = pFindFirstFileW(wpath, &entw);
620     if (dir != INVALID_HANDLE_VALUE)
621     {
622         retval = isSymlinkAttrs(entw.dwFileAttributes, entw.dwReserved0);
623         FindClose(dir);
624     } /* if */
625
626     __PHYSFS_smallFree(wpath);
627     return(retval);
628 } /* __PHYSFS_platformIsSymlink */
629
630
631 int __PHYSFS_platformIsDirectory(const char *fname)
632 {
633     int retval = 0;
634     LPWSTR wpath;
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);
639     return(retval);
640 } /* __PHYSFS_platformIsDirectory */
641
642
643 char *__PHYSFS_platformCvtToDependent(const char *prepend,
644                                       const char *dirName,
645                                       const char *append)
646 {
647     int len = ((prepend) ? strlen(prepend) : 0) +
648               ((append) ? strlen(append) : 0) +
649               strlen(dirName) + 1;
650     char *retval = (char *) allocator.Malloc(len);
651     char *p;
652
653     BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
654
655     if (prepend)
656         strcpy(retval, prepend);
657     else
658         retval[0] = '\0';
659
660     strcat(retval, dirName);
661
662     if (append)
663         strcat(retval, append);
664
665     for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
666         *p = '\\';
667
668     return(retval);
669 } /* __PHYSFS_platformCvtToDependent */
670
671
672 void __PHYSFS_platformEnumerateFiles(const char *dirname,
673                                      int omitSymLinks,
674                                      PHYSFS_EnumFilesCallback callback,
675                                      const char *origdir,
676                                      void *callbackdata)
677 {
678     const int unicode = (pFindFirstFileW != NULL) && (pFindNextFileW != NULL);
679     HANDLE dir = INVALID_HANDLE_VALUE;
680     WIN32_FIND_DATA ent;
681     WIN32_FIND_DATAW entw;
682     size_t len = strlen(dirname);
683     char *searchPath = NULL;
684     WCHAR *wSearchPath = NULL;
685     char *utf8 = NULL;
686
687     /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
688     searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
689     if (searchPath == NULL)
690         return;
691
692     /* Copy current dirname */
693     strcpy(searchPath, dirname);
694
695     /* if there's no '\\' at the end of the path, stick one in there. */
696     if (searchPath[len - 1] != '\\')
697     {
698         searchPath[len++] = '\\';
699         searchPath[len] = '\0';
700     } /* if */
701
702     /* Append the "*" to the end of the string */
703     strcat(searchPath, "*");
704
705     UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
706     if (wSearchPath == NULL)
707         return;  /* oh well. */
708
709     if (unicode)
710         dir = pFindFirstFileW(wSearchPath, &entw);
711     else
712     {
713         const int len = (int) (wStrLen(wSearchPath) + 1);
714         char *cp = (char *) __PHYSFS_smallAlloc(len);
715         if (cp != NULL)
716         {
717             WideCharToMultiByte(CP_ACP, 0, wSearchPath, len, cp, len, 0, 0);
718             dir = FindFirstFileA(cp, &ent);
719             __PHYSFS_smallFree(cp);
720         } /* if */
721     } /* else */
722
723     __PHYSFS_smallFree(wSearchPath);
724     __PHYSFS_smallFree(searchPath);
725     if (dir == INVALID_HANDLE_VALUE)
726         return;
727
728     if (unicode)
729     {
730         do
731         {
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'))
736                 continue;
737             if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
738                 continue;
739             if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
740                 continue;
741
742             utf8 = unicodeToUtf8Heap(fn);
743             if (utf8 != NULL)
744             {
745                 callback(callbackdata, origdir, utf8);
746                 allocator.Free(utf8);
747             } /* if */
748         } while (pFindNextFileW(dir, &entw) != 0);
749     } /* if */
750
751     else  /* ANSI fallback. */
752     {
753         do
754         {
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'))
759                 continue;
760             if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
761                 continue;
762             if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
763                 continue;
764
765             utf8 = codepageToUtf8Heap(fn);
766             if (utf8 != NULL)
767             {
768                 callback(callbackdata, origdir, utf8);
769                 allocator.Free(utf8);
770             } /* if */
771         } while (FindNextFileA(dir, &ent) != 0);
772     } /* else */
773
774     FindClose(dir);
775 } /* __PHYSFS_platformEnumerateFiles */
776
777
778 char *__PHYSFS_platformCurrentDir(void)
779 {
780     char *retval = NULL;
781     WCHAR *wbuf = NULL;
782     DWORD buflen = 0;
783
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);
788
789     if (wbuf[buflen - 2] == '\\')
790         wbuf[buflen-1] = '\0';  /* just in case... */
791     else
792     {
793         wbuf[buflen - 1] = '\\'; 
794         wbuf[buflen] = '\0'; 
795     } /* else */
796
797     retval = unicodeToUtf8Heap(wbuf);
798     __PHYSFS_smallFree(wbuf);
799     return(retval);
800 } /* __PHYSFS_platformCurrentDir */
801
802
803 /* this could probably use a cleanup. */
804 char *__PHYSFS_platformRealPath(const char *path)
805 {
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. */
810     char *retval = NULL;
811     char *p = NULL;
812
813     BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
814     BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
815
816     retval = (char *) allocator.Malloc(MAX_PATH);
817     BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
818
819         /*
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.
822          */
823     if ((path[0] == '\\') && (path[1] == '\\'))
824         strcpy(retval, path);
825
826     else
827     {
828         char *currentDir = __PHYSFS_platformCurrentDir();
829         if (currentDir == NULL)
830         {
831             allocator.Free(retval);
832             BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
833         } /* if */
834
835         if (path[1] == ':')   /* drive letter specified? */
836         {
837             /*
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.
841              */
842             if (path[2] == '\\')  /* maybe an absolute path? */
843                 strcpy(retval, path);
844             else  /* definitely an absolute path. */
845             {
846                 if (path[0] == currentDir[0]) /* current drive; relative. */
847                 {
848                     strcpy(retval, currentDir);
849                     strcat(retval, path + 2);
850                 } /* if */
851
852                 else  /* not current drive; absolute. */
853                 {
854                     retval[0] = path[0];
855                     retval[1] = ':';
856                     retval[2] = '\\';
857                     strcpy(retval + 3, path + 2);
858                 } /* else */
859             } /* else */
860         } /* if */
861
862         else  /* no drive letter specified. */
863         {
864             if (path[0] == '\\')  /* absolute path. */
865             {
866                 retval[0] = currentDir[0];
867                 retval[1] = ':';
868                 strcpy(retval + 2, path);
869             } /* if */
870             else
871             {
872                 strcpy(retval, currentDir);
873                 strcat(retval, path);
874             } /* else */
875         } /* else */
876
877         allocator.Free(currentDir);
878     } /* else */
879
880     /* (whew.) Ok, now take out "." and ".." path entries... */
881
882     p = retval;
883     while ( (p = strstr(p, "\\.")) != NULL)
884     {
885         /* it's a "." entry that doesn't end the string. */
886         if (p[2] == '\\')
887             memmove(p + 1, p + 3, strlen(p + 3) + 1);
888
889         /* it's a "." entry that ends the string. */
890         else if (p[2] == '\0')
891             p[0] = '\0';
892
893         /* it's a ".." entry. */
894         else if (p[2] == '.')
895         {
896             char *prevEntry = p - 1;
897             while ((prevEntry != retval) && (*prevEntry != '\\'))
898                 prevEntry--;
899
900             if (prevEntry == retval)  /* make it look like a "." entry. */
901                 memmove(p + 1, p + 2, strlen(p + 2) + 1);
902             else
903             {
904                 if (p[3] != '\0') /* doesn't end string. */
905                     *prevEntry = '\0';
906                 else /* ends string. */
907                     memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
908
909                 p = prevEntry;
910             } /* else */
911         } /* else if */
912
913         else
914         {
915             p++;  /* look past current char. */
916         } /* else */
917     } /* while */
918
919     /* shrink the retval's memory block if possible... */
920     p = (char *) allocator.Realloc(retval, strlen(retval) + 1);
921     if (p != NULL)
922         retval = p;
923
924     return(retval);
925 } /* __PHYSFS_platformRealPath */
926
927
928 int __PHYSFS_platformMkDir(const char *path)
929 {
930     WCHAR *wpath;
931     DWORD rc;
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);
936     return(1);
937 } /* __PHYSFS_platformMkDir */
938
939
940  /*
941   * Get OS info and save the important parts.
942   *
943   * Returns non-zero if successful, otherwise it returns zero on failure.
944   */
945 static int getOSInfo(void)
946 {
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);
951     return(1);
952 } /* getOSInfo */
953
954
955 int __PHYSFS_platformInit(void)
956 {
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 */
962
963
964 int __PHYSFS_platformDeinit(void)
965 {
966     HANDLE *libs[] = { &libKernel32, &libUserEnv, &libAdvApi32, NULL };
967     int i;
968
969     allocator.Free(userDir);
970     userDir = NULL;
971
972     for (i = 0; libs[i] != NULL; i++)
973     {
974         const HANDLE lib = *(libs[i]);
975         if (lib)
976             FreeLibrary(lib);
977         *(libs[i]) = NULL;
978     } /* for */
979
980     return(1); /* It's all good */
981 } /* __PHYSFS_platformDeinit */
982
983
984 static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
985 {
986     HANDLE fileHandle;
987     WinApiFile *retval;
988     WCHAR *wfname;
989
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);
995
996     BAIL_IF_MACRO
997     (
998         fileHandle == INVALID_HANDLE_VALUE,
999         winApiStrError(), NULL
1000     );
1001
1002     retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
1003     if (retval == NULL)
1004     {
1005         CloseHandle(fileHandle);
1006         BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1007     } /* if */
1008
1009     retval->readonly = rdonly;
1010     retval->handle = fileHandle;
1011     return(retval);
1012 } /* doOpen */
1013
1014
1015 void *__PHYSFS_platformOpenRead(const char *filename)
1016 {
1017     return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
1018 } /* __PHYSFS_platformOpenRead */
1019
1020
1021 void *__PHYSFS_platformOpenWrite(const char *filename)
1022 {
1023     return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
1024 } /* __PHYSFS_platformOpenWrite */
1025
1026
1027 void *__PHYSFS_platformOpenAppend(const char *filename)
1028 {
1029     void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
1030     if (retval != NULL)
1031     {
1032         HANDLE h = ((WinApiFile *) retval)->handle;
1033         DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
1034         if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
1035         {
1036             const char *err = winApiStrError();
1037             CloseHandle(h);
1038             allocator.Free(retval);
1039             BAIL_MACRO(err, NULL);
1040         } /* if */
1041     } /* if */
1042
1043     return(retval);
1044 } /* __PHYSFS_platformOpenAppend */
1045
1046
1047 PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
1048                                     PHYSFS_uint32 size, PHYSFS_uint32 count)
1049 {
1050     HANDLE Handle = ((WinApiFile *) opaque)->handle;
1051     DWORD CountOfBytesRead;
1052     PHYSFS_sint64 retval;
1053
1054     /* Read data from the file */
1055     /* !!! FIXME: uint32 might be a greater # than DWORD */
1056     if(!ReadFile(Handle, buffer, count * size, &CountOfBytesRead, NULL))
1057     {
1058         BAIL_MACRO(winApiStrError(), -1);
1059     } /* if */
1060     else
1061     {
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;
1065     } /* else */
1066
1067     return(retval);
1068 } /* __PHYSFS_platformRead */
1069
1070
1071 PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
1072                                      PHYSFS_uint32 size, PHYSFS_uint32 count)
1073 {
1074     HANDLE Handle = ((WinApiFile *) opaque)->handle;
1075     DWORD CountOfBytesWritten;
1076     PHYSFS_sint64 retval;
1077
1078     /* Read data from the file */
1079     /* !!! FIXME: uint32 might be a greater # than DWORD */
1080     if(!WriteFile(Handle, buffer, count * size, &CountOfBytesWritten, NULL))
1081     {
1082         BAIL_MACRO(winApiStrError(), -1);
1083     } /* if */
1084     else
1085     {
1086         /* Return the number of "objects" read. */
1087         /* !!! FIXME: What if not the right number of bytes was written? */
1088         retval = CountOfBytesWritten / size;
1089     } /* else */
1090
1091     return(retval);
1092 } /* __PHYSFS_platformWrite */
1093
1094
1095 int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
1096 {
1097     HANDLE Handle = ((WinApiFile *) opaque)->handle;
1098     LONG HighOrderPos;
1099     PLONG pHighOrderPos;
1100     DWORD rc;
1101
1102     /* Get the high order 32-bits of the position */
1103     HighOrderPos = HIGHORDER_UINT64(pos);
1104
1105     /*
1106      * MSDN: "If you do not need the high-order 32 bits, this
1107      *         pointer must be set to NULL."
1108      */
1109     pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
1110
1111     /*
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."
1117      */
1118
1119     /* Move pointer "pos" count from start of file */
1120     rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
1121                         pHighOrderPos, FILE_BEGIN);
1122
1123     if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
1124          (GetLastError() != NO_ERROR) )
1125     {
1126         BAIL_MACRO(winApiStrError(), 0);
1127     } /* if */
1128     
1129     return(1);  /* No error occured */
1130 } /* __PHYSFS_platformSeek */
1131
1132
1133 PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
1134 {
1135     HANDLE Handle = ((WinApiFile *) opaque)->handle;
1136     LONG HighPos = 0;
1137     DWORD LowPos;
1138     PHYSFS_sint64 retval;
1139
1140     /* Get current position */
1141     LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
1142     if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
1143          (GetLastError() != NO_ERROR) )
1144     {
1145         BAIL_MACRO(winApiStrError(), 0);
1146     } /* if */
1147     else
1148     {
1149         /* Combine the high/low order to create the 64-bit position value */
1150         retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
1151         assert(retval >= 0);
1152     } /* else */
1153
1154     return(retval);
1155 } /* __PHYSFS_platformTell */
1156
1157
1158 PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
1159 {
1160     HANDLE Handle = ((WinApiFile *) opaque)->handle;
1161     DWORD SizeHigh;
1162     DWORD SizeLow;
1163     PHYSFS_sint64 retval;
1164
1165     SizeLow = GetFileSize(Handle, &SizeHigh);
1166     if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
1167          (GetLastError() != NO_ERROR) )
1168     {
1169         BAIL_MACRO(winApiStrError(), -1);
1170     } /* if */
1171     else
1172     {
1173         /* Combine the high/low order to create the 64-bit position value */
1174         retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
1175         assert(retval >= 0);
1176     } /* else */
1177
1178     return(retval);
1179 } /* __PHYSFS_platformFileLength */
1180
1181
1182 int __PHYSFS_platformEOF(void *opaque)
1183 {
1184     PHYSFS_sint64 FilePosition;
1185     int retval = 0;
1186
1187     /* Get the current position in the file */
1188     if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
1189     {
1190         /* Non-zero if EOF is equal to the file length */
1191         retval = FilePosition == __PHYSFS_platformFileLength(opaque);
1192     } /* if */
1193
1194     return(retval);
1195 } /* __PHYSFS_platformEOF */
1196
1197
1198 int __PHYSFS_platformFlush(void *opaque)
1199 {
1200     WinApiFile *fh = ((WinApiFile *) opaque);
1201     if (!fh->readonly)
1202         BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), winApiStrError(), 0);
1203
1204     return(1);
1205 } /* __PHYSFS_platformFlush */
1206
1207
1208 int __PHYSFS_platformClose(void *opaque)
1209 {
1210     HANDLE Handle = ((WinApiFile *) opaque)->handle;
1211     BAIL_IF_MACRO(!CloseHandle(Handle), winApiStrError(), 0);
1212     allocator.Free(opaque);
1213     return(1);
1214 } /* __PHYSFS_platformClose */
1215
1216
1217 static int doPlatformDelete(LPWSTR wpath)
1218 {
1219     /* If filename is a folder */
1220     if (pGetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)
1221     {
1222         BAIL_IF_MACRO(!pRemoveDirectoryW(wpath), winApiStrError(), 0);
1223     } /* if */
1224     else
1225     {
1226         BAIL_IF_MACRO(!pDeleteFileW(wpath), winApiStrError(), 0);
1227     } /* else */
1228
1229     return(1);   /* if you made it here, it worked. */
1230 } /* doPlatformDelete */
1231
1232
1233 int __PHYSFS_platformDelete(const char *path)
1234 {
1235     int retval = 0;
1236     LPWSTR wpath;
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);
1241     return(retval);
1242 } /* __PHYSFS_platformDelete */
1243
1244
1245 /*
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.
1249  */
1250 void *__PHYSFS_platformCreateMutex(void)
1251 {
1252     return((void *) CreateMutex(NULL, FALSE, NULL));
1253 } /* __PHYSFS_platformCreateMutex */
1254
1255
1256 void __PHYSFS_platformDestroyMutex(void *mutex)
1257 {
1258     CloseHandle((HANDLE) mutex);
1259 } /* __PHYSFS_platformDestroyMutex */
1260
1261
1262 int __PHYSFS_platformGrabMutex(void *mutex)
1263 {
1264     return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
1265 } /* __PHYSFS_platformGrabMutex */
1266
1267
1268 void __PHYSFS_platformReleaseMutex(void *mutex)
1269 {
1270     ReleaseMutex((HANDLE) mutex);
1271 } /* __PHYSFS_platformReleaseMutex */
1272
1273
1274 static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
1275 {
1276     SYSTEMTIME st_utc;
1277     SYSTEMTIME st_localtz;
1278     TIME_ZONE_INFORMATION tzi;
1279     DWORD tzid;
1280     PHYSFS_sint64 retval;
1281     struct tm tm;
1282
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);
1286
1287     /* (This API is unsupported and fails on non-NT systems. */
1288     if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
1289     {
1290         /* do it by hand. Grumble... */
1291         ULARGE_INTEGER ui64;
1292         FILETIME new_ft;
1293         ui64.LowPart = ft->dwLowDateTime;
1294         ui64.HighPart = ft->dwHighDateTime;
1295
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;
1300
1301         /* convert from minutes to 100-nanosecond increments... */
1302         ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
1303
1304         /* Move it back into a FILETIME structure... */
1305         new_ft.dwLowDateTime = ui64.LowPart;
1306         new_ft.dwHighDateTime = ui64.HighPart;
1307
1308         /* Convert to something human-readable... */
1309         if (!FileTimeToSystemTime(&new_ft, &st_localtz))
1310             BAIL_MACRO(winApiStrError(), -1);
1311     } /* if */
1312
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*/;
1321     tm.tm_yday = -1;
1322     tm.tm_isdst = -1;
1323
1324     /* Convert to a format PhysicsFS can grok... */
1325     retval = (PHYSFS_sint64) mktime(&tm);
1326     BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
1327     return(retval);
1328 } /* FileTimeToPhysfsTime */
1329
1330
1331 PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
1332 {
1333     PHYSFS_sint64 retval = -1;
1334     WIN32_FILE_ATTRIBUTE_DATA attr;
1335     int rc = 0;
1336
1337     memset(&attr, '\0', sizeof (attr));
1338
1339     /* GetFileAttributesEx didn't show up until Win98 and NT4. */
1340     if ((pGetFileAttributesExW != NULL) || (pGetFileAttributesExA != NULL))
1341     {
1342         WCHAR *wstr;
1343         UTF8_TO_UNICODE_STACK_MACRO(wstr, fname);
1344         if (wstr != NULL) /* if NULL, maybe the fallback will work. */
1345         {
1346             if (pGetFileAttributesExW != NULL)  /* NT/XP/Vista/etc system. */
1347                 rc = pGetFileAttributesExW(wstr, GetFileExInfoStandard, &attr);
1348             else  /* Win98/ME system */
1349             {
1350                 const int len = (int) (wStrLen(wstr) + 1);
1351                 char *cp = (char *) __PHYSFS_smallAlloc(len);
1352                 if (cp != NULL)
1353                 {
1354                     WideCharToMultiByte(CP_ACP, 0, wstr, len, cp, len, 0, 0);
1355                     rc = pGetFileAttributesExA(cp, GetFileExInfoStandard, &attr);
1356                     __PHYSFS_smallFree(cp);
1357                 } /* if */
1358             } /* else */
1359             __PHYSFS_smallFree(wstr);
1360         } /* if */
1361     } /* if */
1362
1363     if (rc)  /* had API entry point and it worked. */
1364     {
1365         /* 0 return value indicates an error or not supported */
1366         if ( (attr.ftLastWriteTime.dwHighDateTime != 0) ||
1367              (attr.ftLastWriteTime.dwLowDateTime != 0) )
1368         {
1369             retval = FileTimeToPhysfsTime(&attr.ftLastWriteTime);
1370         } /* if */
1371     } /* if */
1372
1373     /* GetFileTime() has been in the Win32 API since the start. */
1374     if (retval == -1)  /* try a fallback... */
1375     {
1376         FILETIME ft;
1377         BOOL rc;
1378         const char *err;
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);
1384         allocator.Free(f);
1385         BAIL_IF_MACRO(!rc, err, -1);
1386         retval = FileTimeToPhysfsTime(&ft);
1387     } /* if */
1388
1389     return(retval);
1390 } /* __PHYSFS_platformGetLastModTime */
1391
1392
1393 /* !!! FIXME: Don't use C runtime for allocators? */
1394 int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
1395 {
1396     return(0);  /* just use malloc() and friends. */
1397 } /* __PHYSFS_platformSetDefaultAllocator */
1398
1399 #endif  /* PHYSFS_PLATFORM_WINDOWS */
1400
1401 /* end of windows.c ... */
1402
1403