windows.c 42 KB

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