platform_windows.c 28 KB

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