windows.c 41 KB

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