misc/libphysfs/platform_windows.c
changeset 13881 99b265e0d1d0
parent 13880 5f819b90d479
child 13882 b172a5d40eee
equal deleted inserted replaced
13880:5f819b90d479 13881:99b265e0d1d0
     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 #ifndef PHYSFS_PLATFORM_WINRT
       
    14 
       
    15 /* Forcibly disable UNICODE macro, since we manage this ourselves. */
       
    16 #ifdef UNICODE
       
    17 #undef UNICODE
       
    18 #endif
       
    19 
       
    20 #define WIN32_LEAN_AND_MEAN 1
       
    21 #include <windows.h>
       
    22 #include <userenv.h>
       
    23 #include <shlobj.h>
       
    24 #include <dbt.h>
       
    25 #include <errno.h>
       
    26 #include <ctype.h>
       
    27 #include <time.h>
       
    28 
       
    29 #include "physfs_internal.h"
       
    30 
       
    31 #define LOWORDER_UINT64(pos) ((PHYSFS_uint32) (pos & 0xFFFFFFFF))
       
    32 #define HIGHORDER_UINT64(pos) ((PHYSFS_uint32) ((pos >> 32) & 0xFFFFFFFF))
       
    33 
       
    34 /*
       
    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
       
    37  *  work as desired.
       
    38  */
       
    39 #define PHYSFS_INVALID_SET_FILE_POINTER  0xFFFFFFFF
       
    40 
       
    41 /* just in case... */
       
    42 #define PHYSFS_INVALID_FILE_ATTRIBUTES   0xFFFFFFFF
       
    43 
       
    44 /* Not defined before the Vista SDK. */
       
    45 #define PHYSFS_IO_REPARSE_TAG_SYMLINK    0xA000000C
       
    46 
       
    47 
       
    48 #define UTF8_TO_UNICODE_STACK_MACRO(w_assignto, str) { \
       
    49     if (str == NULL) \
       
    50         w_assignto = NULL; \
       
    51     else { \
       
    52         const PHYSFS_uint64 len = (PHYSFS_uint64) ((strlen(str) + 1) * 2); \
       
    53         w_assignto = (WCHAR *) __PHYSFS_smallAlloc(len); \
       
    54         if (w_assignto != NULL) \
       
    55             PHYSFS_utf8ToUtf16(str, (PHYSFS_uint16 *) w_assignto, len); \
       
    56     } \
       
    57 } \
       
    58 
       
    59 /* Note this counts WCHARs, not codepoints! */
       
    60 static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
       
    61 {
       
    62     PHYSFS_uint64 len = 0;
       
    63     while (*(wstr++))
       
    64         len++;
       
    65     return len;
       
    66 } /* wStrLen */
       
    67 
       
    68 static char *unicodeToUtf8Heap(const WCHAR *w_str)
       
    69 {
       
    70     char *retval = NULL;
       
    71     if (w_str != NULL)
       
    72     {
       
    73         void *ptr = NULL;
       
    74         const PHYSFS_uint64 len = (wStrLen(w_str) * 4) + 1;
       
    75         retval = allocator.Malloc(len);
       
    76         BAIL_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
       
    77         PHYSFS_utf8FromUtf16((const PHYSFS_uint16 *) w_str, retval, len);
       
    78         ptr = allocator.Realloc(retval, strlen(retval) + 1); /* shrink. */
       
    79         if (ptr != NULL)
       
    80             retval = (char *) ptr;
       
    81     } /* if */
       
    82     return retval;
       
    83 } /* unicodeToUtf8Heap */
       
    84 
       
    85 /* !!! FIXME: do we really need readonly? If not, do we need this struct? */
       
    86 typedef struct
       
    87 {
       
    88     HANDLE handle;
       
    89     int readonly;
       
    90 } WinApiFile;
       
    91 
       
    92 static HANDLE detectCDThreadHandle = NULL;
       
    93 static HWND detectCDHwnd = 0;
       
    94 static volatile int initialDiscDetectionComplete = 0;
       
    95 static volatile DWORD drivesWithMediaBitmap = 0;
       
    96 
       
    97 
       
    98 static PHYSFS_ErrorCode errcodeFromWinApiError(const DWORD err)
       
    99 {
       
   100     /*
       
   101      * win32 error codes are sort of a tricky thing; Microsoft intentionally
       
   102      *  doesn't list which ones a given API might trigger, there are several
       
   103      *  with overlapping and unclear meanings...and there's 16 thousand of
       
   104      *  them in Windows 7. It looks like the ones we care about are in the
       
   105      *  first 500, but I can't say this list is perfect; we might miss
       
   106      *  important values or misinterpret others.
       
   107      *
       
   108      * Don't treat this list as anything other than a work in progress.
       
   109      */
       
   110     switch (err)
       
   111     {
       
   112         case ERROR_SUCCESS: return PHYSFS_ERR_OK;
       
   113         case ERROR_ACCESS_DENIED: return PHYSFS_ERR_PERMISSION;
       
   114         case ERROR_NETWORK_ACCESS_DENIED: return PHYSFS_ERR_PERMISSION;
       
   115         case ERROR_NOT_READY: return PHYSFS_ERR_IO;
       
   116         case ERROR_CRC: return PHYSFS_ERR_IO;
       
   117         case ERROR_SEEK: return PHYSFS_ERR_IO;
       
   118         case ERROR_SECTOR_NOT_FOUND: return PHYSFS_ERR_IO;
       
   119         case ERROR_NOT_DOS_DISK: return PHYSFS_ERR_IO;
       
   120         case ERROR_WRITE_FAULT: return PHYSFS_ERR_IO;
       
   121         case ERROR_READ_FAULT: return PHYSFS_ERR_IO;
       
   122         case ERROR_DEV_NOT_EXIST: return PHYSFS_ERR_IO;
       
   123         /* !!! FIXME: ?? case ELOOP: return PHYSFS_ERR_SYMLINK_LOOP; */
       
   124         case ERROR_BUFFER_OVERFLOW: return PHYSFS_ERR_BAD_FILENAME;
       
   125         case ERROR_INVALID_NAME: return PHYSFS_ERR_BAD_FILENAME;
       
   126         case ERROR_BAD_PATHNAME: return PHYSFS_ERR_BAD_FILENAME;
       
   127         case ERROR_DIRECTORY: return PHYSFS_ERR_BAD_FILENAME;
       
   128         case ERROR_FILE_NOT_FOUND: return PHYSFS_ERR_NOT_FOUND;
       
   129         case ERROR_PATH_NOT_FOUND: return PHYSFS_ERR_NOT_FOUND;
       
   130         case ERROR_DELETE_PENDING: return PHYSFS_ERR_NOT_FOUND;
       
   131         case ERROR_INVALID_DRIVE: return PHYSFS_ERR_NOT_FOUND;
       
   132         case ERROR_HANDLE_DISK_FULL: return PHYSFS_ERR_NO_SPACE;
       
   133         case ERROR_DISK_FULL: return PHYSFS_ERR_NO_SPACE;
       
   134         /* !!! FIXME: ?? case ENOTDIR: return PHYSFS_ERR_NOT_FOUND; */
       
   135         /* !!! FIXME: ?? case EISDIR: return PHYSFS_ERR_NOT_A_FILE; */
       
   136         case ERROR_WRITE_PROTECT: return PHYSFS_ERR_READ_ONLY;
       
   137         case ERROR_LOCK_VIOLATION: return PHYSFS_ERR_BUSY;
       
   138         case ERROR_SHARING_VIOLATION: return PHYSFS_ERR_BUSY;
       
   139         case ERROR_CURRENT_DIRECTORY: return PHYSFS_ERR_BUSY;
       
   140         case ERROR_DRIVE_LOCKED: return PHYSFS_ERR_BUSY;
       
   141         case ERROR_PATH_BUSY: return PHYSFS_ERR_BUSY;
       
   142         case ERROR_BUSY: return PHYSFS_ERR_BUSY;
       
   143         case ERROR_NOT_ENOUGH_MEMORY: return PHYSFS_ERR_OUT_OF_MEMORY;
       
   144         case ERROR_OUTOFMEMORY: return PHYSFS_ERR_OUT_OF_MEMORY;
       
   145         case ERROR_DIR_NOT_EMPTY: return PHYSFS_ERR_DIR_NOT_EMPTY;
       
   146         default: return PHYSFS_ERR_OS_ERROR;
       
   147     } /* switch */
       
   148 } /* errcodeFromWinApiError */
       
   149 
       
   150 static inline PHYSFS_ErrorCode errcodeFromWinApi(void)
       
   151 {
       
   152     return errcodeFromWinApiError(GetLastError());
       
   153 } /* errcodeFromWinApi */
       
   154 
       
   155 
       
   156 typedef BOOL (WINAPI *fnSTEM)(DWORD, LPDWORD b);
       
   157 
       
   158 static DWORD pollDiscDrives(void)
       
   159 {
       
   160     /* Try to use SetThreadErrorMode(), which showed up in Windows 7. */
       
   161     HANDLE lib = LoadLibraryA("kernel32.dll");
       
   162     fnSTEM stem = NULL;
       
   163     char drive[4] = { 'x', ':', '\\', '\0' };
       
   164     DWORD oldErrorMode = 0;
       
   165     DWORD drives = 0;
       
   166     DWORD i;
       
   167 
       
   168     if (lib)
       
   169         stem = (fnSTEM) GetProcAddress(lib, "SetThreadErrorMode");
       
   170 
       
   171     if (stem)
       
   172         stem(SEM_FAILCRITICALERRORS, &oldErrorMode);
       
   173     else
       
   174         oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
       
   175     
       
   176     /* Do detection. This may block if a disc is spinning up. */
       
   177     for (i = 'A'; i <= 'Z'; i++)
       
   178     {
       
   179         DWORD tmp = 0;
       
   180         drive[0] = (char) i;
       
   181         if (GetDriveTypeA(drive) != DRIVE_CDROM)
       
   182             continue;
       
   183 
       
   184         /* If this function succeeds, there's media in the drive */
       
   185         if (GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0))
       
   186             drives |= (1 << (i - 'A'));
       
   187     } /* for */
       
   188 
       
   189     if (stem)
       
   190         stem(oldErrorMode, NULL);
       
   191     else
       
   192         SetErrorMode(oldErrorMode);
       
   193 
       
   194     if (lib)
       
   195         FreeLibrary(lib);
       
   196 
       
   197     return drives;
       
   198 } /* pollDiscDrives */
       
   199 
       
   200 
       
   201 static LRESULT CALLBACK detectCDWndProc(HWND hwnd, UINT msg,
       
   202                                         WPARAM wp, LPARAM lparam)
       
   203 {
       
   204     PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR) lparam;
       
   205     PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME) lparam;
       
   206     const int removed = (wp == DBT_DEVICEREMOVECOMPLETE);
       
   207 
       
   208     if (msg == WM_DESTROY)
       
   209         return 0;
       
   210     else if ((msg != WM_DEVICECHANGE) ||
       
   211              ((wp != DBT_DEVICEARRIVAL) && (wp != DBT_DEVICEREMOVECOMPLETE)) ||
       
   212              (lpdb->dbch_devicetype != DBT_DEVTYP_VOLUME) ||
       
   213              ((lpdbv->dbcv_flags & DBTF_MEDIA) == 0))
       
   214     {
       
   215         return DefWindowProcW(hwnd, msg, wp, lparam);
       
   216     } /* else if */
       
   217 
       
   218     if (removed)
       
   219         drivesWithMediaBitmap &= ~lpdbv->dbcv_unitmask;
       
   220     else
       
   221         drivesWithMediaBitmap |= lpdbv->dbcv_unitmask;
       
   222 
       
   223     return TRUE;
       
   224 } /* detectCDWndProc */
       
   225 
       
   226 
       
   227 static DWORD WINAPI detectCDThread(LPVOID lpParameter)
       
   228 {
       
   229     const char *classname = "PhysicsFSDetectCDCatcher";
       
   230     const char *winname = "PhysicsFSDetectCDMsgWindow";
       
   231     HINSTANCE hInstance = GetModuleHandleW(NULL);
       
   232     ATOM class_atom = 0;
       
   233     WNDCLASSEXA wce;
       
   234     MSG msg;
       
   235 
       
   236     memset(&wce, '\0', sizeof (wce));
       
   237     wce.cbSize = sizeof (wce);
       
   238     wce.lpfnWndProc = detectCDWndProc;
       
   239     wce.lpszClassName = classname;
       
   240     wce.hInstance = hInstance;
       
   241     class_atom = RegisterClassExA(&wce);
       
   242     if (class_atom == 0)
       
   243     {
       
   244         initialDiscDetectionComplete = 1;  /* let main thread go on. */
       
   245         return 0;
       
   246     } /* if */
       
   247 
       
   248     detectCDHwnd = CreateWindowExA(0, classname, winname, WS_OVERLAPPEDWINDOW,
       
   249                         CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
       
   250                         CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL);
       
   251 
       
   252     if (detectCDHwnd == NULL)
       
   253     {
       
   254         initialDiscDetectionComplete = 1;  /* let main thread go on. */
       
   255         UnregisterClassA(classname, hInstance);
       
   256         return 0;
       
   257     } /* if */
       
   258 
       
   259     /* We'll get events when discs come and go from now on. */
       
   260 
       
   261     /* Do initial detection, possibly blocking awhile... */
       
   262     drivesWithMediaBitmap = pollDiscDrives();
       
   263     initialDiscDetectionComplete = 1;  /* let main thread go on. */
       
   264 
       
   265     do
       
   266     {
       
   267         const BOOL rc = GetMessageW(&msg, detectCDHwnd, 0, 0);
       
   268         if ((rc == 0) || (rc == -1))
       
   269             break;  /* don't care if WM_QUIT or error break this loop. */
       
   270         TranslateMessage(&msg);
       
   271         DispatchMessageW(&msg);
       
   272     } while (1);
       
   273 
       
   274     /* we've been asked to quit. */
       
   275     DestroyWindow(detectCDHwnd);
       
   276 
       
   277     do
       
   278     {
       
   279         const BOOL rc = GetMessage(&msg, detectCDHwnd, 0, 0);
       
   280         if ((rc == 0) || (rc == -1))
       
   281             break;
       
   282         TranslateMessage(&msg);
       
   283         DispatchMessageW(&msg);
       
   284     } while (1);
       
   285 
       
   286     UnregisterClassA(classname, hInstance);
       
   287 
       
   288     return 0;
       
   289 } /* detectCDThread */
       
   290 
       
   291 
       
   292 void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
       
   293 {
       
   294     char drive_str[4] = { 'x', ':', '\\', '\0' };
       
   295     DWORD drives = 0;
       
   296     DWORD i;
       
   297 
       
   298     /*
       
   299      * If you poll a drive while a user is inserting a disc, the OS will
       
   300      *  block this thread until the drive has spun up. So we swallow the risk
       
   301      *  once for initial detection, and spin a thread that will get device
       
   302      *  events thereafter, for apps that use this interface to poll for
       
   303      *  disc insertion.
       
   304      */
       
   305     if (!detectCDThreadHandle)
       
   306     {
       
   307         initialDiscDetectionComplete = 0;
       
   308         detectCDThreadHandle = CreateThread(NULL,0,detectCDThread,NULL,0,NULL);
       
   309         if (detectCDThreadHandle == NULL)
       
   310             return;  /* oh well. */
       
   311 
       
   312         while (!initialDiscDetectionComplete)
       
   313             Sleep(50);
       
   314     } /* if */
       
   315 
       
   316     drives = drivesWithMediaBitmap; /* whatever the thread has seen, we take. */
       
   317     for (i = 'A'; i <= 'Z'; i++)
       
   318     {
       
   319         if (drives & (1 << (i - 'A')))
       
   320         {
       
   321             drive_str[0] = (char) i;
       
   322             cb(data, drive_str);
       
   323         } /* if */
       
   324     } /* for */
       
   325 } /* __PHYSFS_platformDetectAvailableCDs */
       
   326 
       
   327 
       
   328 char *__PHYSFS_platformCalcBaseDir(const char *argv0)
       
   329 {
       
   330     DWORD buflen = 64;
       
   331     LPWSTR modpath = NULL;
       
   332     char *retval = NULL;
       
   333 
       
   334     while (1)
       
   335     {
       
   336         DWORD rc;
       
   337         void *ptr;
       
   338 
       
   339         if ( (ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) == NULL )
       
   340         {
       
   341             allocator.Free(modpath);
       
   342             BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
       
   343         } /* if */
       
   344         modpath = (LPWSTR) ptr;
       
   345 
       
   346         rc = GetModuleFileNameW(NULL, modpath, buflen);
       
   347         if (rc == 0)
       
   348         {
       
   349             allocator.Free(modpath);
       
   350             BAIL_MACRO(errcodeFromWinApi(), NULL);
       
   351         } /* if */
       
   352 
       
   353         if (rc < buflen)
       
   354         {
       
   355             buflen = rc;
       
   356             break;
       
   357         } /* if */
       
   358 
       
   359         buflen *= 2;
       
   360     } /* while */
       
   361 
       
   362     if (buflen > 0)  /* just in case... */
       
   363     {
       
   364         WCHAR *ptr = (modpath + buflen) - 1;
       
   365         while (ptr != modpath)
       
   366         {
       
   367             if (*ptr == '\\')
       
   368                 break;
       
   369             ptr--;
       
   370         } /* while */
       
   371 
       
   372         if ((ptr == modpath) && (*ptr != '\\'))
       
   373             PHYSFS_setErrorCode(PHYSFS_ERR_OTHER_ERROR);  /* oh well. */
       
   374         else
       
   375         {
       
   376             *(ptr+1) = '\0';  /* chop off filename. */
       
   377             retval = unicodeToUtf8Heap(modpath);
       
   378         } /* else */
       
   379     } /* else */
       
   380     allocator.Free(modpath);
       
   381 
       
   382     return retval;   /* w00t. */
       
   383 } /* __PHYSFS_platformCalcBaseDir */
       
   384 
       
   385 
       
   386 char *__PHYSFS_platformCalcPrefDir(const char *org, const char *app)
       
   387 {
       
   388     /*
       
   389      * Vista and later has a new API for this, but SHGetFolderPath works there,
       
   390      *  and apparently just wraps the new API. This is the new way to do it:
       
   391      *
       
   392      *     SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE,
       
   393      *                          NULL, &wszPath);
       
   394      */
       
   395 
       
   396     WCHAR path[MAX_PATH];
       
   397     char *utf8 = NULL;
       
   398     size_t len = 0;
       
   399     char *retval = NULL;
       
   400 
       
   401     if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE,
       
   402                                    NULL, 0, path)))
       
   403         BAIL_MACRO(PHYSFS_ERR_OS_ERROR, NULL);
       
   404 
       
   405     utf8 = unicodeToUtf8Heap(path);
       
   406     BAIL_IF_MACRO(!utf8, ERRPASS, NULL);
       
   407     len = strlen(utf8) + strlen(org) + strlen(app) + 4;
       
   408     retval = allocator.Malloc(len);
       
   409     if (!retval)
       
   410     {
       
   411         allocator.Free(utf8);
       
   412         BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
       
   413     } /* if */
       
   414 
       
   415     sprintf(retval, "%s\\%s\\%s\\", utf8, org, app);
       
   416     allocator.Free(utf8);
       
   417     return retval;
       
   418 } /* __PHYSFS_platformCalcPrefDir */
       
   419 
       
   420 
       
   421 char *__PHYSFS_platformCalcUserDir(void)
       
   422 {
       
   423     typedef BOOL (WINAPI *fnGetUserProfDirW)(HANDLE, LPWSTR, LPDWORD);
       
   424     fnGetUserProfDirW pGetDir = NULL;
       
   425     HANDLE lib = NULL;
       
   426     HANDLE accessToken = NULL;       /* Security handle to process */
       
   427     char *retval = NULL;
       
   428 
       
   429     lib = LoadLibraryA("userenv.dll");
       
   430     BAIL_IF_MACRO(!lib, errcodeFromWinApi(), NULL);
       
   431     pGetDir=(fnGetUserProfDirW) GetProcAddress(lib,"GetUserProfileDirectoryW");
       
   432     GOTO_IF_MACRO(!pGetDir, errcodeFromWinApi(), done);
       
   433 
       
   434     if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &accessToken))
       
   435         GOTO_MACRO(errcodeFromWinApi(), done);
       
   436     else
       
   437     {
       
   438         DWORD psize = 1;
       
   439         WCHAR dummy = 0;
       
   440         LPWSTR wstr = NULL;
       
   441         BOOL rc = 0;
       
   442 
       
   443         /*
       
   444          * Should fail. Will write the size of the profile path in
       
   445          *  psize. Also note that the second parameter can't be
       
   446          *  NULL or the function fails.
       
   447          */
       
   448     	rc = pGetDir(accessToken, &dummy, &psize);
       
   449         assert(!rc);  /* !!! FIXME: handle this gracefully. */
       
   450         (void) rc;
       
   451 
       
   452         /* Allocate memory for the profile directory */
       
   453         wstr = (LPWSTR) __PHYSFS_smallAlloc((psize + 1) * sizeof (WCHAR));
       
   454         if (wstr != NULL)
       
   455         {
       
   456             if (pGetDir(accessToken, wstr, &psize))
       
   457             {
       
   458                 /* Make sure it ends in a dirsep. We allocated +1 for this. */
       
   459                 if (wstr[psize - 2] != '\\')
       
   460                 {
       
   461                     wstr[psize - 1] = '\\';
       
   462                     wstr[psize - 0] = '\0';
       
   463                 } /* if */
       
   464                 retval = unicodeToUtf8Heap(wstr);
       
   465             } /* if */
       
   466             __PHYSFS_smallFree(wstr);
       
   467         } /* if */
       
   468 
       
   469         CloseHandle(accessToken);
       
   470     } /* if */
       
   471 
       
   472 done:
       
   473     FreeLibrary(lib);
       
   474     return retval;  /* We made it: hit the showers. */
       
   475 } /* __PHYSFS_platformCalcUserDir */
       
   476 
       
   477 
       
   478 void *__PHYSFS_platformGetThreadID(void)
       
   479 {
       
   480     return ( (void *) ((size_t) GetCurrentThreadId()) );
       
   481 } /* __PHYSFS_platformGetThreadID */
       
   482 
       
   483 void __PHYSFS_platformEnumerateFiles(const char *dirname,
       
   484                                      PHYSFS_EnumFilesCallback callback,
       
   485                                      const char *origdir,
       
   486                                      void *callbackdata)
       
   487 {
       
   488     HANDLE dir = INVALID_HANDLE_VALUE;
       
   489     WIN32_FIND_DATAW entw;
       
   490     size_t len = strlen(dirname);
       
   491     char *searchPath = NULL;
       
   492     WCHAR *wSearchPath = NULL;
       
   493 
       
   494     /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
       
   495     searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
       
   496     if (searchPath == NULL)
       
   497         return;
       
   498 
       
   499     /* Copy current dirname */
       
   500     strcpy(searchPath, dirname);
       
   501 
       
   502     /* if there's no '\\' at the end of the path, stick one in there. */
       
   503     if (searchPath[len - 1] != '\\')
       
   504     {
       
   505         searchPath[len++] = '\\';
       
   506         searchPath[len] = '\0';
       
   507     } /* if */
       
   508 
       
   509     /* Append the "*" to the end of the string */
       
   510     strcat(searchPath, "*");
       
   511 
       
   512     UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
       
   513     if (!wSearchPath)
       
   514         return;  /* oh well. */
       
   515 
       
   516     dir = FindFirstFileW(wSearchPath, &entw);
       
   517 
       
   518     __PHYSFS_smallFree(wSearchPath);
       
   519     __PHYSFS_smallFree(searchPath);
       
   520     if (dir == INVALID_HANDLE_VALUE)
       
   521         return;
       
   522 
       
   523     do
       
   524     {
       
   525         const WCHAR *fn = entw.cFileName;
       
   526         char *utf8;
       
   527 
       
   528         if ((fn[0] == '.') && (fn[1] == '\0'))
       
   529             continue;
       
   530         if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
       
   531             continue;
       
   532 
       
   533         utf8 = unicodeToUtf8Heap(fn);
       
   534         if (utf8 != NULL)
       
   535         {
       
   536             callback(callbackdata, origdir, utf8);
       
   537             allocator.Free(utf8);
       
   538         } /* if */
       
   539     } while (FindNextFileW(dir, &entw) != 0);
       
   540 
       
   541     FindClose(dir);
       
   542 } /* __PHYSFS_platformEnumerateFiles */
       
   543 
       
   544 
       
   545 int __PHYSFS_platformMkDir(const char *path)
       
   546 {
       
   547     WCHAR *wpath;
       
   548     DWORD rc;
       
   549     UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
       
   550     rc = CreateDirectoryW(wpath, NULL);
       
   551     __PHYSFS_smallFree(wpath);
       
   552     BAIL_IF_MACRO(rc == 0, errcodeFromWinApi(), 0);
       
   553     return 1;
       
   554 } /* __PHYSFS_platformMkDir */
       
   555 
       
   556 
       
   557 int __PHYSFS_platformInit(void)
       
   558 {
       
   559     return 1;  /* It's all good */
       
   560 } /* __PHYSFS_platformInit */
       
   561 
       
   562 
       
   563 int __PHYSFS_platformDeinit(void)
       
   564 {
       
   565     if (detectCDThreadHandle)
       
   566     {
       
   567         if (detectCDHwnd)
       
   568             PostMessageW(detectCDHwnd, WM_QUIT, 0, 0);
       
   569         CloseHandle(detectCDThreadHandle);
       
   570         detectCDThreadHandle = NULL;
       
   571         initialDiscDetectionComplete = 0;
       
   572         drivesWithMediaBitmap = 0;
       
   573     } /* if */
       
   574 
       
   575     return 1; /* It's all good */
       
   576 } /* __PHYSFS_platformDeinit */
       
   577 
       
   578 
       
   579 static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
       
   580 {
       
   581     HANDLE fileh;
       
   582     WinApiFile *retval;
       
   583     WCHAR *wfname;
       
   584 
       
   585     UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
       
   586     BAIL_IF_MACRO(!wfname, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
       
   587     fileh = CreateFileW(wfname, mode, FILE_SHARE_READ | FILE_SHARE_WRITE,
       
   588                              NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
       
   589     __PHYSFS_smallFree(wfname);
       
   590 
       
   591     BAIL_IF_MACRO(fileh == INVALID_HANDLE_VALUE,errcodeFromWinApi(), NULL);
       
   592 
       
   593     retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
       
   594     if (!retval)
       
   595     {
       
   596         CloseHandle(fileh);
       
   597         BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
       
   598     } /* if */
       
   599 
       
   600     retval->readonly = rdonly;
       
   601     retval->handle = fileh;
       
   602     return retval;
       
   603 } /* doOpen */
       
   604 
       
   605 
       
   606 void *__PHYSFS_platformOpenRead(const char *filename)
       
   607 {
       
   608     return doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1);
       
   609 } /* __PHYSFS_platformOpenRead */
       
   610 
       
   611 
       
   612 void *__PHYSFS_platformOpenWrite(const char *filename)
       
   613 {
       
   614     return doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0);
       
   615 } /* __PHYSFS_platformOpenWrite */
       
   616 
       
   617 
       
   618 void *__PHYSFS_platformOpenAppend(const char *filename)
       
   619 {
       
   620     void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
       
   621     if (retval != NULL)
       
   622     {
       
   623         HANDLE h = ((WinApiFile *) retval)->handle;
       
   624         DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
       
   625         if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
       
   626         {
       
   627             const PHYSFS_ErrorCode err = errcodeFromWinApi();
       
   628             CloseHandle(h);
       
   629             allocator.Free(retval);
       
   630             BAIL_MACRO(err, NULL);
       
   631         } /* if */
       
   632     } /* if */
       
   633 
       
   634     return retval;
       
   635 } /* __PHYSFS_platformOpenAppend */
       
   636 
       
   637 
       
   638 PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buf, PHYSFS_uint64 len)
       
   639 {
       
   640     HANDLE Handle = ((WinApiFile *) opaque)->handle;
       
   641     PHYSFS_sint64 totalRead = 0;
       
   642 
       
   643     if (!__PHYSFS_ui64FitsAddressSpace(len))
       
   644         BAIL_MACRO(PHYSFS_ERR_INVALID_ARGUMENT, -1);
       
   645 
       
   646     while (len > 0)
       
   647     {
       
   648         const DWORD thislen = (len > 0xFFFFFFFF) ? 0xFFFFFFFF : (DWORD) len;
       
   649         DWORD numRead = 0;
       
   650         if (!ReadFile(Handle, buf, thislen, &numRead, NULL))
       
   651             BAIL_MACRO(errcodeFromWinApi(), -1);
       
   652         len -= (PHYSFS_uint64) numRead;
       
   653         totalRead += (PHYSFS_sint64) numRead;
       
   654         if (numRead != thislen)
       
   655             break;
       
   656     } /* while */
       
   657 
       
   658     return totalRead;
       
   659 } /* __PHYSFS_platformRead */
       
   660 
       
   661 
       
   662 PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
       
   663                                      PHYSFS_uint64 len)
       
   664 {
       
   665     HANDLE Handle = ((WinApiFile *) opaque)->handle;
       
   666     PHYSFS_sint64 totalWritten = 0;
       
   667 
       
   668     if (!__PHYSFS_ui64FitsAddressSpace(len))
       
   669         BAIL_MACRO(PHYSFS_ERR_INVALID_ARGUMENT, -1);
       
   670 
       
   671     while (len > 0)
       
   672     {
       
   673         const DWORD thislen = (len > 0xFFFFFFFF) ? 0xFFFFFFFF : (DWORD) len;
       
   674         DWORD numWritten = 0;
       
   675         if (!WriteFile(Handle, buffer, thislen, &numWritten, NULL))
       
   676             BAIL_MACRO(errcodeFromWinApi(), -1);
       
   677         len -= (PHYSFS_uint64) numWritten;
       
   678         totalWritten += (PHYSFS_sint64) numWritten;
       
   679         if (numWritten != thislen)
       
   680             break;
       
   681     } /* while */
       
   682 
       
   683     return totalWritten;
       
   684 } /* __PHYSFS_platformWrite */
       
   685 
       
   686 
       
   687 int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
       
   688 {
       
   689     HANDLE Handle = ((WinApiFile *) opaque)->handle;
       
   690     LONG HighOrderPos;
       
   691     PLONG pHighOrderPos;
       
   692     DWORD rc;
       
   693 
       
   694     /* Get the high order 32-bits of the position */
       
   695     HighOrderPos = HIGHORDER_UINT64(pos);
       
   696 
       
   697     /*
       
   698      * MSDN: "If you do not need the high-order 32 bits, this
       
   699      *         pointer must be set to NULL."
       
   700      */
       
   701     pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
       
   702 
       
   703     /* Move pointer "pos" count from start of file */
       
   704     rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
       
   705                         pHighOrderPos, FILE_BEGIN);
       
   706 
       
   707     if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
       
   708          (GetLastError() != NO_ERROR) )
       
   709     {
       
   710         BAIL_MACRO(errcodeFromWinApi(), 0);
       
   711     } /* if */
       
   712     
       
   713     return 1;  /* No error occured */
       
   714 } /* __PHYSFS_platformSeek */
       
   715 
       
   716 
       
   717 PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
       
   718 {
       
   719     HANDLE Handle = ((WinApiFile *) opaque)->handle;
       
   720     LONG HighPos = 0;
       
   721     DWORD LowPos;
       
   722     PHYSFS_sint64 retval;
       
   723 
       
   724     /* Get current position */
       
   725     LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
       
   726     if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
       
   727          (GetLastError() != NO_ERROR) )
       
   728     {
       
   729         BAIL_MACRO(errcodeFromWinApi(), -1);
       
   730     } /* if */
       
   731     else
       
   732     {
       
   733         /* Combine the high/low order to create the 64-bit position value */
       
   734         retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
       
   735         assert(retval >= 0);
       
   736     } /* else */
       
   737 
       
   738     return retval;
       
   739 } /* __PHYSFS_platformTell */
       
   740 
       
   741 
       
   742 PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
       
   743 {
       
   744     HANDLE Handle = ((WinApiFile *) opaque)->handle;
       
   745     DWORD SizeHigh;
       
   746     DWORD SizeLow;
       
   747     PHYSFS_sint64 retval;
       
   748 
       
   749     SizeLow = GetFileSize(Handle, &SizeHigh);
       
   750     if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
       
   751          (GetLastError() != NO_ERROR) )
       
   752     {
       
   753         BAIL_MACRO(errcodeFromWinApi(), -1);
       
   754     } /* if */
       
   755     else
       
   756     {
       
   757         /* Combine the high/low order to create the 64-bit position value */
       
   758         retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
       
   759         assert(retval >= 0);
       
   760     } /* else */
       
   761 
       
   762     return retval;
       
   763 } /* __PHYSFS_platformFileLength */
       
   764 
       
   765 
       
   766 int __PHYSFS_platformFlush(void *opaque)
       
   767 {
       
   768     WinApiFile *fh = ((WinApiFile *) opaque);
       
   769     if (!fh->readonly)
       
   770         BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), errcodeFromWinApi(), 0);
       
   771 
       
   772     return 1;
       
   773 } /* __PHYSFS_platformFlush */
       
   774 
       
   775 
       
   776 void __PHYSFS_platformClose(void *opaque)
       
   777 {
       
   778     HANDLE Handle = ((WinApiFile *) opaque)->handle;
       
   779     (void) CloseHandle(Handle); /* ignore errors. You should have flushed! */
       
   780     allocator.Free(opaque);
       
   781 } /* __PHYSFS_platformClose */
       
   782 
       
   783 
       
   784 static int doPlatformDelete(LPWSTR wpath)
       
   785 {
       
   786     const int isdir = (GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY);
       
   787     const BOOL rc = (isdir) ? RemoveDirectoryW(wpath) : DeleteFileW(wpath);
       
   788     BAIL_IF_MACRO(!rc, errcodeFromWinApi(), 0);
       
   789     return 1;   /* if you made it here, it worked. */
       
   790 } /* doPlatformDelete */
       
   791 
       
   792 
       
   793 int __PHYSFS_platformDelete(const char *path)
       
   794 {
       
   795     int retval = 0;
       
   796     LPWSTR wpath = NULL;
       
   797     UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
       
   798     BAIL_IF_MACRO(!wpath, PHYSFS_ERR_OUT_OF_MEMORY, 0);
       
   799     retval = doPlatformDelete(wpath);
       
   800     __PHYSFS_smallFree(wpath);
       
   801     return retval;
       
   802 } /* __PHYSFS_platformDelete */
       
   803 
       
   804 
       
   805 void *__PHYSFS_platformCreateMutex(void)
       
   806 {
       
   807     LPCRITICAL_SECTION lpcs;
       
   808     lpcs = (LPCRITICAL_SECTION) allocator.Malloc(sizeof (CRITICAL_SECTION));
       
   809     BAIL_IF_MACRO(!lpcs, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
       
   810     InitializeCriticalSection(lpcs);
       
   811     return lpcs;
       
   812 } /* __PHYSFS_platformCreateMutex */
       
   813 
       
   814 
       
   815 void __PHYSFS_platformDestroyMutex(void *mutex)
       
   816 {
       
   817     DeleteCriticalSection((LPCRITICAL_SECTION) mutex);
       
   818     allocator.Free(mutex);
       
   819 } /* __PHYSFS_platformDestroyMutex */
       
   820 
       
   821 
       
   822 int __PHYSFS_platformGrabMutex(void *mutex)
       
   823 {
       
   824     EnterCriticalSection((LPCRITICAL_SECTION) mutex);
       
   825     return 1;
       
   826 } /* __PHYSFS_platformGrabMutex */
       
   827 
       
   828 
       
   829 void __PHYSFS_platformReleaseMutex(void *mutex)
       
   830 {
       
   831     LeaveCriticalSection((LPCRITICAL_SECTION) mutex);
       
   832 } /* __PHYSFS_platformReleaseMutex */
       
   833 
       
   834 
       
   835 static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
       
   836 {
       
   837     SYSTEMTIME st_utc;
       
   838     SYSTEMTIME st_localtz;
       
   839     TIME_ZONE_INFORMATION tzi;
       
   840     DWORD tzid;
       
   841     PHYSFS_sint64 retval;
       
   842     struct tm tm;
       
   843     BOOL rc;
       
   844 
       
   845     BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), errcodeFromWinApi(), -1);
       
   846     tzid = GetTimeZoneInformation(&tzi);
       
   847     BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, errcodeFromWinApi(), -1);
       
   848     rc = SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz);
       
   849     BAIL_IF_MACRO(!rc, errcodeFromWinApi(), -1);
       
   850 
       
   851     /* Convert to a format that mktime() can grok... */
       
   852     tm.tm_sec = st_localtz.wSecond;
       
   853     tm.tm_min = st_localtz.wMinute;
       
   854     tm.tm_hour = st_localtz.wHour;
       
   855     tm.tm_mday = st_localtz.wDay;
       
   856     tm.tm_mon = st_localtz.wMonth - 1;
       
   857     tm.tm_year = st_localtz.wYear - 1900;
       
   858     tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
       
   859     tm.tm_yday = -1;
       
   860     tm.tm_isdst = -1;
       
   861 
       
   862     /* Convert to a format PhysicsFS can grok... */
       
   863     retval = (PHYSFS_sint64) mktime(&tm);
       
   864     BAIL_IF_MACRO(retval == -1, PHYSFS_ERR_OS_ERROR, -1);
       
   865     return retval;
       
   866 } /* FileTimeToPhysfsTime */
       
   867 
       
   868 
       
   869 int __PHYSFS_platformStat(const char *filename, PHYSFS_Stat *st)
       
   870 {
       
   871     WIN32_FILE_ATTRIBUTE_DATA winstat;
       
   872     WCHAR *wstr = NULL;
       
   873     DWORD err = 0;
       
   874     BOOL rc = 0;
       
   875 
       
   876     UTF8_TO_UNICODE_STACK_MACRO(wstr, filename);
       
   877     BAIL_IF_MACRO(!wstr, PHYSFS_ERR_OUT_OF_MEMORY, 0);
       
   878     rc = GetFileAttributesExW(wstr, GetFileExInfoStandard, &winstat);
       
   879     err = (!rc) ? GetLastError() : 0;
       
   880     __PHYSFS_smallFree(wstr);
       
   881     BAIL_IF_MACRO(!rc, errcodeFromWinApiError(err), 0);
       
   882 
       
   883     st->modtime = FileTimeToPhysfsTime(&winstat.ftLastWriteTime);
       
   884     st->accesstime = FileTimeToPhysfsTime(&winstat.ftLastAccessTime);
       
   885     st->createtime = FileTimeToPhysfsTime(&winstat.ftCreationTime);
       
   886 
       
   887     if(winstat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
       
   888     {
       
   889         st->filetype = PHYSFS_FILETYPE_DIRECTORY;
       
   890         st->filesize = 0;
       
   891     } /* if */
       
   892 
       
   893     else if(winstat.dwFileAttributes & (FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_DEVICE))
       
   894     {
       
   895         /* !!! FIXME: what are reparse points? */
       
   896         st->filetype = PHYSFS_FILETYPE_OTHER;
       
   897         /* !!! FIXME: don't rely on this */
       
   898         st->filesize = 0;
       
   899     } /* else if */
       
   900 
       
   901     /* !!! FIXME: check for symlinks on Vista. */
       
   902 
       
   903     else
       
   904     {
       
   905         st->filetype = PHYSFS_FILETYPE_REGULAR;
       
   906         st->filesize = (((PHYSFS_uint64) winstat.nFileSizeHigh) << 32) | winstat.nFileSizeLow;
       
   907     } /* else */
       
   908 
       
   909     st->readonly = ((winstat.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
       
   910 
       
   911     return 1;
       
   912 } /* __PHYSFS_platformStat */
       
   913 
       
   914 
       
   915 /* !!! FIXME: Don't use C runtime for allocators? */
       
   916 int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
       
   917 {
       
   918     return 0;  /* just use malloc() and friends. */
       
   919 } /* __PHYSFS_platformSetDefaultAllocator */
       
   920 
       
   921 #endif  /* PHYSFS_PLATFORM_WINDOWS */
       
   922 #endif  /* PHYSFS_PLATFORM_WINRT */
       
   923 
       
   924 /* end of windows.c ... */
       
   925 
       
   926