1
0

windows.c 31 KB

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