windows.c 32 KB

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