platform_windows.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. #define __PHYSICSFS_INTERNAL__
  9. #include "physfs_platforms.h"
  10. #ifdef PHYSFS_PLATFORM_WINDOWS
  11. /* Forcibly disable UNICODE macro, since we manage this ourselves. */
  12. #ifdef UNICODE
  13. #undef UNICODE
  14. #endif
  15. #define WIN32_LEAN_AND_MEAN 1
  16. #include <windows.h>
  17. #include <userenv.h>
  18. #include <errno.h>
  19. #include <ctype.h>
  20. #include <time.h>
  21. #include "physfs_internal.h"
  22. #define LOWORDER_UINT64(pos) ((PHYSFS_uint32) (pos & 0xFFFFFFFF))
  23. #define HIGHORDER_UINT64(pos) ((PHYSFS_uint32) ((pos >> 32) & 0xFFFFFFFF))
  24. /*
  25. * Users without the platform SDK don't have this defined. The original docs
  26. * for SetFilePointer() just said to compare with 0xFFFFFFFF, so this should
  27. * work as desired.
  28. */
  29. #define PHYSFS_INVALID_SET_FILE_POINTER 0xFFFFFFFF
  30. /* just in case... */
  31. #define PHYSFS_INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
  32. /* Not defined before the Vista SDK. */
  33. #define PHYSFS_IO_REPARSE_TAG_SYMLINK 0xA000000C
  34. #define UTF8_TO_UNICODE_STACK_MACRO(w_assignto, str) { \
  35. if (str == NULL) \
  36. w_assignto = NULL; \
  37. else { \
  38. const PHYSFS_uint64 len = (PHYSFS_uint64) ((strlen(str) + 1) * 2); \
  39. w_assignto = (WCHAR *) __PHYSFS_smallAlloc(len); \
  40. if (w_assignto != NULL) \
  41. PHYSFS_utf8ToUcs2(str, (PHYSFS_uint16 *) w_assignto, len); \
  42. } \
  43. } \
  44. #ifndef _MSC_VER
  45. #define _snprintf snprintf
  46. #endif
  47. /* !!! FIXME: this is wrong for UTF-16. */
  48. static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
  49. {
  50. PHYSFS_uint64 len = 0;
  51. while (*(wstr++))
  52. len++;
  53. return len;
  54. } /* wStrLen */
  55. static char *unicodeToUtf8Heap(const WCHAR *w_str)
  56. {
  57. char *retval = NULL;
  58. if (w_str != NULL)
  59. {
  60. void *ptr = NULL;
  61. const PHYSFS_uint64 len = (wStrLen(w_str) * 4) + 1;
  62. retval = allocator.Malloc(len);
  63. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  64. /* !!! FIXME: utf-16. */
  65. PHYSFS_utf8FromUcs2((const PHYSFS_uint16 *) w_str, retval, len);
  66. ptr = allocator.Realloc(retval, strlen(retval) + 1); /* shrink. */
  67. if (ptr != NULL)
  68. retval = (char *) ptr;
  69. } /* if */
  70. return retval;
  71. } /* unicodeToUtf8Heap */
  72. /* !!! FIXME: do we really need readonly? If not, do we need this struct? */
  73. typedef struct
  74. {
  75. HANDLE handle;
  76. int readonly;
  77. } WinApiFile;
  78. const char *__PHYSFS_platformDirSeparator = "\\";
  79. static char *userDir = NULL;
  80. static HANDLE libUserEnv = NULL;
  81. /*
  82. * Figure out what the last failing Windows API call was, and
  83. * generate a human-readable string for the error message.
  84. *
  85. * The return value is a static buffer that is overwritten with
  86. * each call to this function.
  87. */
  88. static const char *winApiStrErrorByNum(const DWORD err)
  89. {
  90. static char utf8buf[255];
  91. WCHAR msgbuf[255];
  92. WCHAR *ptr;
  93. DWORD rc = FormatMessageW(
  94. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  95. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  96. msgbuf, __PHYSFS_ARRAYLEN(msgbuf),
  97. NULL);
  98. if (rc == 0)
  99. msgbuf[0] = '\0'; /* oh well. */
  100. /* chop off newlines. */
  101. for (ptr = msgbuf; *ptr; ptr++)
  102. {
  103. if ((*ptr == '\n') || (*ptr == '\r'))
  104. {
  105. *ptr = '\0';
  106. break;
  107. } /* if */
  108. } /* for */
  109. /* may truncate, but oh well. */
  110. PHYSFS_utf8FromUcs2((PHYSFS_uint16 *) msgbuf, utf8buf, sizeof (utf8buf));
  111. return ((const char *) utf8buf);
  112. } /* winApiStrErrorByNum */
  113. static inline const char *winApiStrError(void)
  114. {
  115. return winApiStrErrorByNum(GetLastError());
  116. } /* winApiStrError */
  117. /*
  118. * On success, module-scope variable (userDir) will have a pointer to
  119. * a malloc()'d string of the user's profile dir, and a non-zero value is
  120. * returned. If we can't determine the profile dir, (userDir) will
  121. * be NULL, and zero is returned.
  122. */
  123. static int determineUserDir(void)
  124. {
  125. typedef BOOL (WINAPI *fnGetUserProfDirW)(HANDLE, LPWSTR, LPDWORD);
  126. fnGetUserProfDirW pGetDir = NULL;
  127. HANDLE accessToken = NULL; /* Security handle to process */
  128. if (userDir != NULL)
  129. return 1; /* already good to go. */
  130. pGetDir = (fnGetUserProfDirW)
  131. GetProcAddress(libUserEnv, "GetUserProfileDirectoryW");
  132. BAIL_IF_MACRO(pGetDir == NULL, winApiStrError(), 0);
  133. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &accessToken))
  134. BAIL_MACRO(winApiStrError(), 0);
  135. else
  136. {
  137. DWORD psize = 0;
  138. WCHAR dummy = 0;
  139. LPWSTR wstr = NULL;
  140. BOOL rc = 0;
  141. /*
  142. * Should fail. Will write the size of the profile path in
  143. * psize. Also note that the second parameter can't be
  144. * NULL or the function fails.
  145. */
  146. rc = pGetDir(accessToken, &dummy, &psize);
  147. assert(!rc); /* !!! FIXME: handle this gracefully. */
  148. (void) rc;
  149. /* Allocate memory for the profile directory */
  150. wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
  151. if (wstr != NULL)
  152. {
  153. if (pGetDir(accessToken, wstr, &psize))
  154. userDir = unicodeToUtf8Heap(wstr);
  155. __PHYSFS_smallFree(wstr);
  156. } /* if */
  157. CloseHandle(accessToken);
  158. } /* if */
  159. return 1; /* We made it: hit the showers. */
  160. } /* determineUserDir */
  161. static BOOL mediaInDrive(const char *drive)
  162. {
  163. UINT oldErrorMode;
  164. DWORD tmp;
  165. BOOL retval;
  166. /* Prevent windows warning message appearing when checking media size */
  167. /* !!! FIXME: Windows 7 offers SetThreadErrorMode(). */
  168. oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  169. /* If this function succeeds, there's media in the drive */
  170. retval = GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0);
  171. /* Revert back to old windows error handler */
  172. SetErrorMode(oldErrorMode);
  173. return retval;
  174. } /* mediaInDrive */
  175. /*
  176. * !!! FIXME: move this to a thread? This function hangs if you call it while
  177. * !!! FIXME: a drive is spinning up right after inserting a disc.
  178. */
  179. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  180. {
  181. /* !!! FIXME: Can CD drives be non-drive letter paths? */
  182. /* !!! FIXME: (so can they be Unicode paths?) */
  183. char drive_str[4] = "x:\\";
  184. char ch;
  185. for (ch = 'A'; ch <= 'Z'; ch++)
  186. {
  187. drive_str[0] = ch;
  188. if (GetDriveTypeA(drive_str) == DRIVE_CDROM && mediaInDrive(drive_str))
  189. cb(data, drive_str);
  190. } /* for */
  191. } /* __PHYSFS_platformDetectAvailableCDs */
  192. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  193. {
  194. DWORD buflen = 64;
  195. LPWSTR modpath = NULL;
  196. char *retval = NULL;
  197. while (1)
  198. {
  199. DWORD rc;
  200. void *ptr;
  201. if ( (ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) == NULL )
  202. {
  203. allocator.Free(modpath);
  204. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  205. } /* if */
  206. modpath = (LPWSTR) ptr;
  207. rc = GetModuleFileNameW(NULL, modpath, buflen);
  208. if (rc == 0)
  209. {
  210. allocator.Free(modpath);
  211. BAIL_MACRO(winApiStrError(), NULL);
  212. } /* if */
  213. if (rc < buflen)
  214. {
  215. buflen = rc;
  216. break;
  217. } /* if */
  218. buflen *= 2;
  219. } /* while */
  220. if (buflen > 0) /* just in case... */
  221. {
  222. WCHAR *ptr = (modpath + buflen) - 1;
  223. while (ptr != modpath)
  224. {
  225. if (*ptr == '\\')
  226. break;
  227. ptr--;
  228. } /* while */
  229. if ((ptr == modpath) && (*ptr != '\\'))
  230. __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
  231. else
  232. {
  233. *(ptr + 1) = '\0'; /* chop off filename. */
  234. retval = unicodeToUtf8Heap(modpath);
  235. } /* else */
  236. } /* else */
  237. allocator.Free(modpath);
  238. return retval; /* w00t. */
  239. } /* __PHYSFS_platformCalcBaseDir */
  240. char *__PHYSFS_platformGetUserName(void)
  241. {
  242. DWORD bufsize = 0;
  243. char *retval = NULL;
  244. if (GetUserNameW(NULL, &bufsize) == 0) /* This SHOULD fail. */
  245. {
  246. LPWSTR wbuf = (LPWSTR) __PHYSFS_smallAlloc(bufsize * sizeof (WCHAR));
  247. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  248. if (GetUserNameW(wbuf, &bufsize) == 0) /* ?! */
  249. __PHYSFS_setError(winApiStrError());
  250. else
  251. retval = unicodeToUtf8Heap(wbuf);
  252. __PHYSFS_smallFree(wbuf);
  253. } /* if */
  254. return retval;
  255. } /* __PHYSFS_platformGetUserName */
  256. char *__PHYSFS_platformGetUserDir(void)
  257. {
  258. char *retval = (char *) allocator.Malloc(strlen(userDir) + 1);
  259. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  260. strcpy(retval, userDir); /* calculated at init time. */
  261. return retval;
  262. } /* __PHYSFS_platformGetUserDir */
  263. void *__PHYSFS_platformGetThreadID(void)
  264. {
  265. return ( (void *) ((size_t) GetCurrentThreadId()) );
  266. } /* __PHYSFS_platformGetThreadID */
  267. static int isSymlinkAttrs(const DWORD attr, const DWORD tag)
  268. {
  269. return ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) &&
  270. (tag == PHYSFS_IO_REPARSE_TAG_SYMLINK) );
  271. } /* isSymlinkAttrs */
  272. char *__PHYSFS_platformCvtToDependent(const char *prepend,
  273. const char *dirName,
  274. const char *append)
  275. {
  276. const int len = ((prepend) ? strlen(prepend) : 0) +
  277. ((append) ? strlen(append) : 0) +
  278. strlen(dirName) + 1;
  279. char *retval = (char *) allocator.Malloc(len);
  280. char *p;
  281. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  282. _snprintf(retval, len, "%s%s%s",
  283. prepend ? prepend : "", dirName, append ? append : "");
  284. for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
  285. *p = '\\';
  286. return retval;
  287. } /* __PHYSFS_platformCvtToDependent */
  288. void __PHYSFS_platformEnumerateFiles(const char *dirname,
  289. int omitSymLinks,
  290. PHYSFS_EnumFilesCallback callback,
  291. const char *origdir,
  292. void *callbackdata)
  293. {
  294. HANDLE dir = INVALID_HANDLE_VALUE;
  295. WIN32_FIND_DATAW entw;
  296. size_t len = strlen(dirname);
  297. char *searchPath = NULL;
  298. WCHAR *wSearchPath = NULL;
  299. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  300. searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
  301. if (searchPath == NULL)
  302. return;
  303. /* Copy current dirname */
  304. strcpy(searchPath, dirname);
  305. /* if there's no '\\' at the end of the path, stick one in there. */
  306. if (searchPath[len - 1] != '\\')
  307. {
  308. searchPath[len++] = '\\';
  309. searchPath[len] = '\0';
  310. } /* if */
  311. /* Append the "*" to the end of the string */
  312. strcat(searchPath, "*");
  313. UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
  314. if (wSearchPath == NULL)
  315. return; /* oh well. */
  316. dir = FindFirstFileW(wSearchPath, &entw);
  317. __PHYSFS_smallFree(wSearchPath);
  318. __PHYSFS_smallFree(searchPath);
  319. if (dir == INVALID_HANDLE_VALUE)
  320. return;
  321. do
  322. {
  323. const DWORD attr = entw.dwFileAttributes;
  324. const DWORD tag = entw.dwReserved0;
  325. const WCHAR *fn = entw.cFileName;
  326. char *utf8;
  327. if ((fn[0] == '.') && (fn[1] == '\0'))
  328. continue;
  329. if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
  330. continue;
  331. if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
  332. continue;
  333. utf8 = unicodeToUtf8Heap(fn);
  334. if (utf8 != NULL)
  335. {
  336. callback(callbackdata, origdir, utf8);
  337. allocator.Free(utf8);
  338. } /* if */
  339. } while (FindNextFileW(dir, &entw) != 0);
  340. FindClose(dir);
  341. } /* __PHYSFS_platformEnumerateFiles */
  342. char *__PHYSFS_platformCurrentDir(void)
  343. {
  344. char *retval = NULL;
  345. WCHAR *wbuf = NULL;
  346. DWORD buflen = 0;
  347. buflen = GetCurrentDirectoryW(buflen, NULL);
  348. wbuf = (WCHAR *) __PHYSFS_smallAlloc((buflen + 2) * sizeof (WCHAR));
  349. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  350. GetCurrentDirectoryW(buflen, wbuf);
  351. if (wbuf[buflen - 2] == '\\')
  352. wbuf[buflen - 1] = '\0'; /* just in case... */
  353. else
  354. {
  355. wbuf[buflen - 1] = '\\';
  356. wbuf[buflen] = '\0';
  357. } /* else */
  358. retval = unicodeToUtf8Heap(wbuf);
  359. __PHYSFS_smallFree(wbuf);
  360. return retval;
  361. } /* __PHYSFS_platformCurrentDir */
  362. /* this could probably use a cleanup. */
  363. char *__PHYSFS_platformRealPath(const char *path)
  364. {
  365. /*
  366. * At this point, we only use this for the user and base dir,
  367. * and we already know those are RealPath'd by the OS for us.
  368. */
  369. char *retval = (char *) allocator.Malloc(strlen(path) + 1);
  370. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  371. strcpy(retval, path);
  372. return retval;
  373. } /* __PHYSFS_platformRealPath */
  374. int __PHYSFS_platformMkDir(const char *path)
  375. {
  376. WCHAR *wpath;
  377. DWORD rc;
  378. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  379. rc = CreateDirectoryW(wpath, NULL);
  380. __PHYSFS_smallFree(wpath);
  381. BAIL_IF_MACRO(rc == 0, winApiStrError(), 0);
  382. return 1;
  383. } /* __PHYSFS_platformMkDir */
  384. int __PHYSFS_platformInit(void)
  385. {
  386. libUserEnv = LoadLibraryA("userenv.dll");
  387. BAIL_IF_MACRO(libUserEnv == NULL, winApiStrError(), 0);
  388. /* !!! FIXME: why do we precalculate this? */
  389. BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
  390. return 1; /* It's all good */
  391. } /* __PHYSFS_platformInit */
  392. int __PHYSFS_platformDeinit(void)
  393. {
  394. if (libUserEnv)
  395. FreeLibrary(libUserEnv);
  396. libUserEnv = NULL;
  397. allocator.Free(userDir);
  398. userDir = NULL;
  399. return 1; /* It's all good */
  400. } /* __PHYSFS_platformDeinit */
  401. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  402. {
  403. HANDLE fileh;
  404. WinApiFile *retval;
  405. WCHAR *wfname;
  406. UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
  407. BAIL_IF_MACRO(wfname == NULL, ERR_OUT_OF_MEMORY, NULL);
  408. fileh = CreateFileW(wfname, mode, FILE_SHARE_READ | FILE_SHARE_WRITE,
  409. NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
  410. __PHYSFS_smallFree(wfname);
  411. BAIL_IF_MACRO(fileh == INVALID_HANDLE_VALUE,winApiStrError(), NULL);
  412. retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
  413. if (retval == NULL)
  414. {
  415. CloseHandle(fileh);
  416. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  417. } /* if */
  418. retval->readonly = rdonly;
  419. retval->handle = fileh;
  420. return retval;
  421. } /* doOpen */
  422. void *__PHYSFS_platformOpenRead(const char *filename)
  423. {
  424. return doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1);
  425. } /* __PHYSFS_platformOpenRead */
  426. void *__PHYSFS_platformOpenWrite(const char *filename)
  427. {
  428. return doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0);
  429. } /* __PHYSFS_platformOpenWrite */
  430. void *__PHYSFS_platformOpenAppend(const char *filename)
  431. {
  432. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  433. if (retval != NULL)
  434. {
  435. HANDLE h = ((WinApiFile *) retval)->handle;
  436. DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
  437. if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
  438. {
  439. const char *err = winApiStrError();
  440. CloseHandle(h);
  441. allocator.Free(retval);
  442. BAIL_MACRO(err, NULL);
  443. } /* if */
  444. } /* if */
  445. return retval;
  446. } /* __PHYSFS_platformOpenAppend */
  447. /* !!! FIXME: this function fails if len > 0xFFFFFFFF. */
  448. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buf, PHYSFS_uint64 len)
  449. {
  450. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  451. DWORD CountOfBytesRead = 0;
  452. BAIL_IF_MACRO(!__PHYSFS_ui64FitsAddressSpace(len),ERR_INVALID_ARGUMENT,-1);
  453. if(!ReadFile(Handle, buf, (DWORD) len, &CountOfBytesRead, NULL))
  454. BAIL_MACRO(winApiStrError(), -1);
  455. return (PHYSFS_sint64) CountOfBytesRead;
  456. } /* __PHYSFS_platformRead */
  457. /* !!! FIXME: this function fails if len > 0xFFFFFFFF. */
  458. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  459. PHYSFS_uint64 len)
  460. {
  461. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  462. DWORD CountOfBytesWritten = 0;
  463. BAIL_IF_MACRO(!__PHYSFS_ui64FitsAddressSpace(len),ERR_INVALID_ARGUMENT,-1);
  464. if(!WriteFile(Handle, buffer, (DWORD) len, &CountOfBytesWritten, NULL))
  465. BAIL_MACRO(winApiStrError(), -1);
  466. return (PHYSFS_sint64) CountOfBytesWritten;
  467. } /* __PHYSFS_platformWrite */
  468. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  469. {
  470. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  471. LONG HighOrderPos;
  472. PLONG pHighOrderPos;
  473. DWORD rc;
  474. /* Get the high order 32-bits of the position */
  475. HighOrderPos = HIGHORDER_UINT64(pos);
  476. /*
  477. * MSDN: "If you do not need the high-order 32 bits, this
  478. * pointer must be set to NULL."
  479. */
  480. pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
  481. /*
  482. * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
  483. * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
  484. * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
  485. * !!! FIXME: the sign extension of the value of lDistanceToMove.
  486. * !!! FIXME: Any other value will be rejected."
  487. */
  488. /* Move pointer "pos" count from start of file */
  489. rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
  490. pHighOrderPos, FILE_BEGIN);
  491. if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
  492. (GetLastError() != NO_ERROR) )
  493. {
  494. BAIL_MACRO(winApiStrError(), 0);
  495. } /* if */
  496. return 1; /* No error occured */
  497. } /* __PHYSFS_platformSeek */
  498. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  499. {
  500. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  501. LONG HighPos = 0;
  502. DWORD LowPos;
  503. PHYSFS_sint64 retval;
  504. /* Get current position */
  505. LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
  506. if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
  507. (GetLastError() != NO_ERROR) )
  508. {
  509. BAIL_MACRO(winApiStrError(), -1);
  510. } /* if */
  511. else
  512. {
  513. /* Combine the high/low order to create the 64-bit position value */
  514. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  515. assert(retval >= 0);
  516. } /* else */
  517. return retval;
  518. } /* __PHYSFS_platformTell */
  519. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  520. {
  521. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  522. DWORD SizeHigh;
  523. DWORD SizeLow;
  524. PHYSFS_sint64 retval;
  525. SizeLow = GetFileSize(Handle, &SizeHigh);
  526. if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
  527. (GetLastError() != NO_ERROR) )
  528. {
  529. BAIL_MACRO(winApiStrError(), -1);
  530. } /* if */
  531. else
  532. {
  533. /* Combine the high/low order to create the 64-bit position value */
  534. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  535. assert(retval >= 0);
  536. } /* else */
  537. return retval;
  538. } /* __PHYSFS_platformFileLength */
  539. int __PHYSFS_platformFlush(void *opaque)
  540. {
  541. WinApiFile *fh = ((WinApiFile *) opaque);
  542. if (!fh->readonly)
  543. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), winApiStrError(), 0);
  544. return 1;
  545. } /* __PHYSFS_platformFlush */
  546. void __PHYSFS_platformClose(void *opaque)
  547. {
  548. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  549. (void) CloseHandle(Handle); /* ignore errors. You should have flushed! */
  550. allocator.Free(opaque);
  551. } /* __PHYSFS_platformClose */
  552. static int doPlatformDelete(LPWSTR wpath)
  553. {
  554. const int isdir = (GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY);
  555. const BOOL rc = (isdir) ? RemoveDirectoryW(wpath) : DeleteFileW(wpath);
  556. BAIL_IF_MACRO(!rc, winApiStrError(), 0);
  557. return 1; /* if you made it here, it worked. */
  558. } /* doPlatformDelete */
  559. int __PHYSFS_platformDelete(const char *path)
  560. {
  561. int retval = 0;
  562. LPWSTR wpath = NULL;
  563. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  564. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  565. retval = doPlatformDelete(wpath);
  566. __PHYSFS_smallFree(wpath);
  567. return retval;
  568. } /* __PHYSFS_platformDelete */
  569. /*
  570. * !!! FIXME: why aren't we using Critical Sections instead of Mutexes?
  571. * !!! FIXME: mutexes on Windows are for cross-process sync. CritSects are
  572. * !!! FIXME: mutexes for threads in a single process and are faster.
  573. */
  574. void *__PHYSFS_platformCreateMutex(void)
  575. {
  576. return ((void *) CreateMutex(NULL, FALSE, NULL));
  577. } /* __PHYSFS_platformCreateMutex */
  578. void __PHYSFS_platformDestroyMutex(void *mutex)
  579. {
  580. CloseHandle((HANDLE) mutex);
  581. } /* __PHYSFS_platformDestroyMutex */
  582. int __PHYSFS_platformGrabMutex(void *mutex)
  583. {
  584. return (WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
  585. } /* __PHYSFS_platformGrabMutex */
  586. void __PHYSFS_platformReleaseMutex(void *mutex)
  587. {
  588. ReleaseMutex((HANDLE) mutex);
  589. } /* __PHYSFS_platformReleaseMutex */
  590. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  591. {
  592. SYSTEMTIME st_utc;
  593. SYSTEMTIME st_localtz;
  594. TIME_ZONE_INFORMATION tzi;
  595. DWORD tzid;
  596. PHYSFS_sint64 retval;
  597. struct tm tm;
  598. BOOL rc;
  599. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), winApiStrError(), -1);
  600. tzid = GetTimeZoneInformation(&tzi);
  601. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, winApiStrError(), -1);
  602. rc = SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz);
  603. BAIL_IF_MACRO(!rc, winApiStrError(), -1);
  604. /* Convert to a format that mktime() can grok... */
  605. tm.tm_sec = st_localtz.wSecond;
  606. tm.tm_min = st_localtz.wMinute;
  607. tm.tm_hour = st_localtz.wHour;
  608. tm.tm_mday = st_localtz.wDay;
  609. tm.tm_mon = st_localtz.wMonth - 1;
  610. tm.tm_year = st_localtz.wYear - 1900;
  611. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  612. tm.tm_yday = -1;
  613. tm.tm_isdst = -1;
  614. /* Convert to a format PhysicsFS can grok... */
  615. retval = (PHYSFS_sint64) mktime(&tm);
  616. BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
  617. return retval;
  618. } /* FileTimeToPhysfsTime */
  619. int __PHYSFS_platformStat(const char *filename, int *exists, PHYSFS_Stat *stat)
  620. {
  621. WIN32_FILE_ATTRIBUTE_DATA winstat;
  622. WCHAR *wstr = NULL;
  623. DWORD err = 0;
  624. BOOL rc = 0;
  625. UTF8_TO_UNICODE_STACK_MACRO(wstr, filename);
  626. BAIL_IF_MACRO(wstr == NULL, ERR_OUT_OF_MEMORY, 0);
  627. rc = GetFileAttributesExW(wstr, GetFileExInfoStandard, &winstat);
  628. err = (!rc) ? GetLastError() : 0;
  629. *exists = ((err != ERROR_FILE_NOT_FOUND) && (err != ERROR_PATH_NOT_FOUND));
  630. __PHYSFS_smallFree(wstr);
  631. BAIL_IF_MACRO(!rc, winApiStrErrorByNum(err), 0);
  632. stat->modtime = FileTimeToPhysfsTime(&winstat.ftLastWriteTime);
  633. stat->accesstime = FileTimeToPhysfsTime(&winstat.ftLastAccessTime);
  634. stat->createtime = FileTimeToPhysfsTime(&winstat.ftCreationTime);
  635. if(winstat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  636. {
  637. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  638. stat->filesize = 0;
  639. } /* if */
  640. else if(winstat.dwFileAttributes & (FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_DEVICE))
  641. {
  642. /* !!! FIXME: what are reparse points? */
  643. stat->filetype = PHYSFS_FILETYPE_OTHER;
  644. /* !!! FIXME: don't rely on this */
  645. stat->filesize = 0;
  646. } /* else if */
  647. /* !!! FIXME: check for symlinks on Vista. */
  648. else
  649. {
  650. stat->filetype = PHYSFS_FILETYPE_REGULAR;
  651. stat->filesize = (((PHYSFS_uint64) winstat.nFileSizeHigh) << 32) | winstat.nFileSizeLow;
  652. } /* else */
  653. stat->readonly = ((winstat.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  654. return 1;
  655. } /* __PHYSFS_platformStat */
  656. /* !!! FIXME: Don't use C runtime for allocators? */
  657. int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
  658. {
  659. return 0; /* just use malloc() and friends. */
  660. } /* __PHYSFS_platformSetDefaultAllocator */
  661. #endif /* PHYSFS_PLATFORM_WINDOWS */
  662. /* end of windows.c ... */