platform_windows.c 27 KB

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