windows.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. #include <windows.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <errno.h>
  16. #include <ctype.h>
  17. #include <time.h>
  18. #include "physfs_internal.h"
  19. #define LOWORDER_UINT64(pos) (PHYSFS_uint32) \
  20. (pos & 0x00000000FFFFFFFF)
  21. #define HIGHORDER_UINT64(pos) (PHYSFS_uint32) \
  22. (((pos & 0xFFFFFFFF00000000) >> 32) & 0x00000000FFFFFFFF)
  23. /* GetUserProfileDirectory() is only available on >= NT4 (no 9x/ME systems!) */
  24. typedef BOOL (STDMETHODCALLTYPE FAR * LPFNGETUSERPROFILEDIR) (
  25. HANDLE hToken,
  26. LPTSTR lpProfileDir,
  27. LPDWORD lpcchSize);
  28. /* GetFileAttributesEx() is only available on >= Win98 or WinNT4 ... */
  29. typedef BOOL (STDMETHODCALLTYPE FAR * LPFNGETFILEATTRIBUTESEX) (
  30. LPCTSTR lpFileName,
  31. GET_FILEEX_INFO_LEVELS fInfoLevelId,
  32. LPVOID lpFileInformation);
  33. typedef struct
  34. {
  35. HANDLE handle;
  36. int readonly;
  37. } win32file;
  38. const char *__PHYSFS_platformDirSeparator = "\\";
  39. static LPFNGETFILEATTRIBUTESEX pGetFileAttributesEx = NULL;
  40. static HANDLE libKernel32 = NULL;
  41. static char *userDir = NULL;
  42. /*
  43. * Users without the platform SDK don't have this defined. The original docs
  44. * for SetFilePointer() just said to compare with 0xFFFFFFFF, so this should
  45. * work as desired.
  46. */
  47. #define PHYSFS_INVALID_SET_FILE_POINTER 0xFFFFFFFF
  48. /* just in case... */
  49. #define PHYSFS_INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
  50. /*
  51. * Figure out what the last failing Win32 API call was, and
  52. * generate a human-readable string for the error message.
  53. *
  54. * The return value is a static buffer that is overwritten with
  55. * each call to this function.
  56. */
  57. static const char *win32strerror(void)
  58. {
  59. static TCHAR msgbuf[255];
  60. TCHAR *ptr = msgbuf;
  61. FormatMessage(
  62. FORMAT_MESSAGE_FROM_SYSTEM |
  63. FORMAT_MESSAGE_IGNORE_INSERTS,
  64. NULL,
  65. GetLastError(),
  66. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
  67. msgbuf,
  68. sizeof (msgbuf) / sizeof (TCHAR),
  69. NULL
  70. );
  71. /* chop off newlines. */
  72. for (ptr = msgbuf; *ptr; ptr++)
  73. {
  74. if ((*ptr == '\n') || (*ptr == '\r'))
  75. {
  76. *ptr = ' ';
  77. break;
  78. } /* if */
  79. } /* for */
  80. return((const char *) msgbuf);
  81. } /* win32strerror */
  82. static char *getExePath(const char *argv0)
  83. {
  84. DWORD buflen;
  85. int success = 0;
  86. char *ptr = NULL;
  87. char *retval = (char *) allocator.Malloc(sizeof (TCHAR) * (MAX_PATH + 1));
  88. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  89. retval[0] = '\0';
  90. /* !!! FIXME: don't preallocate here? */
  91. /* !!! FIXME: use smallAlloc? */
  92. buflen = GetModuleFileName(NULL, retval, MAX_PATH + 1);
  93. if (buflen <= 0)
  94. __PHYSFS_setError(win32strerror());
  95. else
  96. {
  97. retval[buflen] = '\0'; /* does API always null-terminate this? */
  98. /* make sure the string was not truncated. */
  99. if (__PHYSFS_stricmpASCII(&retval[buflen - 4], ".exe") != 0)
  100. __PHYSFS_setError(ERR_GETMODFN_TRUNC);
  101. else
  102. {
  103. ptr = strrchr(retval, '\\');
  104. if (ptr == NULL)
  105. __PHYSFS_setError(ERR_GETMODFN_NO_DIR);
  106. else
  107. {
  108. *(ptr + 1) = '\0'; /* chop off filename. */
  109. success = 1;
  110. } /* else */
  111. } /* else */
  112. } /* else */
  113. /* if any part of the previous approach failed, try SearchPath()... */
  114. if (!success)
  115. {
  116. if (argv0 == NULL)
  117. __PHYSFS_setError(ERR_ARGV0_IS_NULL);
  118. else
  119. {
  120. buflen = SearchPath(NULL, argv0, NULL, MAX_PATH+1, retval, &ptr);
  121. if (buflen == 0)
  122. __PHYSFS_setError(win32strerror());
  123. else if (buflen > MAX_PATH)
  124. __PHYSFS_setError(ERR_SEARCHPATH_TRUNC);
  125. else
  126. success = 1;
  127. } /* else */
  128. } /* if */
  129. if (!success)
  130. {
  131. allocator.Free(retval);
  132. return(NULL); /* physfs error message will be set, above. */
  133. } /* if */
  134. /* free up the bytes we didn't actually use. */
  135. ptr = (char *) allocator.Realloc(retval, strlen(retval) + 1);
  136. if (ptr != NULL)
  137. retval = ptr;
  138. return(retval); /* w00t. */
  139. } /* getExePath */
  140. /*
  141. * Try to make use of GetUserProfileDirectory(), which isn't available on
  142. * some common variants of Win32. If we can't use this, we just punt and
  143. * use the physfs base dir for the user dir, too.
  144. *
  145. * On success, module-scope variable (userDir) will have a pointer to
  146. * a malloc()'d string of the user's profile dir, and a non-zero value is
  147. * returned. If we can't determine the profile dir, (userDir) will
  148. * be NULL, and zero is returned.
  149. */
  150. static int determineUserDir(void)
  151. {
  152. DWORD psize = 0;
  153. char dummy[1];
  154. BOOL rc = 0;
  155. HANDLE processHandle; /* Current process handle */
  156. HANDLE accessToken = NULL; /* Security handle to process */
  157. LPFNGETUSERPROFILEDIR GetUserProfileDirectory;
  158. HMODULE lib;
  159. assert(userDir == NULL);
  160. /*
  161. * GetUserProfileDirectory() is only available on NT 4.0 and later.
  162. * This means Win95/98/ME (and CE?) users have to do without, so for
  163. * them, we'll default to the base directory when we can't get the
  164. * function pointer.
  165. */
  166. lib = LoadLibrary("userenv.dll");
  167. if (lib)
  168. {
  169. /* !!! FIXME: Handle Unicode? */
  170. GetUserProfileDirectory = (LPFNGETUSERPROFILEDIR)
  171. GetProcAddress(lib, "GetUserProfileDirectoryA");
  172. if (GetUserProfileDirectory)
  173. {
  174. processHandle = GetCurrentProcess();
  175. if (OpenProcessToken(processHandle, TOKEN_QUERY, &accessToken))
  176. {
  177. /*
  178. * Should fail. Will write the size of the profile path in
  179. * psize. Also note that the second parameter can't be
  180. * NULL or the function fails.
  181. */
  182. rc = GetUserProfileDirectory(accessToken, dummy, &psize);
  183. assert(!rc); /* success?! */
  184. /* Allocate memory for the profile directory */
  185. userDir = (char *) allocator.Malloc(psize);
  186. if (userDir != NULL)
  187. {
  188. if (!GetUserProfileDirectory(accessToken, userDir, &psize))
  189. {
  190. allocator.Free(userDir);
  191. userDir = NULL;
  192. } /* if */
  193. } /* else */
  194. } /* if */
  195. CloseHandle(accessToken);
  196. } /* if */
  197. FreeLibrary(lib);
  198. } /* if */
  199. if (userDir == NULL) /* couldn't get profile for some reason. */
  200. {
  201. /* Might just be a non-NT system; resort to the basedir. */
  202. userDir = getExePath(NULL);
  203. BAIL_IF_MACRO(userDir == NULL, NULL, 0); /* STILL failed?! */
  204. } /* if */
  205. return(1); /* We made it: hit the showers. */
  206. } /* determineUserDir */
  207. static BOOL mediaInDrive(const char *drive)
  208. {
  209. UINT oldErrorMode;
  210. DWORD tmp;
  211. BOOL retval;
  212. /* Prevent windows warning message appearing when checking media size */
  213. oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  214. /* If this function succeeds, there's media in the drive */
  215. retval = GetVolumeInformation(drive, NULL, 0, NULL, NULL, &tmp, NULL, 0);
  216. /* Revert back to old windows error handler */
  217. SetErrorMode(oldErrorMode);
  218. return(retval);
  219. } /* mediaInDrive */
  220. void __PHYSFS_platformDetectAvailableCDs(PHYSFS_StringCallback cb, void *data)
  221. {
  222. char drive_str[4] = "x:\\";
  223. char ch;
  224. for (ch = 'A'; ch <= 'Z'; ch++)
  225. {
  226. drive_str[0] = ch;
  227. if (GetDriveType(drive_str) == DRIVE_CDROM && mediaInDrive(drive_str))
  228. cb(data, drive_str);
  229. } /* for */
  230. } /* __PHYSFS_platformDetectAvailableCDs */
  231. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  232. {
  233. if ((argv0 != NULL) && (strchr(argv0, '\\') != NULL))
  234. return(NULL); /* default behaviour can handle this. */
  235. return(getExePath(argv0));
  236. } /* __PHYSFS_platformCalcBaseDir */
  237. char *__PHYSFS_platformGetUserName(void)
  238. {
  239. DWORD bufsize = 0;
  240. LPTSTR retval = NULL;
  241. if (GetUserName(NULL, &bufsize) == 0) /* This SHOULD fail. */
  242. {
  243. retval = (LPTSTR) allocator.Malloc(bufsize);
  244. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  245. if (GetUserName(retval, &bufsize) == 0) /* ?! */
  246. {
  247. __PHYSFS_setError(win32strerror());
  248. allocator.Free(retval);
  249. retval = NULL;
  250. } /* if */
  251. } /* if */
  252. return((char *) retval);
  253. } /* __PHYSFS_platformGetUserName */
  254. char *__PHYSFS_platformGetUserDir(void)
  255. {
  256. char *retval = (char *) allocator.Malloc(strlen(userDir) + 1);
  257. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  258. strcpy(retval, userDir); /* calculated at init time. */
  259. return(retval);
  260. } /* __PHYSFS_platformGetUserDir */
  261. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  262. {
  263. return((PHYSFS_uint64) GetCurrentThreadId());
  264. } /* __PHYSFS_platformGetThreadID */
  265. int __PHYSFS_platformExists(const char *fname)
  266. {
  267. BAIL_IF_MACRO
  268. (
  269. GetFileAttributes(fname) == PHYSFS_INVALID_FILE_ATTRIBUTES,
  270. win32strerror(), 0
  271. );
  272. return(1);
  273. } /* __PHYSFS_platformExists */
  274. int __PHYSFS_platformIsSymLink(const char *fname)
  275. {
  276. return(0); /* no symlinks on win32. */
  277. } /* __PHYSFS_platformIsSymlink */
  278. int __PHYSFS_platformIsDirectory(const char *fname)
  279. {
  280. return((GetFileAttributes(fname) & FILE_ATTRIBUTE_DIRECTORY) != 0);
  281. } /* __PHYSFS_platformIsDirectory */
  282. char *__PHYSFS_platformCvtToDependent(const char *prepend,
  283. const char *dirName,
  284. const char *append)
  285. {
  286. int len = ((prepend) ? strlen(prepend) : 0) +
  287. ((append) ? strlen(append) : 0) +
  288. strlen(dirName) + 1;
  289. char *retval = (char *) allocator.Malloc(len);
  290. char *p;
  291. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  292. if (prepend)
  293. strcpy(retval, prepend);
  294. else
  295. retval[0] = '\0';
  296. strcat(retval, dirName);
  297. if (append)
  298. strcat(retval, append);
  299. for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
  300. *p = '\\';
  301. return(retval);
  302. } /* __PHYSFS_platformCvtToDependent */
  303. void __PHYSFS_platformEnumerateFiles(const char *dirname,
  304. int omitSymLinks,
  305. PHYSFS_EnumFilesCallback callback,
  306. const char *origdir,
  307. void *callbackdata)
  308. {
  309. HANDLE dir;
  310. WIN32_FIND_DATA ent;
  311. size_t len = strlen(dirname);
  312. char *SearchPath;
  313. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  314. SearchPath = (char *) __PHYSFS_smallAlloc(len + 3);
  315. if (SearchPath == NULL)
  316. return;
  317. /* Copy current dirname */
  318. strcpy(SearchPath, dirname);
  319. /* if there's no '\\' at the end of the path, stick one in there. */
  320. if (SearchPath[len - 1] != '\\')
  321. {
  322. SearchPath[len++] = '\\';
  323. SearchPath[len] = '\0';
  324. } /* if */
  325. /* Append the "*" to the end of the string */
  326. strcat(SearchPath, "*");
  327. dir = FindFirstFile(SearchPath, &ent);
  328. __PHYSFS_smallFree(SearchPath);
  329. if (dir == INVALID_HANDLE_VALUE)
  330. return;
  331. do
  332. {
  333. if (strcmp(ent.cFileName, ".") == 0)
  334. continue;
  335. if (strcmp(ent.cFileName, "..") == 0)
  336. continue;
  337. callback(callbackdata, origdir, ent.cFileName);
  338. } while (FindNextFile(dir, &ent) != 0);
  339. FindClose(dir);
  340. } /* __PHYSFS_platformEnumerateFiles */
  341. char *__PHYSFS_platformCurrentDir(void)
  342. {
  343. LPTSTR retval;
  344. DWORD buflen = 0;
  345. buflen = GetCurrentDirectory(buflen, NULL);
  346. retval = (LPTSTR) allocator.Malloc(sizeof (TCHAR) * (buflen + 2));
  347. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  348. GetCurrentDirectory(buflen, retval);
  349. if (retval[buflen - 2] != '\\')
  350. strcat(retval, "\\");
  351. return((char *) retval);
  352. } /* __PHYSFS_platformCurrentDir */
  353. /* this could probably use a cleanup. */
  354. char *__PHYSFS_platformRealPath(const char *path)
  355. {
  356. char *retval = NULL;
  357. char *p = NULL;
  358. BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
  359. BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
  360. retval = (char *) allocator.Malloc(MAX_PATH);
  361. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  362. /*
  363. * If in \\server\path format, it's already an absolute path.
  364. * We'll need to check for "." and ".." dirs, though, just in case.
  365. */
  366. if ((path[0] == '\\') && (path[1] == '\\'))
  367. strcpy(retval, path);
  368. else
  369. {
  370. char *currentDir = __PHYSFS_platformCurrentDir();
  371. if (currentDir == NULL)
  372. {
  373. allocator.Free(retval);
  374. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  375. } /* if */
  376. if (path[1] == ':') /* drive letter specified? */
  377. {
  378. /*
  379. * Apparently, "D:mypath" is the same as "D:\\mypath" if
  380. * D: is not the current drive. However, if D: is the
  381. * current drive, then "D:mypath" is a relative path. Ugh.
  382. */
  383. if (path[2] == '\\') /* maybe an absolute path? */
  384. strcpy(retval, path);
  385. else /* definitely an absolute path. */
  386. {
  387. if (path[0] == currentDir[0]) /* current drive; relative. */
  388. {
  389. strcpy(retval, currentDir);
  390. strcat(retval, path + 2);
  391. } /* if */
  392. else /* not current drive; absolute. */
  393. {
  394. retval[0] = path[0];
  395. retval[1] = ':';
  396. retval[2] = '\\';
  397. strcpy(retval + 3, path + 2);
  398. } /* else */
  399. } /* else */
  400. } /* if */
  401. else /* no drive letter specified. */
  402. {
  403. if (path[0] == '\\') /* absolute path. */
  404. {
  405. retval[0] = currentDir[0];
  406. retval[1] = ':';
  407. strcpy(retval + 2, path);
  408. } /* if */
  409. else
  410. {
  411. strcpy(retval, currentDir);
  412. strcat(retval, path);
  413. } /* else */
  414. } /* else */
  415. allocator.Free(currentDir);
  416. } /* else */
  417. /* (whew.) Ok, now take out "." and ".." path entries... */
  418. p = retval;
  419. while ( (p = strstr(p, "\\.")) != NULL)
  420. {
  421. /* it's a "." entry that doesn't end the string. */
  422. if (p[2] == '\\')
  423. memmove(p + 1, p + 3, strlen(p + 3) + 1);
  424. /* it's a "." entry that ends the string. */
  425. else if (p[2] == '\0')
  426. p[0] = '\0';
  427. /* it's a ".." entry. */
  428. else if (p[2] == '.')
  429. {
  430. char *prevEntry = p - 1;
  431. while ((prevEntry != retval) && (*prevEntry != '\\'))
  432. prevEntry--;
  433. if (prevEntry == retval) /* make it look like a "." entry. */
  434. memmove(p + 1, p + 2, strlen(p + 2) + 1);
  435. else
  436. {
  437. if (p[3] != '\0') /* doesn't end string. */
  438. *prevEntry = '\0';
  439. else /* ends string. */
  440. memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
  441. p = prevEntry;
  442. } /* else */
  443. } /* else if */
  444. else
  445. {
  446. p++; /* look past current char. */
  447. } /* else */
  448. } /* while */
  449. /* shrink the retval's memory block if possible... */
  450. p = (char *) allocator.Realloc(retval, strlen(retval) + 1);
  451. if (p != NULL)
  452. retval = p;
  453. return(retval);
  454. } /* __PHYSFS_platformRealPath */
  455. int __PHYSFS_platformMkDir(const char *path)
  456. {
  457. DWORD rc = CreateDirectory(path, NULL);
  458. BAIL_IF_MACRO(rc == 0, win32strerror(), 0);
  459. return(1);
  460. } /* __PHYSFS_platformMkDir */
  461. /*
  462. * Get OS info and save the important parts.
  463. *
  464. * Returns non-zero if successful, otherwise it returns zero on failure.
  465. */
  466. static int getOSInfo(void)
  467. {
  468. #if 0 /* we don't actually use this at the moment, but may in the future. */
  469. OSVERSIONINFO OSVersionInfo; /* Information about the OS */
  470. OSVersionInfo.dwOSVersionInfoSize = sizeof(OSVersionInfo);
  471. BAIL_IF_MACRO(!GetVersionEx(&OSVersionInfo), win32strerror(), 0);
  472. /* Set to TRUE if we are runnign a WinNT based OS 4.0 or greater */
  473. runningNT = ((OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) &&
  474. (OSVersionInfo.dwMajorVersion >= 4));
  475. #endif
  476. return(1);
  477. } /* getOSInfo */
  478. /*
  479. * Some things we want/need are in external DLLs that may or may not be
  480. * available, based on the operating system, etc. This function loads those
  481. * libraries and hunts down the needed pointers.
  482. *
  483. * Libraries that are one-shot deals, or better loaded as needed, are loaded
  484. * elsewhere (see determineUserDir()).
  485. *
  486. * Returns zero if a needed library couldn't load, non-zero if we have enough
  487. * to go on (which means some useful but non-crucial libraries may _NOT_ be
  488. * loaded; check the related module-scope variables).
  489. */
  490. static int loadLibraries(void)
  491. {
  492. /* If this get unwieldy, make it table driven. */
  493. int allNeededLibrariesLoaded = 1; /* flip to zero as needed. */
  494. libKernel32 = LoadLibrary("kernel32.dll");
  495. if (libKernel32)
  496. {
  497. pGetFileAttributesEx = (LPFNGETFILEATTRIBUTESEX)
  498. GetProcAddress(libKernel32, "GetFileAttributesExA");
  499. } /* if */
  500. /* add other DLLs here... */
  501. /* see if there's any reason to keep kernel32.dll around... */
  502. if (libKernel32)
  503. {
  504. if ((pGetFileAttributesEx == NULL) /* && (somethingElse == NULL) */ )
  505. {
  506. FreeLibrary(libKernel32);
  507. libKernel32 = NULL;
  508. } /* if */
  509. } /* if */
  510. return(allNeededLibrariesLoaded);
  511. } /* loadLibraries */
  512. int __PHYSFS_platformInit(void)
  513. {
  514. BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
  515. BAIL_IF_MACRO(!loadLibraries(), NULL, 0);
  516. BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
  517. return(1); /* It's all good */
  518. } /* __PHYSFS_platformInit */
  519. int __PHYSFS_platformDeinit(void)
  520. {
  521. if (userDir != NULL)
  522. {
  523. allocator.Free(userDir);
  524. userDir = NULL;
  525. } /* if */
  526. if (libKernel32)
  527. {
  528. FreeLibrary(libKernel32);
  529. libKernel32 = NULL;
  530. } /* if */
  531. return(1); /* It's all good */
  532. } /* __PHYSFS_platformDeinit */
  533. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  534. {
  535. HANDLE fileHandle;
  536. win32file *retval;
  537. fileHandle = CreateFile(fname, mode, FILE_SHARE_READ, NULL,
  538. creation, FILE_ATTRIBUTE_NORMAL, NULL);
  539. BAIL_IF_MACRO
  540. (
  541. fileHandle == INVALID_HANDLE_VALUE,
  542. win32strerror(), NULL
  543. );
  544. retval = (win32file *) allocator.Malloc(sizeof (win32file));
  545. if (retval == NULL)
  546. {
  547. CloseHandle(fileHandle);
  548. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  549. } /* if */
  550. retval->readonly = rdonly;
  551. retval->handle = fileHandle;
  552. return(retval);
  553. } /* doOpen */
  554. void *__PHYSFS_platformOpenRead(const char *filename)
  555. {
  556. return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
  557. } /* __PHYSFS_platformOpenRead */
  558. void *__PHYSFS_platformOpenWrite(const char *filename)
  559. {
  560. return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
  561. } /* __PHYSFS_platformOpenWrite */
  562. void *__PHYSFS_platformOpenAppend(const char *filename)
  563. {
  564. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  565. if (retval != NULL)
  566. {
  567. HANDLE h = ((win32file *) retval)->handle;
  568. DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
  569. if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
  570. {
  571. const char *err = win32strerror();
  572. CloseHandle(h);
  573. allocator.Free(retval);
  574. BAIL_MACRO(err, NULL);
  575. } /* if */
  576. } /* if */
  577. return(retval);
  578. } /* __PHYSFS_platformOpenAppend */
  579. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
  580. PHYSFS_uint32 size, PHYSFS_uint32 count)
  581. {
  582. HANDLE Handle = ((win32file *) opaque)->handle;
  583. DWORD CountOfBytesRead;
  584. PHYSFS_sint64 retval;
  585. /* Read data from the file */
  586. /* !!! FIXME: uint32 might be a greater # than DWORD */
  587. if(!ReadFile(Handle, buffer, count * size, &CountOfBytesRead, NULL))
  588. {
  589. BAIL_MACRO(win32strerror(), -1);
  590. } /* if */
  591. else
  592. {
  593. /* Return the number of "objects" read. */
  594. /* !!! FIXME: What if not the right amount of bytes was read to make an object? */
  595. retval = CountOfBytesRead / size;
  596. } /* else */
  597. return(retval);
  598. } /* __PHYSFS_platformRead */
  599. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  600. PHYSFS_uint32 size, PHYSFS_uint32 count)
  601. {
  602. HANDLE Handle = ((win32file *) opaque)->handle;
  603. DWORD CountOfBytesWritten;
  604. PHYSFS_sint64 retval;
  605. /* Read data from the file */
  606. /* !!! FIXME: uint32 might be a greater # than DWORD */
  607. if(!WriteFile(Handle, buffer, count * size, &CountOfBytesWritten, NULL))
  608. {
  609. BAIL_MACRO(win32strerror(), -1);
  610. } /* if */
  611. else
  612. {
  613. /* Return the number of "objects" read. */
  614. /* !!! FIXME: What if not the right number of bytes was written? */
  615. retval = CountOfBytesWritten / size;
  616. } /* else */
  617. return(retval);
  618. } /* __PHYSFS_platformWrite */
  619. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  620. {
  621. HANDLE Handle = ((win32file *) opaque)->handle;
  622. DWORD HighOrderPos;
  623. DWORD *pHighOrderPos;
  624. DWORD rc;
  625. /* Get the high order 32-bits of the position */
  626. HighOrderPos = HIGHORDER_UINT64(pos);
  627. /*
  628. * MSDN: "If you do not need the high-order 32 bits, this
  629. * pointer must be set to NULL."
  630. */
  631. pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
  632. /*
  633. * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
  634. * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
  635. * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
  636. * !!! FIXME: the sign extension of the value of lDistanceToMove.
  637. * !!! FIXME: Any other value will be rejected."
  638. */
  639. /* Move pointer "pos" count from start of file */
  640. rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
  641. pHighOrderPos, FILE_BEGIN);
  642. if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
  643. (GetLastError() != NO_ERROR) )
  644. {
  645. BAIL_MACRO(win32strerror(), 0);
  646. } /* if */
  647. return(1); /* No error occured */
  648. } /* __PHYSFS_platformSeek */
  649. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  650. {
  651. HANDLE Handle = ((win32file *) opaque)->handle;
  652. DWORD HighPos = 0;
  653. DWORD LowPos;
  654. PHYSFS_sint64 retval;
  655. /* Get current position */
  656. LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
  657. if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
  658. (GetLastError() != NO_ERROR) )
  659. {
  660. BAIL_MACRO(win32strerror(), 0);
  661. } /* if */
  662. else
  663. {
  664. /* Combine the high/low order to create the 64-bit position value */
  665. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  666. assert(retval >= 0);
  667. } /* else */
  668. return(retval);
  669. } /* __PHYSFS_platformTell */
  670. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  671. {
  672. HANDLE Handle = ((win32file *) opaque)->handle;
  673. DWORD SizeHigh;
  674. DWORD SizeLow;
  675. PHYSFS_sint64 retval;
  676. SizeLow = GetFileSize(Handle, &SizeHigh);
  677. if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
  678. (GetLastError() != NO_ERROR) )
  679. {
  680. BAIL_MACRO(win32strerror(), -1);
  681. } /* if */
  682. else
  683. {
  684. /* Combine the high/low order to create the 64-bit position value */
  685. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  686. assert(retval >= 0);
  687. } /* else */
  688. return(retval);
  689. } /* __PHYSFS_platformFileLength */
  690. int __PHYSFS_platformEOF(void *opaque)
  691. {
  692. PHYSFS_sint64 FilePosition;
  693. int retval = 0;
  694. /* Get the current position in the file */
  695. if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
  696. {
  697. /* Non-zero if EOF is equal to the file length */
  698. retval = FilePosition == __PHYSFS_platformFileLength(opaque);
  699. } /* if */
  700. return(retval);
  701. } /* __PHYSFS_platformEOF */
  702. int __PHYSFS_platformFlush(void *opaque)
  703. {
  704. win32file *fh = ((win32file *) opaque);
  705. if (!fh->readonly)
  706. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), win32strerror(), 0);
  707. return(1);
  708. } /* __PHYSFS_platformFlush */
  709. int __PHYSFS_platformClose(void *opaque)
  710. {
  711. HANDLE Handle = ((win32file *) opaque)->handle;
  712. BAIL_IF_MACRO(!CloseHandle(Handle), win32strerror(), 0);
  713. allocator.Free(opaque);
  714. return(1);
  715. } /* __PHYSFS_platformClose */
  716. int __PHYSFS_platformDelete(const char *path)
  717. {
  718. /* If filename is a folder */
  719. if (GetFileAttributes(path) == FILE_ATTRIBUTE_DIRECTORY)
  720. {
  721. BAIL_IF_MACRO(!RemoveDirectory(path), win32strerror(), 0);
  722. } /* if */
  723. else
  724. {
  725. BAIL_IF_MACRO(!DeleteFile(path), win32strerror(), 0);
  726. } /* else */
  727. return(1); /* if you got here, it worked. */
  728. } /* __PHYSFS_platformDelete */
  729. void *__PHYSFS_platformCreateMutex(void)
  730. {
  731. return((void *) CreateMutex(NULL, FALSE, NULL));
  732. } /* __PHYSFS_platformCreateMutex */
  733. void __PHYSFS_platformDestroyMutex(void *mutex)
  734. {
  735. CloseHandle((HANDLE) mutex);
  736. } /* __PHYSFS_platformDestroyMutex */
  737. int __PHYSFS_platformGrabMutex(void *mutex)
  738. {
  739. return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
  740. } /* __PHYSFS_platformGrabMutex */
  741. void __PHYSFS_platformReleaseMutex(void *mutex)
  742. {
  743. ReleaseMutex((HANDLE) mutex);
  744. } /* __PHYSFS_platformReleaseMutex */
  745. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  746. {
  747. SYSTEMTIME st_utc;
  748. SYSTEMTIME st_localtz;
  749. TIME_ZONE_INFORMATION tzi;
  750. DWORD tzid;
  751. PHYSFS_sint64 retval;
  752. struct tm tm;
  753. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), win32strerror(), -1);
  754. tzid = GetTimeZoneInformation(&tzi);
  755. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, win32strerror(), -1);
  756. /* (This API is unsupported and fails on non-NT systems. */
  757. if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
  758. {
  759. /* do it by hand. Grumble... */
  760. ULARGE_INTEGER ui64;
  761. FILETIME new_ft;
  762. ui64.LowPart = ft->dwLowDateTime;
  763. ui64.HighPart = ft->dwHighDateTime;
  764. if (tzid == TIME_ZONE_ID_STANDARD)
  765. tzi.Bias += tzi.StandardBias;
  766. else if (tzid == TIME_ZONE_ID_DAYLIGHT)
  767. tzi.Bias += tzi.DaylightBias;
  768. /* convert from minutes to 100-nanosecond increments... */
  769. #if 0 /* For compilers that puke on 64-bit math. */
  770. /* goddamn this is inefficient... */
  771. while (tzi.Bias > 0)
  772. {
  773. DWORD tmp = ui64.LowPart - 60000000;
  774. if ((ui64.LowPart < tmp) && (tmp > 60000000))
  775. ui64.HighPart--;
  776. ui64.LowPart = tmp;
  777. tzi.Bias--;
  778. } /* while */
  779. while (tzi.Bias < 0)
  780. {
  781. DWORD tmp = ui64.LowPart + 60000000;
  782. if ((ui64.LowPart > tmp) && (tmp < 60000000))
  783. ui64.HighPart++;
  784. ui64.LowPart = tmp;
  785. tzi.Bias++;
  786. } /* while */
  787. #else
  788. ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
  789. #endif
  790. /* Move it back into a FILETIME structure... */
  791. new_ft.dwLowDateTime = ui64.LowPart;
  792. new_ft.dwHighDateTime = ui64.HighPart;
  793. /* Convert to something human-readable... */
  794. if (!FileTimeToSystemTime(&new_ft, &st_localtz))
  795. BAIL_MACRO(win32strerror(), -1);
  796. } /* if */
  797. /* Convert to a format that mktime() can grok... */
  798. tm.tm_sec = st_localtz.wSecond;
  799. tm.tm_min = st_localtz.wMinute;
  800. tm.tm_hour = st_localtz.wHour;
  801. tm.tm_mday = st_localtz.wDay;
  802. tm.tm_mon = st_localtz.wMonth - 1;
  803. tm.tm_year = st_localtz.wYear - 1900;
  804. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  805. tm.tm_yday = -1;
  806. tm.tm_isdst = -1;
  807. /* Convert to a format PhysicsFS can grok... */
  808. retval = (PHYSFS_sint64) mktime(&tm);
  809. BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
  810. return(retval);
  811. } /* FileTimeToPhysfsTime */
  812. PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
  813. {
  814. PHYSFS_sint64 retval = -1;
  815. WIN32_FILE_ATTRIBUTE_DATA attrData;
  816. memset(&attrData, '\0', sizeof (attrData));
  817. /* GetFileAttributesEx didn't show up until Win98 and NT4. */
  818. if (pGetFileAttributesEx != NULL)
  819. {
  820. if (pGetFileAttributesEx(fname, GetFileExInfoStandard, &attrData))
  821. {
  822. /* 0 return value indicates an error or not supported */
  823. if ( (attrData.ftLastWriteTime.dwHighDateTime != 0) ||
  824. (attrData.ftLastWriteTime.dwLowDateTime != 0) )
  825. {
  826. retval = FileTimeToPhysfsTime(&attrData.ftLastWriteTime);
  827. } /* if */
  828. } /* if */
  829. } /* if */
  830. /* GetFileTime() has been in the Win32 API since the start. */
  831. if (retval == -1) /* try a fallback... */
  832. {
  833. FILETIME ft;
  834. BOOL rc;
  835. const char *err;
  836. win32file *f = (win32file *) __PHYSFS_platformOpenRead(fname);
  837. BAIL_IF_MACRO(f == NULL, NULL, -1)
  838. rc = GetFileTime(f->handle, NULL, NULL, &ft);
  839. err = win32strerror();
  840. CloseHandle(f->handle);
  841. allocator.Free(f);
  842. BAIL_IF_MACRO(!rc, err, -1);
  843. retval = FileTimeToPhysfsTime(&ft);
  844. } /* if */
  845. return(retval);
  846. } /* __PHYSFS_platformGetLastModTime */
  847. /* !!! FIXME: Don't use C runtime for allocators? */
  848. int __PHYSFS_platformSetDefaultAllocator(PHYSFS_Allocator *a)
  849. {
  850. return(0); /* just use malloc() and friends. */
  851. } /* __PHYSFS_platformSetDefaultAllocator */
  852. #endif /* PHYSFS_PLATFORM_WINDOWS */
  853. /* end of windows.c ... */