platform_windows.c 41 KB

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