windows.c 42 KB

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