platform_windows.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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_NOT_FOUND;
  111. case ERROR_PATH_NOT_FOUND: return PHYSFS_ERR_NOT_FOUND;
  112. case ERROR_DELETE_PENDING: return PHYSFS_ERR_NOT_FOUND;
  113. case ERROR_INVALID_DRIVE: return PHYSFS_ERR_NOT_FOUND;
  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_NOT_FOUND; */
  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_setErrorCode(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. allocator.Free(utf8);
  350. return retval;
  351. } /* __PHYSFS_platformCalcPrefDir */
  352. char *__PHYSFS_platformCalcUserDir(void)
  353. {
  354. typedef BOOL (WINAPI *fnGetUserProfDirW)(HANDLE, LPWSTR, LPDWORD);
  355. fnGetUserProfDirW pGetDir = NULL;
  356. HANDLE lib = NULL;
  357. HANDLE accessToken = NULL; /* Security handle to process */
  358. char *retval = NULL;
  359. lib = LoadLibraryA("userenv.dll");
  360. BAIL_IF_MACRO(!lib, errcodeFromWinApi(), NULL);
  361. pGetDir=(fnGetUserProfDirW) GetProcAddress(lib,"GetUserProfileDirectoryW");
  362. GOTO_IF_MACRO(!pGetDir, errcodeFromWinApi(), done);
  363. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &accessToken))
  364. GOTO_MACRO(errcodeFromWinApi(), done);
  365. else
  366. {
  367. DWORD psize = 0;
  368. WCHAR dummy = 0;
  369. LPWSTR wstr = NULL;
  370. BOOL rc = 0;
  371. /*
  372. * Should fail. Will write the size of the profile path in
  373. * psize. Also note that the second parameter can't be
  374. * NULL or the function fails.
  375. */
  376. rc = pGetDir(accessToken, &dummy, &psize);
  377. assert(!rc); /* !!! FIXME: handle this gracefully. */
  378. (void) rc;
  379. /* Allocate memory for the profile directory */
  380. wstr = (LPWSTR) __PHYSFS_smallAlloc((psize + 1) * sizeof (WCHAR));
  381. if (wstr != NULL)
  382. {
  383. if (pGetDir(accessToken, wstr, &psize))
  384. {
  385. /* Make sure it ends in a dirsep. We allocated +1 for this. */
  386. if (wstr[psize - 2] != '\\')
  387. {
  388. wstr[psize - 1] = '\\';
  389. wstr[psize - 0] = '\0';
  390. } /* if */
  391. retval = unicodeToUtf8Heap(wstr);
  392. } /* if */
  393. __PHYSFS_smallFree(wstr);
  394. } /* if */
  395. CloseHandle(accessToken);
  396. } /* if */
  397. done:
  398. FreeLibrary(lib);
  399. return retval; /* We made it: hit the showers. */
  400. } /* __PHYSFS_platformCalcUserDir */
  401. void *__PHYSFS_platformGetThreadID(void)
  402. {
  403. return ( (void *) ((size_t) GetCurrentThreadId()) );
  404. } /* __PHYSFS_platformGetThreadID */
  405. static int isSymlinkAttrs(const DWORD attr, const DWORD tag)
  406. {
  407. return ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) &&
  408. (tag == PHYSFS_IO_REPARSE_TAG_SYMLINK) );
  409. } /* isSymlinkAttrs */
  410. void __PHYSFS_platformEnumerateFiles(const char *dirname,
  411. PHYSFS_EnumFilesCallback callback,
  412. const char *origdir,
  413. void *callbackdata)
  414. {
  415. HANDLE dir = INVALID_HANDLE_VALUE;
  416. WIN32_FIND_DATAW entw;
  417. size_t len = strlen(dirname);
  418. char *searchPath = NULL;
  419. WCHAR *wSearchPath = NULL;
  420. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  421. searchPath = (char *) __PHYSFS_smallAlloc(len + 3);
  422. if (searchPath == NULL)
  423. return;
  424. /* Copy current dirname */
  425. strcpy(searchPath, dirname);
  426. /* if there's no '\\' at the end of the path, stick one in there. */
  427. if (searchPath[len - 1] != '\\')
  428. {
  429. searchPath[len++] = '\\';
  430. searchPath[len] = '\0';
  431. } /* if */
  432. /* Append the "*" to the end of the string */
  433. strcat(searchPath, "*");
  434. UTF8_TO_UNICODE_STACK_MACRO(wSearchPath, searchPath);
  435. if (!wSearchPath)
  436. return; /* oh well. */
  437. dir = FindFirstFileW(wSearchPath, &entw);
  438. __PHYSFS_smallFree(wSearchPath);
  439. __PHYSFS_smallFree(searchPath);
  440. if (dir == INVALID_HANDLE_VALUE)
  441. return;
  442. do
  443. {
  444. const DWORD attr = entw.dwFileAttributes;
  445. const DWORD tag = entw.dwReserved0;
  446. const WCHAR *fn = entw.cFileName;
  447. char *utf8;
  448. if ((fn[0] == '.') && (fn[1] == '\0'))
  449. continue;
  450. if ((fn[0] == '.') && (fn[1] == '.') && (fn[2] == '\0'))
  451. continue;
  452. utf8 = unicodeToUtf8Heap(fn);
  453. if (utf8 != NULL)
  454. {
  455. callback(callbackdata, origdir, utf8);
  456. allocator.Free(utf8);
  457. } /* if */
  458. } while (FindNextFileW(dir, &entw) != 0);
  459. FindClose(dir);
  460. } /* __PHYSFS_platformEnumerateFiles */
  461. int __PHYSFS_platformMkDir(const char *path)
  462. {
  463. WCHAR *wpath;
  464. DWORD rc;
  465. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  466. rc = CreateDirectoryW(wpath, NULL);
  467. __PHYSFS_smallFree(wpath);
  468. BAIL_IF_MACRO(rc == 0, errcodeFromWinApi(), 0);
  469. return 1;
  470. } /* __PHYSFS_platformMkDir */
  471. int __PHYSFS_platformInit(void)
  472. {
  473. return 1; /* It's all good */
  474. } /* __PHYSFS_platformInit */
  475. int __PHYSFS_platformDeinit(void)
  476. {
  477. if (detectCDThreadHandle)
  478. {
  479. if (detectCDHwnd)
  480. PostMessageW(detectCDHwnd, WM_QUIT, 0, 0);
  481. CloseHandle(detectCDThreadHandle);
  482. detectCDThreadHandle = NULL;
  483. initialDiscDetectionComplete = 0;
  484. drivesWithMediaBitmap = 0;
  485. } /* if */
  486. return 1; /* It's all good */
  487. } /* __PHYSFS_platformDeinit */
  488. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  489. {
  490. HANDLE fileh;
  491. WinApiFile *retval;
  492. WCHAR *wfname;
  493. UTF8_TO_UNICODE_STACK_MACRO(wfname, fname);
  494. BAIL_IF_MACRO(!wfname, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  495. fileh = CreateFileW(wfname, mode, FILE_SHARE_READ | FILE_SHARE_WRITE,
  496. NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
  497. __PHYSFS_smallFree(wfname);
  498. BAIL_IF_MACRO(fileh == INVALID_HANDLE_VALUE,errcodeFromWinApi(), NULL);
  499. retval = (WinApiFile *) allocator.Malloc(sizeof (WinApiFile));
  500. if (!retval)
  501. {
  502. CloseHandle(fileh);
  503. BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  504. } /* if */
  505. retval->readonly = rdonly;
  506. retval->handle = fileh;
  507. return retval;
  508. } /* doOpen */
  509. void *__PHYSFS_platformOpenRead(const char *filename)
  510. {
  511. return doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1);
  512. } /* __PHYSFS_platformOpenRead */
  513. void *__PHYSFS_platformOpenWrite(const char *filename)
  514. {
  515. return doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0);
  516. } /* __PHYSFS_platformOpenWrite */
  517. void *__PHYSFS_platformOpenAppend(const char *filename)
  518. {
  519. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  520. if (retval != NULL)
  521. {
  522. HANDLE h = ((WinApiFile *) retval)->handle;
  523. DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
  524. if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
  525. {
  526. const PHYSFS_ErrorCode err = errcodeFromWinApi();
  527. CloseHandle(h);
  528. allocator.Free(retval);
  529. BAIL_MACRO(err, NULL);
  530. } /* if */
  531. } /* if */
  532. return retval;
  533. } /* __PHYSFS_platformOpenAppend */
  534. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buf, PHYSFS_uint64 len)
  535. {
  536. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  537. PHYSFS_sint64 totalRead = 0;
  538. if (!__PHYSFS_ui64FitsAddressSpace(len))
  539. BAIL_MACRO(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  540. while (len > 0)
  541. {
  542. const DWORD thislen = (len > 0xFFFFFFFF) ? 0xFFFFFFFF : (DWORD) len;
  543. DWORD numRead = 0;
  544. if (!ReadFile(Handle, buf, thislen, &numRead, NULL))
  545. BAIL_MACRO(errcodeFromWinApi(), -1);
  546. len -= (PHYSFS_uint64) numRead;
  547. totalRead += (PHYSFS_sint64) numRead;
  548. if (numRead != thislen)
  549. break;
  550. } /* while */
  551. return totalRead;
  552. } /* __PHYSFS_platformRead */
  553. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  554. PHYSFS_uint64 len)
  555. {
  556. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  557. PHYSFS_sint64 totalWritten = 0;
  558. if (!__PHYSFS_ui64FitsAddressSpace(len))
  559. BAIL_MACRO(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  560. while (len > 0)
  561. {
  562. const DWORD thislen = (len > 0xFFFFFFFF) ? 0xFFFFFFFF : (DWORD) len;
  563. DWORD numWritten = 0;
  564. if (!WriteFile(Handle, buffer, thislen, &numWritten, NULL))
  565. BAIL_MACRO(errcodeFromWinApi(), -1);
  566. len -= (PHYSFS_uint64) numWritten;
  567. totalWritten += (PHYSFS_sint64) numWritten;
  568. if (numWritten != thislen)
  569. break;
  570. } /* while */
  571. return totalWritten;
  572. } /* __PHYSFS_platformWrite */
  573. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  574. {
  575. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  576. LONG HighOrderPos;
  577. PLONG pHighOrderPos;
  578. DWORD rc;
  579. /* Get the high order 32-bits of the position */
  580. HighOrderPos = HIGHORDER_UINT64(pos);
  581. /*
  582. * MSDN: "If you do not need the high-order 32 bits, this
  583. * pointer must be set to NULL."
  584. */
  585. pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
  586. /* Move pointer "pos" count from start of file */
  587. rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
  588. pHighOrderPos, FILE_BEGIN);
  589. if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
  590. (GetLastError() != NO_ERROR) )
  591. {
  592. BAIL_MACRO(errcodeFromWinApi(), 0);
  593. } /* if */
  594. return 1; /* No error occured */
  595. } /* __PHYSFS_platformSeek */
  596. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  597. {
  598. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  599. LONG HighPos = 0;
  600. DWORD LowPos;
  601. PHYSFS_sint64 retval;
  602. /* Get current position */
  603. LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
  604. if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
  605. (GetLastError() != NO_ERROR) )
  606. {
  607. BAIL_MACRO(errcodeFromWinApi(), -1);
  608. } /* if */
  609. else
  610. {
  611. /* Combine the high/low order to create the 64-bit position value */
  612. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  613. assert(retval >= 0);
  614. } /* else */
  615. return retval;
  616. } /* __PHYSFS_platformTell */
  617. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  618. {
  619. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  620. DWORD SizeHigh;
  621. DWORD SizeLow;
  622. PHYSFS_sint64 retval;
  623. SizeLow = GetFileSize(Handle, &SizeHigh);
  624. if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
  625. (GetLastError() != NO_ERROR) )
  626. {
  627. BAIL_MACRO(errcodeFromWinApi(), -1);
  628. } /* if */
  629. else
  630. {
  631. /* Combine the high/low order to create the 64-bit position value */
  632. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  633. assert(retval >= 0);
  634. } /* else */
  635. return retval;
  636. } /* __PHYSFS_platformFileLength */
  637. int __PHYSFS_platformFlush(void *opaque)
  638. {
  639. WinApiFile *fh = ((WinApiFile *) opaque);
  640. if (!fh->readonly)
  641. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), errcodeFromWinApi(), 0);
  642. return 1;
  643. } /* __PHYSFS_platformFlush */
  644. void __PHYSFS_platformClose(void *opaque)
  645. {
  646. HANDLE Handle = ((WinApiFile *) opaque)->handle;
  647. (void) CloseHandle(Handle); /* ignore errors. You should have flushed! */
  648. allocator.Free(opaque);
  649. } /* __PHYSFS_platformClose */
  650. static int doPlatformDelete(LPWSTR wpath)
  651. {
  652. const int isdir = (GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY);
  653. const BOOL rc = (isdir) ? RemoveDirectoryW(wpath) : DeleteFileW(wpath);
  654. BAIL_IF_MACRO(!rc, errcodeFromWinApi(), 0);
  655. return 1; /* if you made it here, it worked. */
  656. } /* doPlatformDelete */
  657. int __PHYSFS_platformDelete(const char *path)
  658. {
  659. int retval = 0;
  660. LPWSTR wpath = NULL;
  661. UTF8_TO_UNICODE_STACK_MACRO(wpath, path);
  662. BAIL_IF_MACRO(!wpath, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  663. retval = doPlatformDelete(wpath);
  664. __PHYSFS_smallFree(wpath);
  665. return retval;
  666. } /* __PHYSFS_platformDelete */
  667. void *__PHYSFS_platformCreateMutex(void)
  668. {
  669. LPCRITICAL_SECTION lpcs;
  670. lpcs = (LPCRITICAL_SECTION) allocator.Malloc(sizeof (CRITICAL_SECTION));
  671. BAIL_IF_MACRO(!lpcs, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  672. InitializeCriticalSection(lpcs);
  673. return lpcs;
  674. } /* __PHYSFS_platformCreateMutex */
  675. void __PHYSFS_platformDestroyMutex(void *mutex)
  676. {
  677. DeleteCriticalSection((LPCRITICAL_SECTION) mutex);
  678. allocator.Free(mutex);
  679. } /* __PHYSFS_platformDestroyMutex */
  680. int __PHYSFS_platformGrabMutex(void *mutex)
  681. {
  682. EnterCriticalSection((LPCRITICAL_SECTION) mutex);
  683. return 1;
  684. } /* __PHYSFS_platformGrabMutex */
  685. void __PHYSFS_platformReleaseMutex(void *mutex)
  686. {
  687. LeaveCriticalSection((LPCRITICAL_SECTION) mutex);
  688. } /* __PHYSFS_platformReleaseMutex */
  689. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  690. {
  691. SYSTEMTIME st_utc;
  692. SYSTEMTIME st_localtz;
  693. TIME_ZONE_INFORMATION tzi;
  694. DWORD tzid;
  695. PHYSFS_sint64 retval;
  696. struct tm tm;
  697. BOOL rc;
  698. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), errcodeFromWinApi(), -1);
  699. tzid = GetTimeZoneInformation(&tzi);
  700. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, errcodeFromWinApi(), -1);
  701. rc = SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz);
  702. BAIL_IF_MACRO(!rc, errcodeFromWinApi(), -1);
  703. /* Convert to a format that mktime() can grok... */
  704. tm.tm_sec = st_localtz.wSecond;
  705. tm.tm_min = st_localtz.wMinute;
  706. tm.tm_hour = st_localtz.wHour;
  707. tm.tm_mday = st_localtz.wDay;
  708. tm.tm_mon = st_localtz.wMonth - 1;
  709. tm.tm_year = st_localtz.wYear - 1900;
  710. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  711. tm.tm_yday = -1;
  712. tm.tm_isdst = -1;
  713. /* Convert to a format PhysicsFS can grok... */
  714. retval = (PHYSFS_sint64) mktime(&tm);
  715. BAIL_IF_MACRO(retval == -1, PHYSFS_ERR_OS_ERROR, -1);
  716. return retval;
  717. } /* FileTimeToPhysfsTime */
  718. int __PHYSFS_platformStat(const char *filename, PHYSFS_Stat *st)
  719. {
  720. WIN32_FILE_ATTRIBUTE_DATA winstat;
  721. WCHAR *wstr = NULL;
  722. DWORD err = 0;
  723. BOOL rc = 0;
  724. UTF8_TO_UNICODE_STACK_MACRO(wstr, filename);
  725. BAIL_IF_MACRO(!wstr, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  726. rc = GetFileAttributesExW(wstr, GetFileExInfoStandard, &winstat);
  727. err = (!rc) ? GetLastError() : 0;
  728. __PHYSFS_smallFree(wstr);
  729. BAIL_IF_MACRO(!rc, errcodeFromWinApiError(err), 0);
  730. st->modtime = FileTimeToPhysfsTime(&winstat.ftLastWriteTime);
  731. st->accesstime = FileTimeToPhysfsTime(&winstat.ftLastAccessTime);
  732. st->createtime = FileTimeToPhysfsTime(&winstat.ftCreationTime);
  733. if(winstat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  734. {
  735. st->filetype = PHYSFS_FILETYPE_DIRECTORY;
  736. st->filesize = 0;
  737. } /* if */
  738. else if(winstat.dwFileAttributes & (FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_DEVICE))
  739. {
  740. /* !!! FIXME: what are reparse points? */
  741. st->filetype = PHYSFS_FILETYPE_OTHER;
  742. /* !!! FIXME: don't rely on this */
  743. st->filesize = 0;
  744. } /* else if */
  745. /* !!! FIXME: check for symlinks on Vista. */
  746. else
  747. {
  748. st->filetype = PHYSFS_FILETYPE_REGULAR;
  749. st->filesize = (((PHYSFS_uint64) winstat.nFileSizeHigh) << 32) | winstat.nFileSizeLow;
  750. } /* else */
  751. st->readonly = ((winstat.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  752. return 1;
  753. } /* __PHYSFS_platformStat */
  754. /* !!! FIXME: Don't use C runtime for allocators? */
  755. int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
  756. {
  757. return 0; /* just use malloc() and friends. */
  758. } /* __PHYSFS_platformSetDefaultAllocator */
  759. #endif /* PHYSFS_PLATFORM_WINDOWS */
  760. /* end of windows.c ... */