windows.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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, since we manage this ourselves. */
  12. #ifdef UNICODE
  13. #undef UNICODE
  14. #endif
  15. #include <windows.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <errno.h>
  20. #include <ctype.h>
  21. #include <time.h>
  22. #include "physfs_internal.h"
  23. #define LOWORDER_UINT64(pos) (PHYSFS_uint32) \
  24. (pos & 0x00000000FFFFFFFF)
  25. #define HIGHORDER_UINT64(pos) (PHYSFS_uint32) \
  26. (((pos & 0xFFFFFFFF00000000) >> 32) & 0x00000000FFFFFFFF)
  27. /*
  28. * Users without the platform SDK don't have this defined. The original docs
  29. * for SetFilePointer() just said to compare with 0xFFFFFFFF, so this should
  30. * work as desired.
  31. */
  32. #define PHYSFS_INVALID_SET_FILE_POINTER 0xFFFFFFFF
  33. /* just in case... */
  34. #define PHYSFS_INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
  35. #define UTF8_TO_UNICODE_STACK_MACRO(w_assignto, str) { \
  36. if (str == NULL) \
  37. w_assignto = NULL; \
  38. else { \
  39. const PHYSFS_uint64 len = (PHYSFS_uint64) ((strlen(str) * 4) + 1); \
  40. w_assignto = (WCHAR *) __PHYSFS_smallAlloc(len); \
  41. if (w_assignto != NULL) \
  42. PHYSFS_utf8ToUcs2(str, (PHYSFS_uint16 *) w_assignto, len); \
  43. } \
  44. } \
  45. static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
  46. {
  47. PHYSFS_uint64 len = 0;
  48. while (*(wstr++))
  49. len++;
  50. return(len);
  51. } /* wStrLen */
  52. static char *unicodeToUtf8Heap(const WCHAR *w_str)
  53. {
  54. char *retval = NULL;
  55. if (w_str != NULL)
  56. {
  57. void *ptr = NULL;
  58. const PHYSFS_uint64 len = (wStrLen(w_str) * 4) + 1;
  59. retval = allocator.Malloc(len);
  60. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  61. PHYSFS_utf8FromUcs2((const PHYSFS_uint16 *) w_str, retval, len);
  62. ptr = allocator.Realloc(retval, strlen(retval) + 1); /* shrink. */
  63. if (ptr != NULL)
  64. retval = (char *) ptr;
  65. } /* if */
  66. return(retval);
  67. } /* unicodeToUtf8Heap */
  68. static char *codepageToUtf8Heap(const char *cpstr)
  69. {
  70. char *retval = NULL;
  71. if (cpstr != NULL)
  72. {
  73. const int len = (int) (strlen(cpstr) + 1);
  74. WCHAR *wbuf = (WCHAR *) __PHYSFS_smallAlloc(len * sizeof (WCHAR));
  75. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  76. MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cpstr, len, wbuf, len);
  77. retval = (char *) allocator.Malloc(len * 4);
  78. if (retval == NULL)
  79. __PHYSFS_setError(ERR_OUT_OF_MEMORY);
  80. else
  81. PHYSFS_utf8FromUcs2(wbuf, retval, len * 4);
  82. __PHYSFS_smallFree(wbuf);
  83. } /* if */
  84. return(retval);
  85. } /* codepageToUtf8Heap */
  86. typedef struct
  87. {
  88. HANDLE handle;
  89. int readonly;
  90. } WinApiFile;
  91. static char *userDir = NULL;
  92. static int osHasUnicode = 0;
  93. /* pointers for APIs that may not exist on some Windows versions... */
  94. static HANDLE libKernel32 = NULL;
  95. static HANDLE libUserEnv = NULL;
  96. static HANDLE libAdvApi32 = NULL;
  97. static DWORD (WINAPI *pGetModuleFileNameW)(HMODULE, LPWCH, DWORD);
  98. static BOOL (WINAPI *pGetUserProfileDirectoryW)(HANDLE, LPWSTR, LPDWORD);
  99. static BOOL (WINAPI *pGetUserNameW)(LPWSTR, LPDWORD);
  100. static DWORD (WINAPI *pGetFileAttributesW)(LPCWSTR);
  101. static HANDLE (WINAPI *pFindFirstFileW)(LPCWSTR, LPWIN32_FIND_DATAW);
  102. static BOOL (WINAPI *pFindNextFileW)(HANDLE, LPWIN32_FIND_DATAW);
  103. static DWORD (WINAPI *pGetCurrentDirectoryW)(DWORD, LPWSTR);
  104. static BOOL (WINAPI *pDeleteFileW)(LPCWSTR);
  105. static BOOL (WINAPI *pRemoveDirectoryW)(LPCWSTR);
  106. static BOOL (WINAPI *pCreateDirectoryW)(LPCWSTR, LPSECURITY_ATTRIBUTES);
  107. static BOOL (WINAPI *pGetFileAttributesExA)
  108. (LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
  109. static BOOL (WINAPI *pGetFileAttributesExW)
  110. (LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);
  111. static DWORD (WINAPI *pFormatMessageW)
  112. (DWORD, LPCVOID, DWORD, DWORD, LPWSTR, DWORD, va_list *);
  113. static HANDLE (WINAPI *pCreateFileW)
  114. (LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
  115. /*
  116. * Fallbacks for missing Unicode functions on Win95/98/ME. These are filled
  117. * into the function pointers if looking up the real Unicode entry points
  118. * in the system DLLs fails, so they're never used on WinNT/XP/Vista/etc.
  119. * They make an earnest effort to convert to/from UTF-8 and UCS-2 to
  120. * the user's current codepage.
  121. */
  122. static BOOL WINAPI fallbackGetUserNameW(LPWSTR buf, LPDWORD len)
  123. {
  124. const DWORD cplen = *len;
  125. char *cpstr = __PHYSFS_smallAlloc(cplen);
  126. BOOL retval = GetUserNameA(cpstr, len);
  127. if (buf != NULL)
  128. MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, cpstr, cplen, buf, *len);
  129. __PHYSFS_smallFree(cpstr);
  130. return(retval);
  131. } /* fallbackGetUserNameW */
  132. static DWORD WINAPI fallbackFormatMessageW(DWORD dwFlags, LPCVOID lpSource,
  133. DWORD dwMessageId, DWORD dwLangId,
  134. LPWSTR lpBuf, DWORD nSize,
  135. va_list *Arguments)
  136. {
  137. char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
  138. DWORD retval = FormatMessageA(dwFlags, lpSource, dwMessageId, dwLangId,
  139. cpbuf, nSize, Arguments);
  140. if (retval > 0)
  141. MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
  142. __PHYSFS_smallFree(cpbuf);
  143. return(retval);
  144. } /* fallbackFormatMessageW */
  145. static DWORD WINAPI fallbackGetModuleFileNameW(HMODULE hMod, LPWCH lpBuf,
  146. DWORD nSize)
  147. {
  148. char *cpbuf = (char *) __PHYSFS_smallAlloc(nSize);
  149. DWORD retval = GetModuleFileNameA(hMod, cpbuf, nSize);
  150. if (retval > 0)
  151. MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,lpBuf,nSize);
  152. __PHYSFS_smallFree(cpbuf);
  153. return(retval);
  154. } /* fallbackGetModuleFileNameW */
  155. static DWORD WINAPI fallbackGetFileAttributesW(LPCWSTR fname)
  156. {
  157. DWORD retval = 0;
  158. const int buflen = (int) (wStrLen(fname) + 1);
  159. char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
  160. WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
  161. retval = GetFileAttributesA(cpstr);
  162. __PHYSFS_smallFree(cpstr);
  163. return(retval);
  164. } /* fallbackGetFileAttributesW */
  165. static DWORD WINAPI fallbackGetCurrentDirectoryW(DWORD buflen, LPWSTR buf)
  166. {
  167. DWORD retval = 0;
  168. char *cpbuf = NULL;
  169. if (buf != NULL)
  170. cpbuf = (char *) __PHYSFS_smallAlloc(buflen);
  171. retval = GetCurrentDirectoryA(buflen, cpbuf);
  172. if (cpbuf != NULL)
  173. {
  174. MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,cpbuf,retval,buf,buflen);
  175. __PHYSFS_smallFree(cpbuf);
  176. } /* if */
  177. return(retval);
  178. } /* fallbackGetCurrentDirectoryW */
  179. static BOOL WINAPI fallbackRemoveDirectoryW(LPCWSTR dname)
  180. {
  181. BOOL retval = 0;
  182. const int buflen = (int) (wStrLen(dname) + 1);
  183. char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
  184. WideCharToMultiByte(CP_ACP, 0, dname, buflen, cpstr, buflen, NULL, NULL);
  185. retval = RemoveDirectoryA(cpstr);
  186. __PHYSFS_smallFree(cpstr);
  187. return(retval);
  188. } /* fallbackRemoveDirectoryW */
  189. static BOOL WINAPI fallbackCreateDirectoryW(LPCWSTR dname,
  190. LPSECURITY_ATTRIBUTES attr)
  191. {
  192. BOOL retval = 0;
  193. const int buflen = (int) (wStrLen(dname) + 1);
  194. char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
  195. WideCharToMultiByte(CP_ACP, 0, dname, buflen, cpstr, buflen, NULL, NULL);
  196. retval = CreateDirectoryA(cpstr, attr);
  197. __PHYSFS_smallFree(cpstr);
  198. return(retval);
  199. } /* fallbackCreateDirectoryW */
  200. static BOOL WINAPI fallbackDeleteFileW(LPCWSTR fname)
  201. {
  202. BOOL retval = 0;
  203. const int buflen = (int) (wStrLen(fname) + 1);
  204. char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
  205. WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
  206. retval = DeleteFileA(cpstr);
  207. __PHYSFS_smallFree(cpstr);
  208. return(retval);
  209. } /* fallbackDeleteFileW */
  210. static HANDLE WINAPI fallbackCreateFileW(LPCWSTR fname,
  211. DWORD dwDesiredAccess, DWORD dwShareMode,
  212. LPSECURITY_ATTRIBUTES lpSecurityAttrs,
  213. DWORD dwCreationDisposition,
  214. DWORD dwFlagsAndAttrs, HANDLE hTemplFile)
  215. {
  216. HANDLE retval;
  217. const int buflen = (int) (wStrLen(fname) + 1);
  218. char *cpstr = (char *) __PHYSFS_smallAlloc(buflen);
  219. WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL);
  220. retval = CreateFileA(cpstr, dwDesiredAccess, dwShareMode, lpSecurityAttrs,
  221. dwCreationDisposition, dwFlagsAndAttrs, hTemplFile);
  222. __PHYSFS_smallFree(cpstr);
  223. return(retval);
  224. } /* fallbackCreateFileW */
  225. /* A blatant abuse of pointer casting... */
  226. static int symLookup(HMODULE dll, void **addr, const char *sym)
  227. {
  228. return( (*addr = GetProcAddress(dll, sym)) != NULL );
  229. } /* symLookup */
  230. static int findApiSymbols(void)
  231. {
  232. HMODULE dll = NULL;
  233. #define LOOKUP_NOFALLBACK(x, reallyLook) { \
  234. if (reallyLook) \
  235. symLookup(dll, (void **) &p##x, #x); \
  236. else \
  237. p##x = NULL; \
  238. }
  239. #define LOOKUP(x, reallyLook) { \
  240. if ((!reallyLook) || (!symLookup(dll, (void **) &p##x, #x))) \
  241. p##x = fallback##x; \
  242. }
  243. /* Apparently Win9x HAS the Unicode entry points, they just don't WORK. */
  244. /* ...so don't look them up unless we're on NT+. (see osHasUnicode.) */
  245. dll = libUserEnv = LoadLibraryA("userenv.dll");
  246. if (dll != NULL)
  247. LOOKUP_NOFALLBACK(GetUserProfileDirectoryW, osHasUnicode);
  248. /* !!! FIXME: what do they call advapi32.dll on Win64? */
  249. dll = libAdvApi32 = LoadLibraryA("advapi32.dll");
  250. if (dll != NULL)
  251. LOOKUP(GetUserNameW, osHasUnicode);
  252. /* !!! FIXME: what do they call kernel32.dll on Win64? */
  253. dll = libKernel32 = LoadLibraryA("kernel32.dll");
  254. if (dll != NULL)
  255. {
  256. LOOKUP_NOFALLBACK(GetFileAttributesExA, 1);
  257. LOOKUP_NOFALLBACK(GetFileAttributesExW, osHasUnicode);
  258. LOOKUP_NOFALLBACK(FindFirstFileW, osHasUnicode);
  259. LOOKUP_NOFALLBACK(FindNextFileW, osHasUnicode);
  260. LOOKUP(GetModuleFileNameW, osHasUnicode);
  261. LOOKUP(FormatMessageW, osHasUnicode);
  262. LOOKUP(GetFileAttributesW, osHasUnicode);
  263. LOOKUP(GetCurrentDirectoryW, osHasUnicode);
  264. LOOKUP(CreateDirectoryW, osHasUnicode);
  265. LOOKUP(RemoveDirectoryW, osHasUnicode);
  266. LOOKUP(CreateFileW, osHasUnicode);
  267. LOOKUP(DeleteFileW, osHasUnicode);
  268. } /* if */
  269. #undef LOOKUP_NOFALLBACK
  270. #undef LOOKUP
  271. return(1);
  272. } /* findApiSymbols */
  273. const char *__PHYSFS_platformDirSeparator = "\\";
  274. /*
  275. * Figure out what the last failing Windows API call was, and
  276. * generate a human-readable string for the error message.
  277. *
  278. * The return value is a static buffer that is overwritten with
  279. * each call to this function.
  280. */
  281. static const char *winApiStrError(void)
  282. {
  283. static char utf8buf[255];
  284. WCHAR msgbuf[255];
  285. WCHAR *ptr;
  286. DWORD rc = pFormatMessageW(
  287. FORMAT_MESSAGE_FROM_SYSTEM |
  288. FORMAT_MESSAGE_IGNORE_INSERTS,
  289. NULL, GetLastError(),
  290. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  291. msgbuf, __PHYSFS_ARRAYLEN(msgbuf),
  292. NULL);
  293. /* chop off newlines. */
  294. for (ptr = msgbuf; *ptr; ptr++)
  295. {
  296. if ((*ptr == '\n') || (*ptr == '\r'))
  297. {
  298. *ptr = '\0';
  299. break;
  300. } /* if */
  301. } /* for */
  302. /* may truncate, but oh well. */
  303. PHYSFS_utf8FromUcs2((PHYSFS_uint16 *) msgbuf, utf8buf, sizeof (utf8buf));
  304. return((const char *) utf8buf);
  305. } /* winApiStrError */
  306. static char *getExePath(void)
  307. {
  308. DWORD buflen = 64;
  309. int success = 0;
  310. LPWSTR modpath = NULL;
  311. char *retval = NULL;
  312. while (1)
  313. {
  314. DWORD rc;
  315. void *ptr;
  316. if ( !(ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) )
  317. {
  318. allocator.Free(modpath);
  319. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  320. } /* if */
  321. modpath = (LPWSTR) ptr;
  322. rc = pGetModuleFileNameW(NULL, modpath, buflen);
  323. if (rc == 0)
  324. {
  325. allocator.Free(modpath);
  326. BAIL_MACRO(winApiStrError(), NULL);
  327. } /* if */
  328. if (rc < buflen)
  329. {
  330. buflen = rc;
  331. break;
  332. } /* if */
  333. buflen *= 2;
  334. } /* while */
  335. if (buflen > 0) /* just in case... */
  336. {
  337. WCHAR *ptr = (modpath + buflen) - 1;
  338. while (ptr != modpath)
  339. {
  340. if (*ptr == '\\')
  341. break;
  342. ptr--;
  343. } /* while */
  344. if ((ptr == modpath) && (*ptr != '\\'))
  345. __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
  346. else
  347. {
  348. *(ptr + 1) = '\0'; /* chop off filename. */
  349. retval = unicodeToUtf8Heap(modpath);
  350. } /* else */
  351. } /* else */
  352. allocator.Free(modpath);
  353. return(retval); /* w00t. */
  354. } /* getExePath */
  355. /*
  356. * Try to make use of GetUserProfileDirectoryW(), which isn't available on
  357. * some common variants of Win32. If we can't use this, we just punt and
  358. * use the physfs base dir for the user dir, too.
  359. *
  360. * On success, module-scope variable (userDir) will have a pointer to
  361. * a malloc()'d string of the user's profile dir, and a non-zero value is
  362. * returned. If we can't determine the profile dir, (userDir) will
  363. * be NULL, and zero is returned.
  364. */
  365. static int determineUserDir(void)
  366. {
  367. if (userDir != NULL)
  368. return(1); /* already good to go. */
  369. /*
  370. * GetUserProfileDirectoryW() is only available on NT 4.0 and later.
  371. * This means Win95/98/ME (and CE?) users have to do without, so for
  372. * them, we'll default to the base directory when we can't get the
  373. * function pointer. Since this is originally an NT API, we don't
  374. * offer a non-Unicode fallback.
  375. */
  376. if (pGetUserProfileDirectoryW != NULL)
  377. {
  378. HANDLE accessToken = NULL; /* Security handle to process */
  379. HANDLE processHandle = GetCurrentProcess();
  380. if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
  381. {
  382. DWORD psize = 0;
  383. WCHAR dummy = 0;
  384. LPWSTR wstr = NULL;
  385. BOOL rc = 0;
  386. /*
  387. * Should fail. Will write the size of the profile path in
  388. * psize. Also note that the second parameter can't be
  389. * NULL or the function fails.
  390. */
  391. rc = pGetUserProfileDirectoryW(accessToken, &dummy, &psize);
  392. assert(!rc); /* !!! FIXME: handle this gracefully. */
  393. /* Allocate memory for the profile directory */
  394. wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
  395. if (wstr != NULL)
  396. {
  397. if (pGetUserProfileDirectoryW(accessToken, wstr, &psize))
  398. userDir = unicodeToUtf8Heap(wstr);
  399. __PHYSFS_smallFree(wstr);
  400. } /* else */
  401. } /* if */
  402. CloseHandle(accessToken);
  403. } /* if */
  404. if (userDir == NULL) /* couldn't get profile for some reason. */
  405. {
  406. /* Might just be a non-NT system; resort to the basedir. */
  407. userDir = getExePath();
  408. BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
  409. } /* if */
  410. return(1); /* We made it: hit the showers. */
  411. } /* determineUserDir */
  412. static BOOL mediaInDrive(const char *drive)
  413. {
  414. UINT oldErrorMode;
  415. DWORD tmp;
  416. BOOL retval;
  417. /* Prevent windows warning message appearing when checking media size */
  418. oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  419. /* If this function succeeds, there's media in the drive */
  420. retval = GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0);
  421. /* Revert back to old windows error handler */
  422. SetErrorMode(oldErrorMode);
  423. return(retval);
  424. } /* mediaInDrive */
  425. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  426. {
  427. /* !!! FIXME: Can CD drives be non-drive letter paths? */
  428. /* !!! FIXME: (so can they be Unicode paths?) */
  429. char drive_str[4] = "x:\\";
  430. char ch;
  431. for (ch = 'A'; ch <= 'Z'; ch++)
  432. {
  433. drive_str[0] = ch;
  434. if (GetDriveType(drive_str) == DRIVE_CDROM && mediaInDrive(drive_str))
  435. cb(data, drive_str);
  436. } /* for */
  437. } /* __PHYSFS_platformDetectAvailableCDs */
  438. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  439. {
  440. if ((argv0 != NULL) && (strchr(argv0, '\\') != NULL))
  441. return(NULL); /* default behaviour can handle this. */
  442. return(getExePath());
  443. } /* __PHYSFS_platformCalcBaseDir */
  444. char *__PHYSFS_platformGetUserName(void)
  445. {
  446. DWORD bufsize = 0;
  447. char *retval = NULL;
  448. if (pGetUserNameW(NULL, &bufsize) == 0) /* This SHOULD fail. */
  449. {
  450. LPWSTR wbuf = (LPWSTR) __PHYSFS_smallAlloc(bufsize * sizeof (WCHAR));
  451. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  452. if (pGetUserNameW(wbuf, &bufsize) == 0) /* ?! */
  453. __PHYSFS_setError(winApiStrError());
  454. else
  455. retval = unicodeToUtf8Heap(wbuf);
  456. __PHYSFS_smallFree(wbuf);
  457. } /* if */
  458. return(retval);
  459. } /* __PHYSFS_platformGetUserName */
  460. char *__PHYSFS_platformGetUserDir(void)
  461. {
  462. char *retval = (char *) allocator.Malloc(strlen(userDir) + 1);
  463. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  464. strcpy(retval, userDir); /* calculated at init time. */
  465. return(retval);
  466. } /* __PHYSFS_platformGetUserDir */
  467. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  468. {
  469. return((PHYSFS_uint64) GetCurrentThreadId());
  470. } /* __PHYSFS_platformGetThreadID */
  471. static int doPlatformExists(LPWSTR wpath)
  472. {
  473. BAIL_IF_MACRO
  474. (
  475. pGetFileAttributesW(wpath) == PHYSFS_INVALID_FILE_ATTRIBUTES,
  476. winApiStrError(), 0
  477. );
  478. return(1);
  479. } /* doPlatformExists */
  480. int __PHYSFS_platformExists(const char *fname)
  481. {
  482. int retval = 0;
  483. LPWSTR wpath;
  484. UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
  485. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  486. retval = doPlatformExists(wpath);
  487. __PHYSFS_smallFree(wpath);
  488. return(retval);
  489. } /* __PHYSFS_platformExists */
  490. int __PHYSFS_platformIsSymLink(const char *fname)
  491. {
  492. /* !!! FIXME: Vista has symlinks. Recheck this. */
  493. return(0); /* no symlinks on win32. */
  494. } /* __PHYSFS_platformIsSymlink */
  495. int __PHYSFS_platformIsDirectory(const char *fname)
  496. {
  497. int retval = 0;
  498. LPWSTR wpath;
  499. UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
  500. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  501. retval = ((pGetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY) != 0);
  502. __PHYSFS_smallFree(wpath);
  503. return(retval);
  504. } /* __PHYSFS_platformIsDirectory */
  505. char *__PHYSFS_platformCvtToDependent(const char *prepend,
  506. const char *dirName,
  507. const char *append)
  508. {
  509. int len = ((prepend) ? strlen(prepend) : 0) +
  510. ((append) ? strlen(append) : 0) +
  511. strlen(dirName) + 1;
  512. char *retval = (char *) allocator.Malloc(len);
  513. char *p;
  514. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  515. if (prepend)
  516. strcpy(retval, prepend);
  517. else
  518. retval[0] = '\0';
  519. strcat(retval, dirName);
  520. if (append)
  521. strcat(retval, append);
  522. for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
  523. *p = '\\';
  524. return(retval);
  525. } /* __PHYSFS_platformCvtToDependent */
  526. void __PHYSFS_platformEnumerateFiles(const char *dirname,
  527. int omitSymLinks,
  528. PHYSFS_EnumFilesCallback callback,
  529. const char *origdir,
  530. void *callbackdata)
  531. {
  532. const int unicode = (pFindFirstFileW != NULL) && (pFindNextFileW != NULL);
  533. HANDLE dir = INVALID_HANDLE_VALUE;
  534. WIN32_FIND_DATA ent;
  535. WIN32_FIND_DATAW entw;
  536. size_t len = strlen(dirname);
  537. char *searchPath = NULL;
  538. WCHAR *wSearchPath = NULL;
  539. char *utf8 = NULL;
  540. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  541. searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
  542. if (searchPath == NULL)
  543. return;
  544. /* Copy current dirname */
  545. strcpy(searchPath, dirname);
  546. /* if there's no '\\' at the end of the path, stick one in there. */
  547. if (searchPath[len - 1] != '\\')
  548. {
  549. searchPath[len++] = '\\';
  550. searchPath[len] = '\0';
  551. } /* if */
  552. /* Append the "*" to the end of the string */
  553. strcat(searchPath, "*");
  554. UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
  555. if (wSearchPath == NULL)
  556. return; /* oh well. */
  557. if (unicode)
  558. dir = pFindFirstFileW(wSearchPath, &entw);
  559. else
  560. {
  561. const int len = (int) (wStrLen(wSearchPath) + 1);
  562. char *cp = (char *) __PHYSFS_smallAlloc(len);
  563. if (cp != NULL)
  564. {
  565. WideCharToMultiByte(CP_ACP, 0, wSearchPath, len, cp, len, 0, 0);
  566. dir = FindFirstFileA(cp, &ent);
  567. __PHYSFS_smallFree(cp);
  568. } /* if */
  569. } /* else */
  570. __PHYSFS_smallFree(wSearchPath);
  571. __PHYSFS_smallFree(searchPath);
  572. if (dir == INVALID_HANDLE_VALUE)
  573. return;
  574. if (unicode)
  575. {
  576. do
  577. {
  578. const WCHAR *fn = entw.cFileName;
  579. if ((fn[0] == '.') && (fn[1] == '\0'))
  580. continue;
  581. if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
  582. continue;
  583. utf8 = unicodeToUtf8Heap(entw.cFileName);
  584. if (utf8 != NULL)
  585. {
  586. callback(callbackdata, origdir, utf8);
  587. allocator.Free(utf8);
  588. } /* if */
  589. } while (pFindNextFileW(dir, &entw) != 0);
  590. } /* if */
  591. else /* ANSI fallback. */
  592. {
  593. do
  594. {
  595. const char *fn = ent.cFileName;
  596. if ((fn[0] == '.') && (fn[1] == '\0'))
  597. continue;
  598. if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
  599. continue;
  600. utf8 = codepageToUtf8Heap(ent.cFileName);
  601. if (utf8 != NULL)
  602. {
  603. callback(callbackdata, origdir, utf8);
  604. allocator.Free(utf8);
  605. } /* if */
  606. } while (FindNextFileA(dir, &ent) != 0);
  607. } /* else */
  608. FindClose(dir);
  609. } /* __PHYSFS_platformEnumerateFiles */
  610. char *__PHYSFS_platformCurrentDir(void)
  611. {
  612. char *retval = NULL;
  613. WCHAR *wbuf = NULL;
  614. DWORD buflen = 0;
  615. buflen = pGetCurrentDirectoryW(buflen, NULL);
  616. wbuf = (WCHAR *) __PHYSFS_smallAlloc((buflen + 2) * sizeof (WCHAR));
  617. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  618. pGetCurrentDirectoryW(buflen, wbuf);
  619. if (wbuf[buflen - 2] == '\\')
  620. wbuf[buflen-1] = '\0'; /* just in case... */
  621. else
  622. {
  623. wbuf[buflen - 1] = '\\';
  624. wbuf[buflen] = '\0';
  625. } /* else */
  626. retval = unicodeToUtf8Heap(wbuf);
  627. __PHYSFS_smallFree(wbuf);
  628. return(retval);
  629. } /* __PHYSFS_platformCurrentDir */
  630. /* this could probably use a cleanup. */
  631. char *__PHYSFS_platformRealPath(const char *path)
  632. {
  633. /* !!! FIXME: try GetFullPathName() instead? */
  634. /* this function should be UTF-8 clean. */
  635. char *retval = NULL;
  636. char *p = NULL;
  637. BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
  638. BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
  639. retval = (char *) allocator.Malloc(MAX_PATH);
  640. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  641. /*
  642. * If in \\server\path format, it's already an absolute path.
  643. * We'll need to check for "." and ".." dirs, though, just in case.
  644. */
  645. if ((path[0] == '\\') && (path[1] == '\\'))
  646. strcpy(retval, path);
  647. else
  648. {
  649. char *currentDir = __PHYSFS_platformCurrentDir();
  650. if (currentDir == NULL)
  651. {
  652. allocator.Free(retval);
  653. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  654. } /* if */
  655. if (path[1] == ':') /* drive letter specified? */
  656. {
  657. /*
  658. * Apparently, "D:mypath" is the same as "D:\\mypath" if
  659. * D: is not the current drive. However, if D: is the
  660. * current drive, then "D:mypath" is a relative path. Ugh.
  661. */
  662. if (path[2] == '\\') /* maybe an absolute path? */
  663. strcpy(retval, path);
  664. else /* definitely an absolute path. */
  665. {
  666. if (path[0] == currentDir[0]) /* current drive; relative. */
  667. {
  668. strcpy(retval, currentDir);
  669. strcat(retval, path + 2);
  670. } /* if */
  671. else /* not current drive; absolute. */
  672. {
  673. retval[0] = path[0];
  674. retval[1] = ':';
  675. retval[2] = '\\';
  676. strcpy(retval + 3, path + 2);
  677. } /* else */
  678. } /* else */
  679. } /* if */
  680. else /* no drive letter specified. */
  681. {
  682. if (path[0] == '\\') /* absolute path. */
  683. {
  684. retval[0] = currentDir[0];
  685. retval[1] = ':';
  686. strcpy(retval + 2, path);
  687. } /* if */
  688. else
  689. {
  690. strcpy(retval, currentDir);
  691. strcat(retval, path);
  692. } /* else */
  693. } /* else */
  694. allocator.Free(currentDir);
  695. } /* else */
  696. /* (whew.) Ok, now take out "." and ".." path entries... */
  697. p = retval;
  698. while ( (p = strstr(p, "\\.")) != NULL)
  699. {
  700. /* it's a "." entry that doesn't end the string. */
  701. if (p[2] == '\\')
  702. memmove(p + 1, p + 3, strlen(p + 3) + 1);
  703. /* it's a "." entry that ends the string. */
  704. else if (p[2] == '\0')
  705. p[0] = '\0';
  706. /* it's a ".." entry. */
  707. else if (p[2] == '.')
  708. {
  709. char *prevEntry = p - 1;
  710. while ((prevEntry != retval) && (*prevEntry != '\\'))
  711. prevEntry--;
  712. if (prevEntry == retval) /* make it look like a "." entry. */
  713. memmove(p + 1, p + 2, strlen(p + 2) + 1);
  714. else
  715. {
  716. if (p[3] != '\0') /* doesn't end string. */
  717. *prevEntry = '\0';
  718. else /* ends string. */
  719. memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
  720. p = prevEntry;
  721. } /* else */
  722. } /* else if */
  723. else
  724. {
  725. p++; /* look past current char. */
  726. } /* else */
  727. } /* while */
  728. /* shrink the retval's memory block if possible... */
  729. p = (char *) allocator.Realloc(retval, strlen(retval) + 1);
  730. if (p != NULL)
  731. retval = p;
  732. return(retval);
  733. } /* __PHYSFS_platformRealPath */
  734. int __PHYSFS_platformMkDir(const char *path)
  735. {
  736. WCHAR *wpath;
  737. DWORD rc;
  738. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  739. rc = pCreateDirectoryW(wpath, NULL);
  740. __PHYSFS_smallFree(wpath);
  741. BAIL_IF_MACRO(rc == 0, winApiStrError(), 0);
  742. return(1);
  743. } /* __PHYSFS_platformMkDir */
  744. /*
  745. * Get OS info and save the important parts.
  746. *
  747. * Returns non-zero if successful, otherwise it returns zero on failure.
  748. */
  749. static int getOSInfo(void)
  750. {
  751. OSVERSIONINFO osVerInfo; /* Information about the OS */
  752. osVerInfo.dwOSVersionInfoSize = sizeof(osVerInfo);
  753. BAIL_IF_MACRO(!GetVersionEx(&osVerInfo), winApiStrError(), 0);
  754. osHasUnicode = (osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS);
  755. return(1);
  756. } /* getOSInfo */
  757. int __PHYSFS_platformInit(void)
  758. {
  759. BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
  760. BAIL_IF_MACRO(!findApiSymbols(), NULL, 0);
  761. BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
  762. return(1); /* It's all good */
  763. } /* __PHYSFS_platformInit */
  764. int __PHYSFS_platformDeinit(void)
  765. {
  766. HANDLE *libs[] = { &libKernel32, &libUserEnv, &libAdvApi32, NULL };
  767. int i;
  768. allocator.Free(userDir);
  769. userDir = NULL;
  770. for (i = 0; libs[i] != NULL; i++)
  771. {
  772. const HANDLE lib = *(libs[i]);
  773. if (lib)
  774. FreeLibrary(lib);
  775. *(libs[i]) = NULL;
  776. } /* for */
  777. return(1); /* It's all good */
  778. } /* __PHYSFS_platformDeinit */
  779. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  780. {
  781. HANDLE fileHandle;
  782. WinApiFile *retval;
  783. WCHAR *wfname;
  784. UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
  785. BAIL_IF_MACRO(wfname == NULL, ERR_OUT_OF_MEMORY, NULL);
  786. fileHandle = pCreateFileW(wfname, mode, FILE_SHARE_READ, NULL,
  787. creation, FILE_ATTRIBUTE_NORMAL, NULL);
  788. __PHYSFS_smallFree(wfname);
  789. BAIL_IF_MACRO
  790. (
  791. fileHandle == INVALID_HANDLE_VALUE,
  792. winApiStrError(), NULL
  793. );
  794. retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
  795. if (retval == NULL)
  796. {
  797. CloseHandle(fileHandle);
  798. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  799. } /* if */
  800. retval->readonly = rdonly;
  801. retval->handle = fileHandle;
  802. return(retval);
  803. } /* doOpen */
  804. void *__PHYSFS_platformOpenRead(const char *filename)
  805. {
  806. return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
  807. } /* __PHYSFS_platformOpenRead */
  808. void *__PHYSFS_platformOpenWrite(const char *filename)
  809. {
  810. return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
  811. } /* __PHYSFS_platformOpenWrite */
  812. void *__PHYSFS_platformOpenAppend(const char *filename)
  813. {
  814. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  815. if (retval != NULL)
  816. {
  817. HANDLE h = ((WinApiFile *) retval)->handle;
  818. DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
  819. if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
  820. {
  821. const char *err = winApiStrError();
  822. CloseHandle(h);
  823. allocator.Free(retval);
  824. BAIL_MACRO(err, NULL);
  825. } /* if */
  826. } /* if */
  827. return(retval);
  828. } /* __PHYSFS_platformOpenAppend */
  829. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
  830. PHYSFS_uint32 size, PHYSFS_uint32 count)
  831. {
  832. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  833. DWORD CountOfBytesRead;
  834. PHYSFS_sint64 retval;
  835. /* Read data from the file */
  836. /* !!! FIXME: uint32 might be a greater # than DWORD */
  837. if(!ReadFile(Handle, buffer, count * size, &CountOfBytesRead, NULL))
  838. {
  839. BAIL_MACRO(winApiStrError(), -1);
  840. } /* if */
  841. else
  842. {
  843. /* Return the number of "objects" read. */
  844. /* !!! FIXME: What if not the right amount of bytes was read to make an object? */
  845. retval = CountOfBytesRead / size;
  846. } /* else */
  847. return(retval);
  848. } /* __PHYSFS_platformRead */
  849. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  850. PHYSFS_uint32 size, PHYSFS_uint32 count)
  851. {
  852. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  853. DWORD CountOfBytesWritten;
  854. PHYSFS_sint64 retval;
  855. /* Read data from the file */
  856. /* !!! FIXME: uint32 might be a greater # than DWORD */
  857. if(!WriteFile(Handle, buffer, count * size, &CountOfBytesWritten, NULL))
  858. {
  859. BAIL_MACRO(winApiStrError(), -1);
  860. } /* if */
  861. else
  862. {
  863. /* Return the number of "objects" read. */
  864. /* !!! FIXME: What if not the right number of bytes was written? */
  865. retval = CountOfBytesWritten / size;
  866. } /* else */
  867. return(retval);
  868. } /* __PHYSFS_platformWrite */
  869. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  870. {
  871. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  872. DWORD HighOrderPos;
  873. DWORD *pHighOrderPos;
  874. DWORD rc;
  875. /* Get the high order 32-bits of the position */
  876. HighOrderPos = HIGHORDER_UINT64(pos);
  877. /*
  878. * MSDN: "If you do not need the high-order 32 bits, this
  879. * pointer must be set to NULL."
  880. */
  881. pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
  882. /*
  883. * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
  884. * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
  885. * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
  886. * !!! FIXME: the sign extension of the value of lDistanceToMove.
  887. * !!! FIXME: Any other value will be rejected."
  888. */
  889. /* Move pointer "pos" count from start of file */
  890. rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
  891. pHighOrderPos, FILE_BEGIN);
  892. if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
  893. (GetLastError() != NO_ERROR) )
  894. {
  895. BAIL_MACRO(winApiStrError(), 0);
  896. } /* if */
  897. return(1); /* No error occured */
  898. } /* __PHYSFS_platformSeek */
  899. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  900. {
  901. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  902. DWORD HighPos = 0;
  903. DWORD LowPos;
  904. PHYSFS_sint64 retval;
  905. /* Get current position */
  906. LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
  907. if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
  908. (GetLastError() != NO_ERROR) )
  909. {
  910. BAIL_MACRO(winApiStrError(), 0);
  911. } /* if */
  912. else
  913. {
  914. /* Combine the high/low order to create the 64-bit position value */
  915. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  916. assert(retval >= 0);
  917. } /* else */
  918. return(retval);
  919. } /* __PHYSFS_platformTell */
  920. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  921. {
  922. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  923. DWORD SizeHigh;
  924. DWORD SizeLow;
  925. PHYSFS_sint64 retval;
  926. SizeLow = GetFileSize(Handle, &SizeHigh);
  927. if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
  928. (GetLastError() != NO_ERROR) )
  929. {
  930. BAIL_MACRO(winApiStrError(), -1);
  931. } /* if */
  932. else
  933. {
  934. /* Combine the high/low order to create the 64-bit position value */
  935. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  936. assert(retval >= 0);
  937. } /* else */
  938. return(retval);
  939. } /* __PHYSFS_platformFileLength */
  940. int __PHYSFS_platformEOF(void *opaque)
  941. {
  942. PHYSFS_sint64 FilePosition;
  943. int retval = 0;
  944. /* Get the current position in the file */
  945. if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
  946. {
  947. /* Non-zero if EOF is equal to the file length */
  948. retval = FilePosition == __PHYSFS_platformFileLength(opaque);
  949. } /* if */
  950. return(retval);
  951. } /* __PHYSFS_platformEOF */
  952. int __PHYSFS_platformFlush(void *opaque)
  953. {
  954. WinApiFile *fh = ((WinApiFile *) opaque);
  955. if (!fh->readonly)
  956. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), winApiStrError(), 0);
  957. return(1);
  958. } /* __PHYSFS_platformFlush */
  959. int __PHYSFS_platformClose(void *opaque)
  960. {
  961. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  962. BAIL_IF_MACRO(!CloseHandle(Handle), winApiStrError(), 0);
  963. allocator.Free(opaque);
  964. return(1);
  965. } /* __PHYSFS_platformClose */
  966. static int doPlatformDelete(LPWSTR wpath)
  967. {
  968. /* If filename is a folder */
  969. if (pGetFileAttributesW(wpath) == FILE_ATTRIBUTE_DIRECTORY)
  970. {
  971. BAIL_IF_MACRO(!pRemoveDirectoryW(wpath), winApiStrError(), 0);
  972. } /* if */
  973. else
  974. {
  975. BAIL_IF_MACRO(!pDeleteFileW(wpath), winApiStrError(), 0);
  976. } /* else */
  977. return(1); /* if you made it here, it worked. */
  978. } /* doPlatformDelete */
  979. int __PHYSFS_platformDelete(const char *path)
  980. {
  981. int retval = 0;
  982. LPWSTR wpath;
  983. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  984. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  985. retval = doPlatformDelete(wpath);
  986. __PHYSFS_smallFree(wpath);
  987. return(retval);
  988. } /* __PHYSFS_platformDelete */
  989. /*
  990. * !!! FIXME: why aren't we using Critical Sections instead of Mutexes?
  991. * !!! FIXME: mutexes on Windows are for cross-process sync. CritSects are
  992. * !!! FIXME: mutexes for threads in a single process and are faster.
  993. */
  994. void *__PHYSFS_platformCreateMutex(void)
  995. {
  996. return((void *) CreateMutex(NULL, FALSE, NULL));
  997. } /* __PHYSFS_platformCreateMutex */
  998. void __PHYSFS_platformDestroyMutex(void *mutex)
  999. {
  1000. CloseHandle((HANDLE) mutex);
  1001. } /* __PHYSFS_platformDestroyMutex */
  1002. int __PHYSFS_platformGrabMutex(void *mutex)
  1003. {
  1004. return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
  1005. } /* __PHYSFS_platformGrabMutex */
  1006. void __PHYSFS_platformReleaseMutex(void *mutex)
  1007. {
  1008. ReleaseMutex((HANDLE) mutex);
  1009. } /* __PHYSFS_platformReleaseMutex */
  1010. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  1011. {
  1012. SYSTEMTIME st_utc;
  1013. SYSTEMTIME st_localtz;
  1014. TIME_ZONE_INFORMATION tzi;
  1015. DWORD tzid;
  1016. PHYSFS_sint64 retval;
  1017. struct tm tm;
  1018. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), winApiStrError(), -1);
  1019. tzid = GetTimeZoneInformation(&tzi);
  1020. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, winApiStrError(), -1);
  1021. /* (This API is unsupported and fails on non-NT systems. */
  1022. if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
  1023. {
  1024. /* do it by hand. Grumble... */
  1025. ULARGE_INTEGER ui64;
  1026. FILETIME new_ft;
  1027. ui64.LowPart = ft->dwLowDateTime;
  1028. ui64.HighPart = ft->dwHighDateTime;
  1029. if (tzid == TIME_ZONE_ID_STANDARD)
  1030. tzi.Bias += tzi.StandardBias;
  1031. else if (tzid == TIME_ZONE_ID_DAYLIGHT)
  1032. tzi.Bias += tzi.DaylightBias;
  1033. /* convert from minutes to 100-nanosecond increments... */
  1034. ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
  1035. /* Move it back into a FILETIME structure... */
  1036. new_ft.dwLowDateTime = ui64.LowPart;
  1037. new_ft.dwHighDateTime = ui64.HighPart;
  1038. /* Convert to something human-readable... */
  1039. if (!FileTimeToSystemTime(&new_ft, &st_localtz))
  1040. BAIL_MACRO(winApiStrError(), -1);
  1041. } /* if */
  1042. /* Convert to a format that mktime() can grok... */
  1043. tm.tm_sec = st_localtz.wSecond;
  1044. tm.tm_min = st_localtz.wMinute;
  1045. tm.tm_hour = st_localtz.wHour;
  1046. tm.tm_mday = st_localtz.wDay;
  1047. tm.tm_mon = st_localtz.wMonth - 1;
  1048. tm.tm_year = st_localtz.wYear - 1900;
  1049. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  1050. tm.tm_yday = -1;
  1051. tm.tm_isdst = -1;
  1052. /* Convert to a format PhysicsFS can grok... */
  1053. retval = (PHYSFS_sint64) mktime(&tm);
  1054. BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
  1055. return(retval);
  1056. } /* FileTimeToPhysfsTime */
  1057. PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
  1058. {
  1059. PHYSFS_sint64 retval = -1;
  1060. WIN32_FILE_ATTRIBUTE_DATA attr;
  1061. int rc = 0;
  1062. memset(&attr, '\0', sizeof (attr));
  1063. /* GetFileAttributesEx didn't show up until Win98 and NT4. */
  1064. if ((pGetFileAttributesExW != NULL) || (pGetFileAttributesExA != NULL))
  1065. {
  1066. WCHAR *wstr;
  1067. UTF8_TO_UNICODE_STACK_MACRO(wstr, fname);
  1068. if (wstr != NULL) /* if NULL, maybe the fallback will work. */
  1069. {
  1070. if (pGetFileAttributesExW != NULL) /* NT/XP/Vista/etc system. */
  1071. rc = pGetFileAttributesExW(wstr, GetFileExInfoStandard, &attr);
  1072. else /* Win98/ME system */
  1073. {
  1074. const int len = (int) (wStrLen(wstr) + 1);
  1075. char *cp = (char *) __PHYSFS_smallAlloc(len);
  1076. if (cp != NULL)
  1077. {
  1078. WideCharToMultiByte(CP_ACP, 0, wstr, len, cp, len, 0, 0);
  1079. rc = pGetFileAttributesExA(cp, GetFileExInfoStandard, &attr);
  1080. __PHYSFS_smallFree(cp);
  1081. } /* if */
  1082. } /* else */
  1083. __PHYSFS_smallFree(wstr);
  1084. } /* if */
  1085. } /* if */
  1086. if (rc) /* had API entry point and it worked. */
  1087. {
  1088. /* 0 return value indicates an error or not supported */
  1089. if ( (attr.ftLastWriteTime.dwHighDateTime != 0) ||
  1090. (attr.ftLastWriteTime.dwLowDateTime != 0) )
  1091. {
  1092. retval = FileTimeToPhysfsTime(&attr.ftLastWriteTime);
  1093. } /* if */
  1094. } /* if */
  1095. /* GetFileTime() has been in the Win32 API since the start. */
  1096. if (retval == -1) /* try a fallback... */
  1097. {
  1098. FILETIME ft;
  1099. BOOL rc;
  1100. const char *err;
  1101. WinApiFile *f = (WinApiFile *) __PHYSFS_platformOpenRead(fname);
  1102. BAIL_IF_MACRO(f == NULL, NULL, -1)
  1103. rc = GetFileTime(f->handle, NULL, NULL, &ft);
  1104. err = winApiStrError();
  1105. CloseHandle(f->handle);
  1106. allocator.Free(f);
  1107. BAIL_IF_MACRO(!rc, err, -1);
  1108. retval = FileTimeToPhysfsTime(&ft);
  1109. } /* if */
  1110. return(retval);
  1111. } /* __PHYSFS_platformGetLastModTime */
  1112. /* !!! FIXME: Don't use C runtime for allocators? */
  1113. int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
  1114. {
  1115. return(0); /* just use malloc() and friends. */
  1116. } /* __PHYSFS_platformSetDefaultAllocator */
  1117. #endif /* PHYSFS_PLATFORM_WINDOWS */
  1118. /* end of windows.c ... */