platform_windows.c 27 KB

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