windows.c 41 KB

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