1
0

platform_windows.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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 macro, since we manage this ourselves. */
  12. #ifdef UNICODE
  13. #undef UNICODE
  14. #endif
  15. #define WIN32_LEAN_AND_MEAN 1
  16. #include <windows.h>
  17. #include <userenv.h>
  18. #include <dbt.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. #ifndef _MSC_VER
  46. #define _snprintf snprintf
  47. #endif
  48. /* !!! FIXME: this is wrong for UTF-16. */
  49. static PHYSFS_uint64 wStrLen(const WCHAR *wstr)
  50. {
  51. PHYSFS_uint64 len = 0;
  52. while (*(wstr++))
  53. len++;
  54. return len;
  55. } /* wStrLen */
  56. static char *unicodeToUtf8Heap(const WCHAR *w_str)
  57. {
  58. char *retval = NULL;
  59. if (w_str != NULL)
  60. {
  61. void *ptr = NULL;
  62. const PHYSFS_uint64 len = (wStrLen(w_str) * 4) + 1;
  63. retval = allocator.Malloc(len);
  64. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  65. /* !!! FIXME: utf-16. */
  66. PHYSFS_utf8FromUcs2((const PHYSFS_uint16 *) w_str, retval, len);
  67. ptr = allocator.Realloc(retval, strlen(retval) + 1); /* shrink. */
  68. if (ptr != NULL)
  69. retval = (char *) ptr;
  70. } /* if */
  71. return retval;
  72. } /* unicodeToUtf8Heap */
  73. /* !!! FIXME: do we really need readonly? If not, do we need this struct? */
  74. typedef struct
  75. {
  76. HANDLE handle;
  77. int readonly;
  78. } WinApiFile;
  79. const char *__PHYSFS_platformDirSeparator = "\\";
  80. static char *userDir = NULL;
  81. static HANDLE libUserEnv = NULL;
  82. static HANDLE detectCDThreadHandle = NULL;
  83. static HWND detectCDHwnd = 0;
  84. static volatile int initialDiscDetectionComplete = 0;
  85. static volatile DWORD drivesWithMediaBitmap = 0;
  86. /*
  87. * Figure out what the last failing Windows API call was, and
  88. * generate a human-readable string for the error message.
  89. *
  90. * The return value is a static buffer that is overwritten with
  91. * each call to this function.
  92. */
  93. static const char *winApiStrErrorByNum(const DWORD err)
  94. {
  95. static char utf8buf[255];
  96. WCHAR msgbuf[255];
  97. WCHAR *ptr;
  98. DWORD rc = FormatMessageW(
  99. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  100. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  101. msgbuf, __PHYSFS_ARRAYLEN(msgbuf),
  102. NULL);
  103. if (rc == 0)
  104. msgbuf[0] = '\0'; /* oh well. */
  105. /* chop off newlines. */
  106. for (ptr = msgbuf; *ptr; ptr++)
  107. {
  108. if ((*ptr == '\n') || (*ptr == '\r'))
  109. {
  110. *ptr = '\0';
  111. break;
  112. } /* if */
  113. } /* for */
  114. /* may truncate, but oh well. */
  115. PHYSFS_utf8FromUcs2((PHYSFS_uint16 *) msgbuf, utf8buf, sizeof (utf8buf));
  116. return ((const char *) utf8buf);
  117. } /* winApiStrErrorByNum */
  118. static inline const char *winApiStrError(void)
  119. {
  120. return winApiStrErrorByNum(GetLastError());
  121. } /* winApiStrError */
  122. /*
  123. * On success, module-scope variable (userDir) will have a pointer to
  124. * a malloc()'d string of the user's profile dir, and a non-zero value is
  125. * returned. If we can't determine the profile dir, (userDir) will
  126. * be NULL, and zero is returned.
  127. */
  128. static int determineUserDir(void)
  129. {
  130. typedef BOOL (WINAPI *fnGetUserProfDirW)(HANDLE, LPWSTR, LPDWORD);
  131. fnGetUserProfDirW pGetDir = NULL;
  132. HANDLE accessToken = NULL; /* Security handle to process */
  133. if (userDir != NULL)
  134. return 1; /* already good to go. */
  135. pGetDir = (fnGetUserProfDirW)
  136. GetProcAddress(libUserEnv, "GetUserProfileDirectoryW");
  137. BAIL_IF_MACRO(pGetDir == NULL, winApiStrError(), 0);
  138. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &accessToken))
  139. BAIL_MACRO(winApiStrError(), 0);
  140. else
  141. {
  142. DWORD psize = 0;
  143. WCHAR dummy = 0;
  144. LPWSTR wstr = NULL;
  145. BOOL rc = 0;
  146. /*
  147. * Should fail. Will write the size of the profile path in
  148. * psize. Also note that the second parameter can't be
  149. * NULL or the function fails.
  150. */
  151. rc = pGetDir(accessToken, &dummy, &psize);
  152. assert(!rc); /* !!! FIXME: handle this gracefully. */
  153. (void) rc;
  154. /* Allocate memory for the profile directory */
  155. wstr = (LPWSTR) __PHYSFS_smallAlloc(psize * sizeof (WCHAR));
  156. if (wstr != NULL)
  157. {
  158. if (pGetDir(accessToken, wstr, &psize))
  159. userDir = unicodeToUtf8Heap(wstr);
  160. __PHYSFS_smallFree(wstr);
  161. } /* if */
  162. CloseHandle(accessToken);
  163. } /* if */
  164. return 1; /* We made it: hit the showers. */
  165. } /* determineUserDir */
  166. typedef BOOL (WINAPI *fnSTEM)(DWORD, LPDWORD b);
  167. static DWORD pollDiscDrives(void)
  168. {
  169. /* Try to use SetThreadErrorMode(), which showed up in Windows 7. */
  170. HANDLE lib = LoadLibraryA("kernel32.dll");
  171. fnSTEM stem = NULL;
  172. char drive[4] = { 'x', ':', '\\', '\0' };
  173. DWORD oldErrorMode = 0;
  174. DWORD drives = 0;
  175. DWORD i;
  176. if (lib)
  177. stem = (fnSTEM) GetProcAddress(lib, "SetThreadErrorMode");
  178. if (stem)
  179. stem(SEM_FAILCRITICALERRORS, &oldErrorMode);
  180. else
  181. oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  182. /* Do detection. This may block if a disc is spinning up. */
  183. for (i = 'A'; i <= 'Z'; i++)
  184. {
  185. DWORD tmp = 0;
  186. drive[0] = (char) i;
  187. if (GetDriveTypeA(drive) != DRIVE_CDROM)
  188. continue;
  189. /* If this function succeeds, there's media in the drive */
  190. if (GetVolumeInformationA(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0))
  191. drives |= (1 << (i - 'A'));
  192. } /* for */
  193. if (stem)
  194. stem(oldErrorMode, NULL);
  195. else
  196. SetErrorMode(oldErrorMode);
  197. if (lib)
  198. FreeLibrary(lib);
  199. return drives;
  200. } /* pollDiscDrives */
  201. static LRESULT CALLBACK detectCDWndProc(HWND hwnd, UINT msg,
  202. WPARAM wp, LPARAM lparam)
  203. {
  204. PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR) lparam;
  205. PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME) lparam;
  206. const int removed = (wp == DBT_DEVICEREMOVECOMPLETE);
  207. if (msg == WM_DESTROY)
  208. return 0;
  209. else if ((msg != WM_DEVICECHANGE) ||
  210. ((wp != DBT_DEVICEARRIVAL) && (wp != DBT_DEVICEREMOVECOMPLETE)) ||
  211. (lpdb->dbch_devicetype != DBT_DEVTYP_VOLUME) ||
  212. ((lpdbv->dbcv_flags & DBTF_MEDIA) == 0))
  213. {
  214. return DefWindowProcW(hwnd, msg, wp, lparam);
  215. } /* else if */
  216. if (removed)
  217. drivesWithMediaBitmap &= ~lpdbv->dbcv_unitmask;
  218. else
  219. drivesWithMediaBitmap |= lpdbv->dbcv_unitmask;
  220. return TRUE;
  221. } /* detectCDWndProc */
  222. static DWORD WINAPI detectCDThread(LPVOID lpParameter)
  223. {
  224. const char *classname = "PhysicsFSDetectCDCatcher";
  225. const char *winname = "PhysicsFSDetectCDMsgWindow";
  226. HINSTANCE hInstance = GetModuleHandleW(NULL);
  227. ATOM class_atom = 0;
  228. WNDCLASSEXA wce;
  229. MSG msg;
  230. memset(&wce, '\0', sizeof (wce));
  231. wce.cbSize = sizeof (wce);
  232. wce.lpfnWndProc = detectCDWndProc;
  233. wce.lpszClassName = classname;
  234. wce.hInstance = hInstance;
  235. class_atom = RegisterClassExA(&wce);
  236. if (class_atom == 0)
  237. {
  238. initialDiscDetectionComplete = 1; /* let main thread go on. */
  239. return 0;
  240. } /* if */
  241. detectCDHwnd = CreateWindowExA(0, classname, winname, WS_OVERLAPPEDWINDOW,
  242. CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
  243. CW_USEDEFAULT, HWND_DESKTOP, NULL, hInstance, NULL);
  244. if (detectCDHwnd == NULL)
  245. {
  246. initialDiscDetectionComplete = 1; /* let main thread go on. */
  247. UnregisterClassA(classname, hInstance);
  248. return 0;
  249. } /* if */
  250. /* We'll get events when discs come and go from now on. */
  251. /* Do initial detection, possibly blocking awhile... */
  252. drivesWithMediaBitmap = pollDiscDrives();
  253. initialDiscDetectionComplete = 1; /* let main thread go on. */
  254. do
  255. {
  256. const BOOL rc = GetMessageW(&msg, detectCDHwnd, 0, 0);
  257. if ((rc == 0) || (rc == -1))
  258. break; /* don't care if WM_QUIT or error break this loop. */
  259. TranslateMessage(&msg);
  260. DispatchMessageW(&msg);
  261. } while (1);
  262. /* we've been asked to quit. */
  263. DestroyWindow(detectCDHwnd);
  264. do
  265. {
  266. const BOOL rc = GetMessage(&msg, detectCDHwnd, 0, 0);
  267. if ((rc == 0) || (rc == -1))
  268. break;
  269. TranslateMessage(&msg);
  270. DispatchMessageW(&msg);
  271. } while (1);
  272. UnregisterClassA(classname, hInstance);
  273. return 0;
  274. } /* detectCDThread */
  275. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  276. {
  277. char drive_str[4] = { 'x', ':', '\\', '\0' };
  278. DWORD drives = 0;
  279. DWORD i;
  280. /*
  281. * If you poll a drive while a user is inserting a disc, the OS will
  282. * block this thread until the drive has spun up. So we swallow the risk
  283. * once for initial detection, and spin a thread that will get device
  284. * events thereafter, for apps that use this interface to poll for
  285. * disc insertion.
  286. */
  287. if (!detectCDThreadHandle)
  288. {
  289. initialDiscDetectionComplete = 0;
  290. detectCDThreadHandle = CreateThread(NULL,0,detectCDThread,NULL,0,NULL);
  291. if (detectCDThreadHandle == NULL)
  292. return; /* oh well. */
  293. while (!initialDiscDetectionComplete)
  294. Sleep(50);
  295. } /* if */
  296. drives = drivesWithMediaBitmap; /* whatever the thread has seen, we take. */
  297. for (i = 'A'; i <= 'Z'; i++)
  298. {
  299. if (drives & (1 << (i - 'A')))
  300. {
  301. drive_str[0] = (char) i;
  302. cb(data, drive_str);
  303. } /* if */
  304. } /* for */
  305. } /* __PHYSFS_platformDetectAvailableCDs */
  306. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  307. {
  308. DWORD buflen = 64;
  309. LPWSTR modpath = NULL;
  310. char *retval = NULL;
  311. while (1)
  312. {
  313. DWORD rc;
  314. void *ptr;
  315. if ( (ptr = allocator.Realloc(modpath, buflen*sizeof(WCHAR))) == NULL )
  316. {
  317. allocator.Free(modpath);
  318. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  319. } /* if */
  320. modpath = (LPWSTR) ptr;
  321. rc = GetModuleFileNameW(NULL, modpath, buflen);
  322. if (rc == 0)
  323. {
  324. allocator.Free(modpath);
  325. BAIL_MACRO(winApiStrError(), NULL);
  326. } /* if */
  327. if (rc < buflen)
  328. {
  329. buflen = rc;
  330. break;
  331. } /* if */
  332. buflen *= 2;
  333. } /* while */
  334. if (buflen > 0) /* just in case... */
  335. {
  336. WCHAR *ptr = (modpath + buflen) - 1;
  337. while (ptr != modpath)
  338. {
  339. if (*ptr == '\\')
  340. break;
  341. ptr--;
  342. } /* while */
  343. if ((ptr == modpath) && (*ptr != '\\'))
  344. __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
  345. else
  346. {
  347. *(ptr + 1) = '\0'; /* chop off filename. */
  348. retval = unicodeToUtf8Heap(modpath);
  349. } /* else */
  350. } /* else */
  351. allocator.Free(modpath);
  352. return retval; /* w00t. */
  353. } /* __PHYSFS_platformCalcBaseDir */
  354. char *__PHYSFS_platformGetUserName(void)
  355. {
  356. DWORD bufsize = 0;
  357. char *retval = NULL;
  358. if (GetUserNameW(NULL, &bufsize) == 0) /* This SHOULD fail. */
  359. {
  360. LPWSTR wbuf = (LPWSTR) __PHYSFS_smallAlloc(bufsize * sizeof (WCHAR));
  361. BAIL_IF_MACRO(wbuf == NULL, ERR_OUT_OF_MEMORY, NULL);
  362. if (GetUserNameW(wbuf, &bufsize) == 0) /* ?! */
  363. __PHYSFS_setError(winApiStrError());
  364. else
  365. retval = unicodeToUtf8Heap(wbuf);
  366. __PHYSFS_smallFree(wbuf);
  367. } /* if */
  368. return retval;
  369. } /* __PHYSFS_platformGetUserName */
  370. char *__PHYSFS_platformGetUserDir(void)
  371. {
  372. char *retval = (char *) allocator.Malloc(strlen(userDir) + 1);
  373. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  374. strcpy(retval, userDir); /* calculated at init time. */
  375. return retval;
  376. } /* __PHYSFS_platformGetUserDir */
  377. void *__PHYSFS_platformGetThreadID(void)
  378. {
  379. return ( (void *) ((size_t) GetCurrentThreadId()) );
  380. } /* __PHYSFS_platformGetThreadID */
  381. static int isSymlinkAttrs(const DWORD attr, const DWORD tag)
  382. {
  383. return ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) &&
  384. (tag == PHYSFS_IO_REPARSE_TAG_SYMLINK) );
  385. } /* isSymlinkAttrs */
  386. char *__PHYSFS_platformCvtToDependent(const char *prepend,
  387. const char *dirName,
  388. const char *append)
  389. {
  390. const size_t len = ((prepend) ? strlen(prepend) : 0) +
  391. ((append) ? strlen(append) : 0) +
  392. strlen(dirName) + 1;
  393. char *retval = (char *) allocator.Malloc(len);
  394. char *p;
  395. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  396. _snprintf(retval, len, "%s%s%s",
  397. prepend ? prepend : "", dirName, append ? append : "");
  398. for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
  399. *p = '\\';
  400. return retval;
  401. } /* __PHYSFS_platformCvtToDependent */
  402. void __PHYSFS_platformEnumerateFiles(const char *dirname,
  403. int omitSymLinks,
  404. PHYSFS_EnumFilesCallback callback,
  405. const char *origdir,
  406. void *callbackdata)
  407. {
  408. HANDLE dir = INVALID_HANDLE_VALUE;
  409. WIN32_FIND_DATAW entw;
  410. size_t len = strlen(dirname);
  411. char *searchPath = NULL;
  412. WCHAR *wSearchPath = NULL;
  413. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  414. searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
  415. if (searchPath == NULL)
  416. return;
  417. /* Copy current dirname */
  418. strcpy(searchPath, dirname);
  419. /* if there's no '\\' at the end of the path, stick one in there. */
  420. if (searchPath[len - 1] != '\\')
  421. {
  422. searchPath[len++] = '\\';
  423. searchPath[len] = '\0';
  424. } /* if */
  425. /* Append the "*" to the end of the string */
  426. strcat(searchPath, "*");
  427. UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
  428. if (wSearchPath == NULL)
  429. return; /* oh well. */
  430. dir = FindFirstFileW(wSearchPath, &entw);
  431. __PHYSFS_smallFree(wSearchPath);
  432. __PHYSFS_smallFree(searchPath);
  433. if (dir == INVALID_HANDLE_VALUE)
  434. return;
  435. do
  436. {
  437. const DWORD attr = entw.dwFileAttributes;
  438. const DWORD tag = entw.dwReserved0;
  439. const WCHAR *fn = entw.cFileName;
  440. char *utf8;
  441. if ((fn[0] == '.') && (fn[1] == '\0'))
  442. continue;
  443. if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
  444. continue;
  445. if ((omitSymLinks) && (isSymlinkAttrs(attr, tag)))
  446. continue;
  447. utf8 = unicodeToUtf8Heap(fn);
  448. if (utf8 != NULL)
  449. {
  450. callback(callbackdata, origdir, utf8);
  451. allocator.Free(utf8);
  452. } /* if */
  453. } while (FindNextFileW(dir, &entw) != 0);
  454. FindClose(dir);
  455. } /* __PHYSFS_platformEnumerateFiles */
  456. int __PHYSFS_platformMkDir(const char *path)
  457. {
  458. WCHAR *wpath;
  459. DWORD rc;
  460. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  461. rc = CreateDirectoryW(wpath, NULL);
  462. __PHYSFS_smallFree(wpath);
  463. BAIL_IF_MACRO(rc == 0, winApiStrError(), 0);
  464. return 1;
  465. } /* __PHYSFS_platformMkDir */
  466. int __PHYSFS_platformInit(void)
  467. {
  468. libUserEnv = LoadLibraryA("userenv.dll");
  469. BAIL_IF_MACRO(libUserEnv == NULL, winApiStrError(), 0);
  470. /* !!! FIXME: why do we precalculate this? */
  471. BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
  472. return 1; /* It's all good */
  473. } /* __PHYSFS_platformInit */
  474. int __PHYSFS_platformDeinit(void)
  475. {
  476. if (detectCDThreadHandle != NULL)
  477. {
  478. if (detectCDHwnd)
  479. PostMessageW(detectCDHwnd, WM_QUIT, 0, 0);
  480. CloseHandle(detectCDThreadHandle);
  481. detectCDThreadHandle = NULL;
  482. initialDiscDetectionComplete = 0;
  483. drivesWithMediaBitmap = 0;
  484. } /* if */
  485. if (libUserEnv)
  486. FreeLibrary(libUserEnv);
  487. libUserEnv = NULL;
  488. allocator.Free(userDir);
  489. userDir = NULL;
  490. return 1; /* It's all good */
  491. } /* __PHYSFS_platformDeinit */
  492. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  493. {
  494. HANDLE fileh;
  495. WinApiFile *retval;
  496. WCHAR *wfname;
  497. UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
  498. BAIL_IF_MACRO(wfname == NULL, ERR_OUT_OF_MEMORY, NULL);
  499. fileh = CreateFileW(wfname, mode, FILE_SHARE_READ | FILE_SHARE_WRITE,
  500. NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
  501. __PHYSFS_smallFree(wfname);
  502. BAIL_IF_MACRO(fileh == INVALID_HANDLE_VALUE,winApiStrError(), NULL);
  503. retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
  504. if (retval == NULL)
  505. {
  506. CloseHandle(fileh);
  507. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  508. } /* if */
  509. retval->readonly = rdonly;
  510. retval->handle = fileh;
  511. return retval;
  512. } /* doOpen */
  513. void *__PHYSFS_platformOpenRead(const char *filename)
  514. {
  515. return doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1);
  516. } /* __PHYSFS_platformOpenRead */
  517. void *__PHYSFS_platformOpenWrite(const char *filename)
  518. {
  519. return doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0);
  520. } /* __PHYSFS_platformOpenWrite */
  521. void *__PHYSFS_platformOpenAppend(const char *filename)
  522. {
  523. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  524. if (retval != NULL)
  525. {
  526. HANDLE h = ((WinApiFile *) retval)->handle;
  527. DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
  528. if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
  529. {
  530. const char *err = winApiStrError();
  531. CloseHandle(h);
  532. allocator.Free(retval);
  533. BAIL_MACRO(err, NULL);
  534. } /* if */
  535. } /* if */
  536. return retval;
  537. } /* __PHYSFS_platformOpenAppend */
  538. /* !!! FIXME: this function fails if len > 0xFFFFFFFF. */
  539. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buf, PHYSFS_uint64 len)
  540. {
  541. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  542. DWORD CountOfBytesRead = 0;
  543. BAIL_IF_MACRO(!__PHYSFS_ui64FitsAddressSpace(len),ERR_INVALID_ARGUMENT,-1);
  544. if(!ReadFile(Handle, buf, (DWORD) len, &CountOfBytesRead, NULL))
  545. BAIL_MACRO(winApiStrError(), -1);
  546. return (PHYSFS_sint64) CountOfBytesRead;
  547. } /* __PHYSFS_platformRead */
  548. /* !!! FIXME: this function fails if len > 0xFFFFFFFF. */
  549. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  550. PHYSFS_uint64 len)
  551. {
  552. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  553. DWORD CountOfBytesWritten = 0;
  554. BAIL_IF_MACRO(!__PHYSFS_ui64FitsAddressSpace(len),ERR_INVALID_ARGUMENT,-1);
  555. if(!WriteFile(Handle, buffer, (DWORD) len, &CountOfBytesWritten, NULL))
  556. BAIL_MACRO(winApiStrError(), -1);
  557. return (PHYSFS_sint64) CountOfBytesWritten;
  558. } /* __PHYSFS_platformWrite */
  559. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  560. {
  561. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  562. LONG HighOrderPos;
  563. PLONG pHighOrderPos;
  564. DWORD rc;
  565. /* Get the high order 32-bits of the position */
  566. HighOrderPos = HIGHORDER_UINT64(pos);
  567. /*
  568. * MSDN: "If you do not need the high-order 32 bits, this
  569. * pointer must be set to NULL."
  570. */
  571. pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
  572. /*
  573. * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
  574. * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
  575. * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
  576. * !!! FIXME: the sign extension of the value of lDistanceToMove.
  577. * !!! FIXME: Any other value will be rejected."
  578. */
  579. /* Move pointer "pos" count from start of file */
  580. rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
  581. pHighOrderPos, FILE_BEGIN);
  582. if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
  583. (GetLastError() != NO_ERROR) )
  584. {
  585. BAIL_MACRO(winApiStrError(), 0);
  586. } /* if */
  587. return 1; /* No error occured */
  588. } /* __PHYSFS_platformSeek */
  589. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  590. {
  591. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  592. LONG HighPos = 0;
  593. DWORD LowPos;
  594. PHYSFS_sint64 retval;
  595. /* Get current position */
  596. LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
  597. if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
  598. (GetLastError() != NO_ERROR) )
  599. {
  600. BAIL_MACRO(winApiStrError(), -1);
  601. } /* if */
  602. else
  603. {
  604. /* Combine the high/low order to create the 64-bit position value */
  605. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  606. assert(retval >= 0);
  607. } /* else */
  608. return retval;
  609. } /* __PHYSFS_platformTell */
  610. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  611. {
  612. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  613. DWORD SizeHigh;
  614. DWORD SizeLow;
  615. PHYSFS_sint64 retval;
  616. SizeLow = GetFileSize(Handle, &SizeHigh);
  617. if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
  618. (GetLastError() != NO_ERROR) )
  619. {
  620. BAIL_MACRO(winApiStrError(), -1);
  621. } /* if */
  622. else
  623. {
  624. /* Combine the high/low order to create the 64-bit position value */
  625. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  626. assert(retval >= 0);
  627. } /* else */
  628. return retval;
  629. } /* __PHYSFS_platformFileLength */
  630. int __PHYSFS_platformFlush(void *opaque)
  631. {
  632. WinApiFile *fh = ((WinApiFile *) opaque);
  633. if (!fh->readonly)
  634. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), winApiStrError(), 0);
  635. return 1;
  636. } /* __PHYSFS_platformFlush */
  637. void __PHYSFS_platformClose(void *opaque)
  638. {
  639. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  640. (void) CloseHandle(Handle); /* ignore errors. You should have flushed! */
  641. allocator.Free(opaque);
  642. } /* __PHYSFS_platformClose */
  643. static int doPlatformDelete(LPWSTR wpath)
  644. {
  645. const int isdir = (GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY);
  646. const BOOL rc = (isdir) ? RemoveDirectoryW(wpath) : DeleteFileW(wpath);
  647. BAIL_IF_MACRO(!rc, winApiStrError(), 0);
  648. return 1; /* if you made it here, it worked. */
  649. } /* doPlatformDelete */
  650. int __PHYSFS_platformDelete(const char *path)
  651. {
  652. int retval = 0;
  653. LPWSTR wpath = NULL;
  654. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  655. BAIL_IF_MACRO(wpath == NULL, ERR_OUT_OF_MEMORY, 0);
  656. retval = doPlatformDelete(wpath);
  657. __PHYSFS_smallFree(wpath);
  658. return retval;
  659. } /* __PHYSFS_platformDelete */
  660. /*
  661. * !!! FIXME: why aren't we using Critical Sections instead of Mutexes?
  662. * !!! FIXME: mutexes on Windows are for cross-process sync. CritSects are
  663. * !!! FIXME: mutexes for threads in a single process and are faster.
  664. */
  665. void *__PHYSFS_platformCreateMutex(void)
  666. {
  667. return ((void *) CreateMutex(NULL, FALSE, NULL));
  668. } /* __PHYSFS_platformCreateMutex */
  669. void __PHYSFS_platformDestroyMutex(void *mutex)
  670. {
  671. CloseHandle((HANDLE) mutex);
  672. } /* __PHYSFS_platformDestroyMutex */
  673. int __PHYSFS_platformGrabMutex(void *mutex)
  674. {
  675. return (WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
  676. } /* __PHYSFS_platformGrabMutex */
  677. void __PHYSFS_platformReleaseMutex(void *mutex)
  678. {
  679. ReleaseMutex((HANDLE) mutex);
  680. } /* __PHYSFS_platformReleaseMutex */
  681. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  682. {
  683. SYSTEMTIME st_utc;
  684. SYSTEMTIME st_localtz;
  685. TIME_ZONE_INFORMATION tzi;
  686. DWORD tzid;
  687. PHYSFS_sint64 retval;
  688. struct tm tm;
  689. BOOL rc;
  690. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), winApiStrError(), -1);
  691. tzid = GetTimeZoneInformation(&tzi);
  692. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, winApiStrError(), -1);
  693. rc = SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz);
  694. BAIL_IF_MACRO(!rc, winApiStrError(), -1);
  695. /* Convert to a format that mktime() can grok... */
  696. tm.tm_sec = st_localtz.wSecond;
  697. tm.tm_min = st_localtz.wMinute;
  698. tm.tm_hour = st_localtz.wHour;
  699. tm.tm_mday = st_localtz.wDay;
  700. tm.tm_mon = st_localtz.wMonth - 1;
  701. tm.tm_year = st_localtz.wYear - 1900;
  702. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  703. tm.tm_yday = -1;
  704. tm.tm_isdst = -1;
  705. /* Convert to a format PhysicsFS can grok... */
  706. retval = (PHYSFS_sint64) mktime(&tm);
  707. BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
  708. return retval;
  709. } /* FileTimeToPhysfsTime */
  710. int __PHYSFS_platformStat(const char *filename, int *exists, PHYSFS_Stat *stat)
  711. {
  712. WIN32_FILE_ATTRIBUTE_DATA winstat;
  713. WCHAR *wstr = NULL;
  714. DWORD err = 0;
  715. BOOL rc = 0;
  716. UTF8_TO_UNICODE_STACK_MACRO(wstr, filename);
  717. BAIL_IF_MACRO(wstr == NULL, ERR_OUT_OF_MEMORY, 0);
  718. rc = GetFileAttributesExW(wstr, GetFileExInfoStandard, &winstat);
  719. err = (!rc) ? GetLastError() : 0;
  720. *exists = ((err != ERROR_FILE_NOT_FOUND) && (err != ERROR_PATH_NOT_FOUND));
  721. __PHYSFS_smallFree(wstr);
  722. BAIL_IF_MACRO(!rc, winApiStrErrorByNum(err), 0);
  723. stat->modtime = FileTimeToPhysfsTime(&winstat.ftLastWriteTime);
  724. stat->accesstime = FileTimeToPhysfsTime(&winstat.ftLastAccessTime);
  725. stat->createtime = FileTimeToPhysfsTime(&winstat.ftCreationTime);
  726. if(winstat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  727. {
  728. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  729. stat->filesize = 0;
  730. } /* if */
  731. else if(winstat.dwFileAttributes & (FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_DEVICE))
  732. {
  733. /* !!! FIXME: what are reparse points? */
  734. stat->filetype = PHYSFS_FILETYPE_OTHER;
  735. /* !!! FIXME: don't rely on this */
  736. stat->filesize = 0;
  737. } /* else if */
  738. /* !!! FIXME: check for symlinks on Vista. */
  739. else
  740. {
  741. stat->filetype = PHYSFS_FILETYPE_REGULAR;
  742. stat->filesize = (((PHYSFS_uint64) winstat.nFileSizeHigh) << 32) | winstat.nFileSizeLow;
  743. } /* else */
  744. stat->readonly = ((winstat.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  745. return 1;
  746. } /* __PHYSFS_platformStat */
  747. /* !!! FIXME: Don't use C runtime for allocators? */
  748. int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
  749. {
  750. return 0; /* just use malloc() and friends. */
  751. } /* __PHYSFS_platformSetDefaultAllocator */
  752. #endif /* PHYSFS_PLATFORM_WINDOWS */
  753. /* end of windows.c ... */