windows.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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) (pos & 0xFFFFFFFF))
  24. #define HIGHORDER_UINT64(pos) ((PHYSFS_uint32) ((pos >> 32) & 0xFFFFFFFF))
  25. /*
  26. * Users without the platform SDK don't have this defined. The original docs
  27. * for SetFilePointer() just said to compare with 0xFFFFFFFF, so this should
  28. * work as desired.
  29. */
  30. #define PHYSFS_INVALID_SET_FILE_POINTER 0xFFFFFFFF
  31. /* just in case... */
  32. #define PHYSFS_INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
  33. /* Not defined before the Vista SDK. */
  34. #define PHYSFS_IO_REPARSE_TAG_SYMLINK 0xA000000C
  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. LPWSTR modpath = NULL;
  310. char *retval = NULL;
  311. while (1)
  312. {
  313. DWORD rc;
  314. void *ptr;
  315. if ( !(ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) )
  316. {
  317. allocator.Free(modpath);
  318. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  319. } /* if */
  320. modpath = (LPWSTR) ptr;
  321. rc = pGetModuleFileNameW(NULL, modpath, buflen);
  322. if (rc == 0)
  323. {
  324. allocator.Free(modpath);
  325. BAIL_MACRO(winApiStrError(), NULL);
  326. } /* if */
  327. if (rc < buflen)
  328. {
  329. buflen = rc;
  330. break;
  331. } /* if */
  332. buflen *= 2;
  333. } /* while */
  334. if (buflen > 0) /* just in case... */
  335. {
  336. WCHAR *ptr = (modpath + buflen) - 1;
  337. while (ptr != modpath)
  338. {
  339. if (*ptr == '\\')
  340. break;
  341. ptr--;
  342. } /* while */
  343. if ((ptr == modpath) && (*ptr != '\\'))
  344. __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
  345. else
  346. {
  347. *(ptr + 1) = '\0'; /* chop off filename. */
  348. retval = unicodeToUtf8Heap(modpath);
  349. } /* else */
  350. } /* else */
  351. allocator.Free(modpath);
  352. return(retval); /* w00t. */
  353. } /* getExePath */
  354. /*
  355. * Try to make use of GetUserProfileDirectoryW(), which isn't available on
  356. * some common variants of Win32. If we can't use this, we just punt and
  357. * use the physfs base dir for the user dir, too.
  358. *
  359. * On success, module-scope variable (userDir) will have a pointer to
  360. * a malloc()'d string of the user's profile dir, and a non-zero value is
  361. * returned. If we can't determine the profile dir, (userDir) will
  362. * be NULL, and zero is returned.
  363. */
  364. static int determineUserDir(void)
  365. {
  366. if (userDir != NULL)
  367. return(1); /* already good to go. */
  368. /*
  369. * GetUserProfileDirectoryW() is only available on NT 4.0 and later.
  370. * This means Win95/98/ME (and CE?) users have to do without, so for
  371. * them, we'll default to the base directory when we can't get the
  372. * function pointer. Since this is originally an NT API, we don't
  373. * offer a non-Unicode fallback.
  374. */
  375. if (pGetUserProfileDirectoryW != NULL)
  376. {
  377. HANDLE accessToken = NULL; /* Security handle to process */
  378. HANDLE processHandle = GetCurrentProcess();
  379. if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
  380. {
  381. DWORD psize = 0;
  382. WCHAR dummy = 0;
  383. LPWSTR wstr = NULL;
  384. BOOL rc = 0;
  385. /*
  386. * Should fail. Will write the size of the profile path in
  387. * psize. Also note that the second parameter can't be
  388. * NULL or the function fails.
  389. */
  390. rc = pGetUserProfileDirectoryW(accessToken, &dummy, &psize);
  391. assert(!rc); /* !!! FIXME: handle this gracefully. */
  392. /* Allocate memory for the profile directory */
  393. wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
  394. if (wstr != NULL)
  395. {
  396. if (pGetUserProfileDirectoryW(accessToken, wstr, &psize))
  397. userDir = unicodeToUtf8Heap(wstr);
  398. __PHYSFS_smallFree(wstr);
  399. } /* else */
  400. } /* if */
  401. CloseHandle(accessToken);
  402. } /* if */
  403. if (userDir == NULL) /* couldn't get profile for some reason. */
  404. {
  405. /* Might just be a non-NT system; resort to the basedir. */
  406. userDir = getExePath();
  407. BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
  408. } /* if */
  409. return(1); /* We made it: hit the showers. */
  410. } /* determineUserDir */
  411. static BOOL mediaInDrive(const char *drive)
  412. {
  413. UINT oldErrorMode;
  414. DWORD tmp;
  415. BOOL retval;
  416. /* Prevent windows warning message appearing when checking media size */
  417. oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  418. /* If this function succeeds, there's media in the drive */
  419. retval = GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0);
  420. /* Revert back to old windows error handler */
  421. SetErrorMode(oldErrorMode);
  422. return(retval);
  423. } /* mediaInDrive */
  424. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  425. {
  426. /* !!! FIXME: Can CD drives be non-drive letter paths? */
  427. /* !!! FIXME: (so can they be Unicode paths?) */
  428. char drive_str[4] = "x:\\";
  429. char ch;
  430. for (ch = 'A'; ch <= 'Z'; ch++)
  431. {
  432. drive_str[0] = ch;
  433. if (GetDriveType(drive_str) == DRIVE_CDROM && mediaInDrive(drive_str))
  434. cb(data, drive_str);
  435. } /* for */
  436. } /* __PHYSFS_platformDetectAvailableCDs */
  437. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  438. {
  439. if ((argv0 != NULL) && (strchr(argv0, '\\') != NULL))
  440. return(NULL); /* default behaviour can handle this. */
  441. return(getExePath());
  442. } /* __PHYSFS_platformCalcBaseDir */
  443. char *__PHYSFS_platformGetUserName(void)
  444. {
  445. DWORD bufsize = 0;
  446. char *retval = NULL;
  447. if (pGetUserNameW(NULL, &bufsize) == 0) /* This SHOULD fail. */
  448. {
  449. LPWSTR wbuf = (LPWSTR) __PHYSFS_smallAlloc(bufsize * sizeof (WCHAR));
  450. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  451. if (pGetUserNameW(wbuf, &bufsize) == 0) /* ?! */
  452. __PHYSFS_setError(winApiStrError());
  453. else
  454. retval = unicodeToUtf8Heap(wbuf);
  455. __PHYSFS_smallFree(wbuf);
  456. } /* if */
  457. return(retval);
  458. } /* __PHYSFS_platformGetUserName */
  459. char *__PHYSFS_platformGetUserDir(void)
  460. {
  461. char *retval = (char *) allocator.Malloc(strlen(userDir) + 1);
  462. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  463. strcpy(retval, userDir); /* calculated at init time. */
  464. return(retval);
  465. } /* __PHYSFS_platformGetUserDir */
  466. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  467. {
  468. return((PHYSFS_uint64) GetCurrentThreadId());
  469. } /* __PHYSFS_platformGetThreadID */
  470. static int doPlatformExists(LPWSTR wpath)
  471. {
  472. BAIL_IF_MACRO
  473. (
  474. pGetFileAttributesW(wpath) == PHYSFS_INVALID_FILE_ATTRIBUTES,
  475. winApiStrError(), 0
  476. );
  477. return(1);
  478. } /* doPlatformExists */
  479. int __PHYSFS_platformExists(const char *fname)
  480. {
  481. int retval = 0;
  482. LPWSTR wpath;
  483. UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
  484. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  485. retval = doPlatformExists(wpath);
  486. __PHYSFS_smallFree(wpath);
  487. return(retval);
  488. } /* __PHYSFS_platformExists */
  489. static int isSymlinkAttrs(const DWORD attr, const DWORD tag)
  490. {
  491. return ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) &&
  492. (tag == PHYSFS_IO_REPARSE_TAG_SYMLINK) );
  493. } /* isSymlinkAttrs */
  494. int __PHYSFS_platformIsSymLink(const char *fname)
  495. {
  496. /* !!! FIXME:
  497. * Windows Vista can have NTFS symlinks. Can older Windows releases have
  498. * them when talking to a network file server? What happens when you
  499. * mount a NTFS partition on XP that was plugged into a Vista install
  500. * that made a symlink?
  501. */
  502. int retval = 0;
  503. LPWSTR wpath;
  504. HANDLE dir;
  505. WIN32_FIND_DATAW entw;
  506. /* no unicode entry points? Probably no symlinks. */
  507. BAIL_IF_MACRO(pFindFirstFileW == NULL, NULL, 0);
  508. UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
  509. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  510. /* !!! FIXME: filter wildcard chars? */
  511. dir = pFindFirstFileW(wpath, &entw);
  512. if (dir != INVALID_HANDLE_VALUE)
  513. {
  514. retval = isSymlinkAttrs(entw.dwFileAttributes, entw.dwReserved0);
  515. FindClose(dir);
  516. } /* if */
  517. __PHYSFS_smallFree(wpath);
  518. return(retval);
  519. } /* __PHYSFS_platformIsSymlink */
  520. int __PHYSFS_platformIsDirectory(const char *fname)
  521. {
  522. int retval = 0;
  523. LPWSTR wpath;
  524. UTF8_TO_UNICODE_STACK_MACRO(wpath, fname);
  525. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  526. retval = ((pGetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY) != 0);
  527. __PHYSFS_smallFree(wpath);
  528. return(retval);
  529. } /* __PHYSFS_platformIsDirectory */
  530. char *__PHYSFS_platformCvtToDependent(const char *prepend,
  531. const char *dirName,
  532. const char *append)
  533. {
  534. int len = ((prepend) ? strlen(prepend) : 0) +
  535. ((append) ? strlen(append) : 0) +
  536. strlen(dirName) + 1;
  537. char *retval = (char *) allocator.Malloc(len);
  538. char *p;
  539. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  540. if (prepend)
  541. strcpy(retval, prepend);
  542. else
  543. retval[0] = '\0';
  544. strcat(retval, dirName);
  545. if (append)
  546. strcat(retval, append);
  547. for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
  548. *p = '\\';
  549. return(retval);
  550. } /* __PHYSFS_platformCvtToDependent */
  551. void __PHYSFS_platformEnumerateFiles(const char *dirname,
  552. int omitSymLinks,
  553. PHYSFS_EnumFilesCallback callback,
  554. const char *origdir,
  555. void *callbackdata)
  556. {
  557. const int unicode = (pFindFirstFileW != NULL) && (pFindNextFileW != NULL);
  558. HANDLE dir = INVALID_HANDLE_VALUE;
  559. WIN32_FIND_DATA ent;
  560. WIN32_FIND_DATAW entw;
  561. size_t len = strlen(dirname);
  562. char *searchPath = NULL;
  563. WCHAR *wSearchPath = NULL;
  564. char *utf8 = NULL;
  565. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  566. searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
  567. if (searchPath == NULL)
  568. return;
  569. /* Copy current dirname */
  570. strcpy(searchPath, dirname);
  571. /* if there's no '\\' at the end of the path, stick one in there. */
  572. if (searchPath[len - 1] != '\\')
  573. {
  574. searchPath[len++] = '\\';
  575. searchPath[len] = '\0';
  576. } /* if */
  577. /* Append the "*" to the end of the string */
  578. strcat(searchPath, "*");
  579. UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
  580. if (wSearchPath == NULL)
  581. return; /* oh well. */
  582. if (unicode)
  583. dir = pFindFirstFileW(wSearchPath, &entw);
  584. else
  585. {
  586. const int len = (int) (wStrLen(wSearchPath) + 1);
  587. char *cp = (char *) __PHYSFS_smallAlloc(len);
  588. if (cp != NULL)
  589. {
  590. WideCharToMultiByte(CP_ACP, 0, wSearchPath, len, cp, len, 0, 0);
  591. dir = FindFirstFileA(cp, &ent);
  592. __PHYSFS_smallFree(cp);
  593. } /* if */
  594. } /* else */
  595. __PHYSFS_smallFree(wSearchPath);
  596. __PHYSFS_smallFree(searchPath);
  597. if (dir == INVALID_HANDLE_VALUE)
  598. return;
  599. if (unicode)
  600. {
  601. do
  602. {
  603. const DWORD attr = entw.dwFileAttributes;
  604. const DWORD tag = entw.dwReserved0;
  605. const WCHAR *fn = entw.cFileName;
  606. if ((fn[0] == '.') && (fn[1] == '\0'))
  607. continue;
  608. if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
  609. continue;
  610. if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
  611. continue;
  612. utf8 = unicodeToUtf8Heap(fn);
  613. if (utf8 != NULL)
  614. {
  615. callback(callbackdata, origdir, utf8);
  616. allocator.Free(utf8);
  617. } /* if */
  618. } while (pFindNextFileW(dir, &entw) != 0);
  619. } /* if */
  620. else /* ANSI fallback. */
  621. {
  622. do
  623. {
  624. const DWORD attr = ent.dwFileAttributes;
  625. const DWORD tag = ent.dwReserved0;
  626. const char *fn = ent.cFileName;
  627. if ((fn[0] == '.') && (fn[1] == '\0'))
  628. continue;
  629. if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
  630. continue;
  631. if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
  632. continue;
  633. utf8 = codepageToUtf8Heap(fn);
  634. if (utf8 != NULL)
  635. {
  636. callback(callbackdata, origdir, utf8);
  637. allocator.Free(utf8);
  638. } /* if */
  639. } while (FindNextFileA(dir, &ent) != 0);
  640. } /* else */
  641. FindClose(dir);
  642. } /* __PHYSFS_platformEnumerateFiles */
  643. char *__PHYSFS_platformCurrentDir(void)
  644. {
  645. char *retval = NULL;
  646. WCHAR *wbuf = NULL;
  647. DWORD buflen = 0;
  648. buflen = pGetCurrentDirectoryW(buflen, NULL);
  649. wbuf = (WCHAR *) __PHYSFS_smallAlloc((buflen + 2) * sizeof (WCHAR));
  650. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  651. pGetCurrentDirectoryW(buflen, wbuf);
  652. if (wbuf[buflen - 2] == '\\')
  653. wbuf[buflen-1] = '\0'; /* just in case... */
  654. else
  655. {
  656. wbuf[buflen - 1] = '\\';
  657. wbuf[buflen] = '\0';
  658. } /* else */
  659. retval = unicodeToUtf8Heap(wbuf);
  660. __PHYSFS_smallFree(wbuf);
  661. return(retval);
  662. } /* __PHYSFS_platformCurrentDir */
  663. /* this could probably use a cleanup. */
  664. char *__PHYSFS_platformRealPath(const char *path)
  665. {
  666. /* !!! FIXME: this should return NULL if (path) doesn't exist? */
  667. /* !!! FIXME: Need to handle symlinks in Vista... */
  668. /* !!! FIXME: try GetFullPathName() instead? */
  669. /* this function should be UTF-8 clean. */
  670. char *retval = NULL;
  671. char *p = NULL;
  672. BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
  673. BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
  674. retval = (char *) allocator.Malloc(MAX_PATH);
  675. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  676. /*
  677. * If in \\server\path format, it's already an absolute path.
  678. * We'll need to check for "." and ".." dirs, though, just in case.
  679. */
  680. if ((path[0] == '\\') && (path[1] == '\\'))
  681. strcpy(retval, path);
  682. else
  683. {
  684. char *currentDir = __PHYSFS_platformCurrentDir();
  685. if (currentDir == NULL)
  686. {
  687. allocator.Free(retval);
  688. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  689. } /* if */
  690. if (path[1] == ':') /* drive letter specified? */
  691. {
  692. /*
  693. * Apparently, "D:mypath" is the same as "D:\\mypath" if
  694. * D: is not the current drive. However, if D: is the
  695. * current drive, then "D:mypath" is a relative path. Ugh.
  696. */
  697. if (path[2] == '\\') /* maybe an absolute path? */
  698. strcpy(retval, path);
  699. else /* definitely an absolute path. */
  700. {
  701. if (path[0] == currentDir[0]) /* current drive; relative. */
  702. {
  703. strcpy(retval, currentDir);
  704. strcat(retval, path + 2);
  705. } /* if */
  706. else /* not current drive; absolute. */
  707. {
  708. retval[0] = path[0];
  709. retval[1] = ':';
  710. retval[2] = '\\';
  711. strcpy(retval + 3, path + 2);
  712. } /* else */
  713. } /* else */
  714. } /* if */
  715. else /* no drive letter specified. */
  716. {
  717. if (path[0] == '\\') /* absolute path. */
  718. {
  719. retval[0] = currentDir[0];
  720. retval[1] = ':';
  721. strcpy(retval + 2, path);
  722. } /* if */
  723. else
  724. {
  725. strcpy(retval, currentDir);
  726. strcat(retval, path);
  727. } /* else */
  728. } /* else */
  729. allocator.Free(currentDir);
  730. } /* else */
  731. /* (whew.) Ok, now take out "." and ".." path entries... */
  732. p = retval;
  733. while ( (p = strstr(p, "\\.")) != NULL)
  734. {
  735. /* it's a "." entry that doesn't end the string. */
  736. if (p[2] == '\\')
  737. memmove(p + 1, p + 3, strlen(p + 3) + 1);
  738. /* it's a "." entry that ends the string. */
  739. else if (p[2] == '\0')
  740. p[0] = '\0';
  741. /* it's a ".." entry. */
  742. else if (p[2] == '.')
  743. {
  744. char *prevEntry = p - 1;
  745. while ((prevEntry != retval) && (*prevEntry != '\\'))
  746. prevEntry--;
  747. if (prevEntry == retval) /* make it look like a "." entry. */
  748. memmove(p + 1, p + 2, strlen(p + 2) + 1);
  749. else
  750. {
  751. if (p[3] != '\0') /* doesn't end string. */
  752. *prevEntry = '\0';
  753. else /* ends string. */
  754. memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
  755. p = prevEntry;
  756. } /* else */
  757. } /* else if */
  758. else
  759. {
  760. p++; /* look past current char. */
  761. } /* else */
  762. } /* while */
  763. /* shrink the retval's memory block if possible... */
  764. p = (char *) allocator.Realloc(retval, strlen(retval) + 1);
  765. if (p != NULL)
  766. retval = p;
  767. return(retval);
  768. } /* __PHYSFS_platformRealPath */
  769. int __PHYSFS_platformMkDir(const char *path)
  770. {
  771. WCHAR *wpath;
  772. DWORD rc;
  773. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  774. rc = pCreateDirectoryW(wpath, NULL);
  775. __PHYSFS_smallFree(wpath);
  776. BAIL_IF_MACRO(rc == 0, winApiStrError(), 0);
  777. return(1);
  778. } /* __PHYSFS_platformMkDir */
  779. /*
  780. * Get OS info and save the important parts.
  781. *
  782. * Returns non-zero if successful, otherwise it returns zero on failure.
  783. */
  784. static int getOSInfo(void)
  785. {
  786. OSVERSIONINFO osVerInfo; /* Information about the OS */
  787. osVerInfo.dwOSVersionInfoSize = sizeof(osVerInfo);
  788. BAIL_IF_MACRO(!GetVersionEx(&osVerInfo), winApiStrError(), 0);
  789. osHasUnicode = (osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS);
  790. return(1);
  791. } /* getOSInfo */
  792. int __PHYSFS_platformInit(void)
  793. {
  794. BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
  795. BAIL_IF_MACRO(!findApiSymbols(), NULL, 0);
  796. BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
  797. return(1); /* It's all good */
  798. } /* __PHYSFS_platformInit */
  799. int __PHYSFS_platformDeinit(void)
  800. {
  801. HANDLE *libs[] = { &libKernel32, &libUserEnv, &libAdvApi32, NULL };
  802. int i;
  803. allocator.Free(userDir);
  804. userDir = NULL;
  805. for (i = 0; libs[i] != NULL; i++)
  806. {
  807. const HANDLE lib = *(libs[i]);
  808. if (lib)
  809. FreeLibrary(lib);
  810. *(libs[i]) = NULL;
  811. } /* for */
  812. return(1); /* It's all good */
  813. } /* __PHYSFS_platformDeinit */
  814. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  815. {
  816. HANDLE fileHandle;
  817. WinApiFile *retval;
  818. WCHAR *wfname;
  819. UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
  820. BAIL_IF_MACRO(wfname == NULL, ERR_OUT_OF_MEMORY, NULL);
  821. fileHandle = pCreateFileW(wfname, mode, FILE_SHARE_READ, NULL,
  822. creation, FILE_ATTRIBUTE_NORMAL, NULL);
  823. __PHYSFS_smallFree(wfname);
  824. BAIL_IF_MACRO
  825. (
  826. fileHandle == INVALID_HANDLE_VALUE,
  827. winApiStrError(), NULL
  828. );
  829. retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
  830. if (retval == NULL)
  831. {
  832. CloseHandle(fileHandle);
  833. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  834. } /* if */
  835. retval->readonly = rdonly;
  836. retval->handle = fileHandle;
  837. return(retval);
  838. } /* doOpen */
  839. void *__PHYSFS_platformOpenRead(const char *filename)
  840. {
  841. return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
  842. } /* __PHYSFS_platformOpenRead */
  843. void *__PHYSFS_platformOpenWrite(const char *filename)
  844. {
  845. return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
  846. } /* __PHYSFS_platformOpenWrite */
  847. void *__PHYSFS_platformOpenAppend(const char *filename)
  848. {
  849. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  850. if (retval != NULL)
  851. {
  852. HANDLE h = ((WinApiFile *) retval)->handle;
  853. DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
  854. if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
  855. {
  856. const char *err = winApiStrError();
  857. CloseHandle(h);
  858. allocator.Free(retval);
  859. BAIL_MACRO(err, NULL);
  860. } /* if */
  861. } /* if */
  862. return(retval);
  863. } /* __PHYSFS_platformOpenAppend */
  864. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
  865. PHYSFS_uint32 size, PHYSFS_uint32 count)
  866. {
  867. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  868. DWORD CountOfBytesRead;
  869. PHYSFS_sint64 retval;
  870. /* Read data from the file */
  871. /* !!! FIXME: uint32 might be a greater # than DWORD */
  872. if(!ReadFile(Handle, buffer, count * size, &CountOfBytesRead, NULL))
  873. {
  874. BAIL_MACRO(winApiStrError(), -1);
  875. } /* if */
  876. else
  877. {
  878. /* Return the number of "objects" read. */
  879. /* !!! FIXME: What if not the right amount of bytes was read to make an object? */
  880. retval = CountOfBytesRead / size;
  881. } /* else */
  882. return(retval);
  883. } /* __PHYSFS_platformRead */
  884. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  885. PHYSFS_uint32 size, PHYSFS_uint32 count)
  886. {
  887. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  888. DWORD CountOfBytesWritten;
  889. PHYSFS_sint64 retval;
  890. /* Read data from the file */
  891. /* !!! FIXME: uint32 might be a greater # than DWORD */
  892. if(!WriteFile(Handle, buffer, count * size, &CountOfBytesWritten, NULL))
  893. {
  894. BAIL_MACRO(winApiStrError(), -1);
  895. } /* if */
  896. else
  897. {
  898. /* Return the number of "objects" read. */
  899. /* !!! FIXME: What if not the right number of bytes was written? */
  900. retval = CountOfBytesWritten / size;
  901. } /* else */
  902. return(retval);
  903. } /* __PHYSFS_platformWrite */
  904. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  905. {
  906. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  907. DWORD HighOrderPos;
  908. DWORD *pHighOrderPos;
  909. DWORD rc;
  910. /* Get the high order 32-bits of the position */
  911. HighOrderPos = HIGHORDER_UINT64(pos);
  912. /*
  913. * MSDN: "If you do not need the high-order 32 bits, this
  914. * pointer must be set to NULL."
  915. */
  916. pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
  917. /*
  918. * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
  919. * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
  920. * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
  921. * !!! FIXME: the sign extension of the value of lDistanceToMove.
  922. * !!! FIXME: Any other value will be rejected."
  923. */
  924. /* Move pointer "pos" count from start of file */
  925. rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
  926. pHighOrderPos, FILE_BEGIN);
  927. if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
  928. (GetLastError() != NO_ERROR) )
  929. {
  930. BAIL_MACRO(winApiStrError(), 0);
  931. } /* if */
  932. return(1); /* No error occured */
  933. } /* __PHYSFS_platformSeek */
  934. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  935. {
  936. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  937. DWORD HighPos = 0;
  938. DWORD LowPos;
  939. PHYSFS_sint64 retval;
  940. /* Get current position */
  941. LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
  942. if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
  943. (GetLastError() != NO_ERROR) )
  944. {
  945. BAIL_MACRO(winApiStrError(), 0);
  946. } /* if */
  947. else
  948. {
  949. /* Combine the high/low order to create the 64-bit position value */
  950. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  951. assert(retval >= 0);
  952. } /* else */
  953. return(retval);
  954. } /* __PHYSFS_platformTell */
  955. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  956. {
  957. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  958. DWORD SizeHigh;
  959. DWORD SizeLow;
  960. PHYSFS_sint64 retval;
  961. SizeLow = GetFileSize(Handle, &SizeHigh);
  962. if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
  963. (GetLastError() != NO_ERROR) )
  964. {
  965. BAIL_MACRO(winApiStrError(), -1);
  966. } /* if */
  967. else
  968. {
  969. /* Combine the high/low order to create the 64-bit position value */
  970. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  971. assert(retval >= 0);
  972. } /* else */
  973. return(retval);
  974. } /* __PHYSFS_platformFileLength */
  975. int __PHYSFS_platformEOF(void *opaque)
  976. {
  977. PHYSFS_sint64 FilePosition;
  978. int retval = 0;
  979. /* Get the current position in the file */
  980. if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
  981. {
  982. /* Non-zero if EOF is equal to the file length */
  983. retval = FilePosition == __PHYSFS_platformFileLength(opaque);
  984. } /* if */
  985. return(retval);
  986. } /* __PHYSFS_platformEOF */
  987. int __PHYSFS_platformFlush(void *opaque)
  988. {
  989. WinApiFile *fh = ((WinApiFile *) opaque);
  990. if (!fh->readonly)
  991. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), winApiStrError(), 0);
  992. return(1);
  993. } /* __PHYSFS_platformFlush */
  994. int __PHYSFS_platformClose(void *opaque)
  995. {
  996. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  997. BAIL_IF_MACRO(!CloseHandle(Handle), winApiStrError(), 0);
  998. allocator.Free(opaque);
  999. return(1);
  1000. } /* __PHYSFS_platformClose */
  1001. static int doPlatformDelete(LPWSTR wpath)
  1002. {
  1003. /* If filename is a folder */
  1004. if (pGetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)
  1005. {
  1006. BAIL_IF_MACRO(!pRemoveDirectoryW(wpath), winApiStrError(), 0);
  1007. } /* if */
  1008. else
  1009. {
  1010. BAIL_IF_MACRO(!pDeleteFileW(wpath), winApiStrError(), 0);
  1011. } /* else */
  1012. return(1); /* if you made it here, it worked. */
  1013. } /* doPlatformDelete */
  1014. int __PHYSFS_platformDelete(const char *path)
  1015. {
  1016. int retval = 0;
  1017. LPWSTR wpath;
  1018. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  1019. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  1020. retval = doPlatformDelete(wpath);
  1021. __PHYSFS_smallFree(wpath);
  1022. return(retval);
  1023. } /* __PHYSFS_platformDelete */
  1024. /*
  1025. * !!! FIXME: why aren't we using Critical Sections instead of Mutexes?
  1026. * !!! FIXME: mutexes on Windows are for cross-process sync. CritSects are
  1027. * !!! FIXME: mutexes for threads in a single process and are faster.
  1028. */
  1029. void *__PHYSFS_platformCreateMutex(void)
  1030. {
  1031. return((void *) CreateMutex(NULL, FALSE, NULL));
  1032. } /* __PHYSFS_platformCreateMutex */
  1033. void __PHYSFS_platformDestroyMutex(void *mutex)
  1034. {
  1035. CloseHandle((HANDLE) mutex);
  1036. } /* __PHYSFS_platformDestroyMutex */
  1037. int __PHYSFS_platformGrabMutex(void *mutex)
  1038. {
  1039. return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
  1040. } /* __PHYSFS_platformGrabMutex */
  1041. void __PHYSFS_platformReleaseMutex(void *mutex)
  1042. {
  1043. ReleaseMutex((HANDLE) mutex);
  1044. } /* __PHYSFS_platformReleaseMutex */
  1045. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  1046. {
  1047. SYSTEMTIME st_utc;
  1048. SYSTEMTIME st_localtz;
  1049. TIME_ZONE_INFORMATION tzi;
  1050. DWORD tzid;
  1051. PHYSFS_sint64 retval;
  1052. struct tm tm;
  1053. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), winApiStrError(), -1);
  1054. tzid = GetTimeZoneInformation(&tzi);
  1055. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, winApiStrError(), -1);
  1056. /* (This API is unsupported and fails on non-NT systems. */
  1057. if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
  1058. {
  1059. /* do it by hand. Grumble... */
  1060. ULARGE_INTEGER ui64;
  1061. FILETIME new_ft;
  1062. ui64.LowPart = ft->dwLowDateTime;
  1063. ui64.HighPart = ft->dwHighDateTime;
  1064. if (tzid == TIME_ZONE_ID_STANDARD)
  1065. tzi.Bias += tzi.StandardBias;
  1066. else if (tzid == TIME_ZONE_ID_DAYLIGHT)
  1067. tzi.Bias += tzi.DaylightBias;
  1068. /* convert from minutes to 100-nanosecond increments... */
  1069. ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
  1070. /* Move it back into a FILETIME structure... */
  1071. new_ft.dwLowDateTime = ui64.LowPart;
  1072. new_ft.dwHighDateTime = ui64.HighPart;
  1073. /* Convert to something human-readable... */
  1074. if (!FileTimeToSystemTime(&new_ft, &st_localtz))
  1075. BAIL_MACRO(winApiStrError(), -1);
  1076. } /* if */
  1077. /* Convert to a format that mktime() can grok... */
  1078. tm.tm_sec = st_localtz.wSecond;
  1079. tm.tm_min = st_localtz.wMinute;
  1080. tm.tm_hour = st_localtz.wHour;
  1081. tm.tm_mday = st_localtz.wDay;
  1082. tm.tm_mon = st_localtz.wMonth - 1;
  1083. tm.tm_year = st_localtz.wYear - 1900;
  1084. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  1085. tm.tm_yday = -1;
  1086. tm.tm_isdst = -1;
  1087. /* Convert to a format PhysicsFS can grok... */
  1088. retval = (PHYSFS_sint64) mktime(&tm);
  1089. BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
  1090. return(retval);
  1091. } /* FileTimeToPhysfsTime */
  1092. PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
  1093. {
  1094. PHYSFS_sint64 retval = -1;
  1095. WIN32_FILE_ATTRIBUTE_DATA attr;
  1096. int rc = 0;
  1097. memset(&attr, '\0', sizeof (attr));
  1098. /* GetFileAttributesEx didn't show up until Win98 and NT4. */
  1099. if ((pGetFileAttributesExW != NULL) || (pGetFileAttributesExA != NULL))
  1100. {
  1101. WCHAR *wstr;
  1102. UTF8_TO_UNICODE_STACK_MACRO(wstr, fname);
  1103. if (wstr != NULL) /* if NULL, maybe the fallback will work. */
  1104. {
  1105. if (pGetFileAttributesExW != NULL) /* NT/XP/Vista/etc system. */
  1106. rc = pGetFileAttributesExW(wstr, GetFileExInfoStandard, &attr);
  1107. else /* Win98/ME system */
  1108. {
  1109. const int len = (int) (wStrLen(wstr) + 1);
  1110. char *cp = (char *) __PHYSFS_smallAlloc(len);
  1111. if (cp != NULL)
  1112. {
  1113. WideCharToMultiByte(CP_ACP, 0, wstr, len, cp, len, 0, 0);
  1114. rc = pGetFileAttributesExA(cp, GetFileExInfoStandard, &attr);
  1115. __PHYSFS_smallFree(cp);
  1116. } /* if */
  1117. } /* else */
  1118. __PHYSFS_smallFree(wstr);
  1119. } /* if */
  1120. } /* if */
  1121. if (rc) /* had API entry point and it worked. */
  1122. {
  1123. /* 0 return value indicates an error or not supported */
  1124. if ( (attr.ftLastWriteTime.dwHighDateTime != 0) ||
  1125. (attr.ftLastWriteTime.dwLowDateTime != 0) )
  1126. {
  1127. retval = FileTimeToPhysfsTime(&attr.ftLastWriteTime);
  1128. } /* if */
  1129. } /* if */
  1130. /* GetFileTime() has been in the Win32 API since the start. */
  1131. if (retval == -1) /* try a fallback... */
  1132. {
  1133. FILETIME ft;
  1134. BOOL rc;
  1135. const char *err;
  1136. WinApiFile *f = (WinApiFile *) __PHYSFS_platformOpenRead(fname);
  1137. BAIL_IF_MACRO(f == NULL, NULL, -1)
  1138. rc = GetFileTime(f->handle, NULL, NULL, &ft);
  1139. err = winApiStrError();
  1140. CloseHandle(f->handle);
  1141. allocator.Free(f);
  1142. BAIL_IF_MACRO(!rc, err, -1);
  1143. retval = FileTimeToPhysfsTime(&ft);
  1144. } /* if */
  1145. return(retval);
  1146. } /* __PHYSFS_platformGetLastModTime */
  1147. /* !!! FIXME: Don't use C runtime for allocators? */
  1148. int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
  1149. {
  1150. return(0); /* just use malloc() and friends. */
  1151. } /* __PHYSFS_platformSetDefaultAllocator */
  1152. #endif /* PHYSFS_PLATFORM_WINDOWS */
  1153. /* end of windows.c ... */