win32.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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 MINGW) /* 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_StringCallback callback,
  360. void *callbackdata)
  361. {
  362. HANDLE dir;
  363. WIN32_FIND_DATA ent;
  364. size_t len = strlen(dirname);
  365. char *SearchPath;
  366. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  367. SearchPath = (char *) alloca(len + 3);
  368. if (SearchPath == NULL)
  369. return;
  370. /* Copy current dirname */
  371. strcpy(SearchPath, dirname);
  372. /* if there's no '\\' at the end of the path, stick one in there. */
  373. if (SearchPath[len - 1] != '\\')
  374. {
  375. SearchPath[len++] = '\\';
  376. SearchPath[len] = '\0';
  377. } /* if */
  378. /* Append the "*" to the end of the string */
  379. strcat(SearchPath, "*");
  380. dir = FindFirstFile(SearchPath, &ent);
  381. if (dir == INVALID_HANDLE_VALUE)
  382. return;
  383. do
  384. {
  385. if (strcmp(ent.cFileName, ".") == 0)
  386. continue;
  387. if (strcmp(ent.cFileName, "..") == 0)
  388. continue;
  389. callback(callbackdata, ent.cFileName);
  390. } while (FindNextFile(dir, &ent) != 0);
  391. FindClose(dir);
  392. } /* __PHYSFS_platformEnumerateFiles */
  393. char *__PHYSFS_platformCurrentDir(void)
  394. {
  395. LPTSTR retval;
  396. DWORD buflen = 0;
  397. buflen = GetCurrentDirectory(buflen, NULL);
  398. retval = (LPTSTR) allocator.Malloc(sizeof (TCHAR) * (buflen + 2));
  399. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  400. GetCurrentDirectory(buflen, retval);
  401. if (retval[buflen - 2] != '\\')
  402. strcat(retval, "\\");
  403. return((char *) retval);
  404. } /* __PHYSFS_platformCurrentDir */
  405. /* this could probably use a cleanup. */
  406. char *__PHYSFS_platformRealPath(const char *path)
  407. {
  408. char *retval = NULL;
  409. char *p = NULL;
  410. BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
  411. BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
  412. retval = (char *) allocator.Malloc(MAX_PATH);
  413. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  414. /*
  415. * If in \\server\path format, it's already an absolute path.
  416. * We'll need to check for "." and ".." dirs, though, just in case.
  417. */
  418. if ((path[0] == '\\') && (path[1] == '\\'))
  419. strcpy(retval, path);
  420. else
  421. {
  422. char *currentDir = __PHYSFS_platformCurrentDir();
  423. if (currentDir == NULL)
  424. {
  425. allocator.Free(retval);
  426. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  427. } /* if */
  428. if (path[1] == ':') /* drive letter specified? */
  429. {
  430. /*
  431. * Apparently, "D:mypath" is the same as "D:\\mypath" if
  432. * D: is not the current drive. However, if D: is the
  433. * current drive, then "D:mypath" is a relative path. Ugh.
  434. */
  435. if (path[2] == '\\') /* maybe an absolute path? */
  436. strcpy(retval, path);
  437. else /* definitely an absolute path. */
  438. {
  439. if (path[0] == currentDir[0]) /* current drive; relative. */
  440. {
  441. strcpy(retval, currentDir);
  442. strcat(retval, path + 2);
  443. } /* if */
  444. else /* not current drive; absolute. */
  445. {
  446. retval[0] = path[0];
  447. retval[1] = ':';
  448. retval[2] = '\\';
  449. strcpy(retval + 3, path + 2);
  450. } /* else */
  451. } /* else */
  452. } /* if */
  453. else /* no drive letter specified. */
  454. {
  455. if (path[0] == '\\') /* absolute path. */
  456. {
  457. retval[0] = currentDir[0];
  458. retval[1] = ':';
  459. strcpy(retval + 2, path);
  460. } /* if */
  461. else
  462. {
  463. strcpy(retval, currentDir);
  464. strcat(retval, path);
  465. } /* else */
  466. } /* else */
  467. allocator.Free(currentDir);
  468. } /* else */
  469. /* (whew.) Ok, now take out "." and ".." path entries... */
  470. p = retval;
  471. while ( (p = strstr(p, "\\.")) != NULL)
  472. {
  473. /* it's a "." entry that doesn't end the string. */
  474. if (p[2] == '\\')
  475. memmove(p + 1, p + 3, strlen(p + 3) + 1);
  476. /* it's a "." entry that ends the string. */
  477. else if (p[2] == '\0')
  478. p[0] = '\0';
  479. /* it's a ".." entry. */
  480. else if (p[2] == '.')
  481. {
  482. char *prevEntry = p - 1;
  483. while ((prevEntry != retval) && (*prevEntry != '\\'))
  484. prevEntry--;
  485. if (prevEntry == retval) /* make it look like a "." entry. */
  486. memmove(p + 1, p + 2, strlen(p + 2) + 1);
  487. else
  488. {
  489. if (p[3] != '\0') /* doesn't end string. */
  490. *prevEntry = '\0';
  491. else /* ends string. */
  492. memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
  493. p = prevEntry;
  494. } /* else */
  495. } /* else if */
  496. else
  497. {
  498. p++; /* look past current char. */
  499. } /* else */
  500. } /* while */
  501. /* shrink the retval's memory block if possible... */
  502. p = (char *) allocator.Realloc(retval, strlen(retval) + 1);
  503. if (p != NULL)
  504. retval = p;
  505. return(retval);
  506. } /* __PHYSFS_platformRealPath */
  507. int __PHYSFS_platformMkDir(const char *path)
  508. {
  509. DWORD rc = CreateDirectory(path, NULL);
  510. BAIL_IF_MACRO(rc == 0, win32strerror(), 0);
  511. return(1);
  512. } /* __PHYSFS_platformMkDir */
  513. /*
  514. * Get OS info and save the important parts.
  515. *
  516. * Returns non-zero if successful, otherwise it returns zero on failure.
  517. */
  518. static int getOSInfo(void)
  519. {
  520. #if 0 /* we don't actually use this at the moment, but may in the future. */
  521. OSVERSIONINFO OSVersionInfo; /* Information about the OS */
  522. OSVersionInfo.dwOSVersionInfoSize = sizeof(OSVersionInfo);
  523. BAIL_IF_MACRO(!GetVersionEx(&OSVersionInfo), win32strerror(), 0);
  524. /* Set to TRUE if we are runnign a WinNT based OS 4.0 or greater */
  525. runningNT = ((OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) &&
  526. (OSVersionInfo.dwMajorVersion >= 4));
  527. #endif
  528. return(1);
  529. } /* getOSInfo */
  530. /*
  531. * Some things we want/need are in external DLLs that may or may not be
  532. * available, based on the operating system, etc. This function loads those
  533. * libraries and hunts down the needed pointers.
  534. *
  535. * Libraries that are one-shot deals, or better loaded as needed, are loaded
  536. * elsewhere (see determineUserDir()).
  537. *
  538. * Returns zero if a needed library couldn't load, non-zero if we have enough
  539. * to go on (which means some useful but non-crucial libraries may _NOT_ be
  540. * loaded; check the related module-scope variables).
  541. */
  542. static int loadLibraries(void)
  543. {
  544. /* If this get unwieldy, make it table driven. */
  545. int allNeededLibrariesLoaded = 1; /* flip to zero as needed. */
  546. libKernel32 = LoadLibrary("kernel32.dll");
  547. if (libKernel32)
  548. {
  549. pGetFileAttributesEx = (LPFNGETFILEATTRIBUTESEX)
  550. GetProcAddress(libKernel32, "GetFileAttributesExA");
  551. } /* if */
  552. /* add other DLLs here... */
  553. /* see if there's any reason to keep kernel32.dll around... */
  554. if (libKernel32)
  555. {
  556. if ((pGetFileAttributesEx == NULL) /* && (somethingElse == NULL) */ )
  557. {
  558. FreeLibrary(libKernel32);
  559. libKernel32 = NULL;
  560. } /* if */
  561. } /* if */
  562. return(allNeededLibrariesLoaded);
  563. } /* loadLibraries */
  564. int __PHYSFS_platformInit(void)
  565. {
  566. BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
  567. BAIL_IF_MACRO(!loadLibraries(), NULL, 0);
  568. BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
  569. return(1); /* It's all good */
  570. } /* __PHYSFS_platformInit */
  571. int __PHYSFS_platformDeinit(void)
  572. {
  573. if (userDir != NULL)
  574. {
  575. allocator.Free(userDir);
  576. userDir = NULL;
  577. } /* if */
  578. if (libKernel32)
  579. {
  580. FreeLibrary(libKernel32);
  581. libKernel32 = NULL;
  582. } /* if */
  583. return(1); /* It's all good */
  584. } /* __PHYSFS_platformDeinit */
  585. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  586. {
  587. HANDLE fileHandle;
  588. win32file *retval;
  589. fileHandle = CreateFile(fname, mode, FILE_SHARE_READ, NULL,
  590. creation, FILE_ATTRIBUTE_NORMAL, NULL);
  591. BAIL_IF_MACRO
  592. (
  593. fileHandle == INVALID_HANDLE_VALUE,
  594. win32strerror(), NULL
  595. );
  596. retval = (win32file *) allocator.Malloc(sizeof (win32file));
  597. if (retval == NULL)
  598. {
  599. CloseHandle(fileHandle);
  600. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  601. } /* if */
  602. retval->readonly = rdonly;
  603. retval->handle = fileHandle;
  604. return(retval);
  605. } /* doOpen */
  606. void *__PHYSFS_platformOpenRead(const char *filename)
  607. {
  608. return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
  609. } /* __PHYSFS_platformOpenRead */
  610. void *__PHYSFS_platformOpenWrite(const char *filename)
  611. {
  612. return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
  613. } /* __PHYSFS_platformOpenWrite */
  614. void *__PHYSFS_platformOpenAppend(const char *filename)
  615. {
  616. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  617. if (retval != NULL)
  618. {
  619. HANDLE h = ((win32file *) retval)->handle;
  620. DWORD rc = SetFilePointer(h, 0, NULL, FILE_END);
  621. if (rc == PHYSFS_INVALID_SET_FILE_POINTER)
  622. {
  623. const char *err = win32strerror();
  624. CloseHandle(h);
  625. allocator.Free(retval);
  626. BAIL_MACRO(err, NULL);
  627. } /* if */
  628. } /* if */
  629. return(retval);
  630. } /* __PHYSFS_platformOpenAppend */
  631. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
  632. PHYSFS_uint32 size, PHYSFS_uint32 count)
  633. {
  634. HANDLE Handle = ((win32file *) opaque)->handle;
  635. DWORD CountOfBytesRead;
  636. PHYSFS_sint64 retval;
  637. /* Read data from the file */
  638. /* !!! FIXME: uint32 might be a greater # than DWORD */
  639. if(!ReadFile(Handle, buffer, count * size, &CountOfBytesRead, NULL))
  640. {
  641. BAIL_MACRO(win32strerror(), -1);
  642. } /* if */
  643. else
  644. {
  645. /* Return the number of "objects" read. */
  646. /* !!! FIXME: What if not the right amount of bytes was read to make an object? */
  647. retval = CountOfBytesRead / size;
  648. } /* else */
  649. return(retval);
  650. } /* __PHYSFS_platformRead */
  651. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  652. PHYSFS_uint32 size, PHYSFS_uint32 count)
  653. {
  654. HANDLE Handle = ((win32file *) opaque)->handle;
  655. DWORD CountOfBytesWritten;
  656. PHYSFS_sint64 retval;
  657. /* Read data from the file */
  658. /* !!! FIXME: uint32 might be a greater # than DWORD */
  659. if(!WriteFile(Handle, buffer, count * size, &CountOfBytesWritten, NULL))
  660. {
  661. BAIL_MACRO(win32strerror(), -1);
  662. } /* if */
  663. else
  664. {
  665. /* Return the number of "objects" read. */
  666. /* !!! FIXME: What if not the right number of bytes was written? */
  667. retval = CountOfBytesWritten / size;
  668. } /* else */
  669. return(retval);
  670. } /* __PHYSFS_platformWrite */
  671. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  672. {
  673. HANDLE Handle = ((win32file *) opaque)->handle;
  674. DWORD HighOrderPos;
  675. DWORD *pHighOrderPos;
  676. DWORD rc;
  677. /* Get the high order 32-bits of the position */
  678. HighOrderPos = HIGHORDER_UINT64(pos);
  679. /*
  680. * MSDN: "If you do not need the high-order 32 bits, this
  681. * pointer must be set to NULL."
  682. */
  683. pHighOrderPos = (HighOrderPos) ? &HighOrderPos : NULL;
  684. /*
  685. * !!! FIXME: MSDN: "Windows Me/98/95: If the pointer
  686. * !!! FIXME: lpDistanceToMoveHigh is not NULL, then it must
  687. * !!! FIXME: point to either 0, INVALID_SET_FILE_POINTER, or
  688. * !!! FIXME: the sign extension of the value of lDistanceToMove.
  689. * !!! FIXME: Any other value will be rejected."
  690. */
  691. /* Move pointer "pos" count from start of file */
  692. rc = SetFilePointer(Handle, LOWORDER_UINT64(pos),
  693. pHighOrderPos, FILE_BEGIN);
  694. if ( (rc == PHYSFS_INVALID_SET_FILE_POINTER) &&
  695. (GetLastError() != NO_ERROR) )
  696. {
  697. BAIL_MACRO(win32strerror(), 0);
  698. } /* if */
  699. return(1); /* No error occured */
  700. } /* __PHYSFS_platformSeek */
  701. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  702. {
  703. HANDLE Handle = ((win32file *) opaque)->handle;
  704. DWORD HighPos = 0;
  705. DWORD LowPos;
  706. PHYSFS_sint64 retval;
  707. /* Get current position */
  708. LowPos = SetFilePointer(Handle, 0, &HighPos, FILE_CURRENT);
  709. if ( (LowPos == PHYSFS_INVALID_SET_FILE_POINTER) &&
  710. (GetLastError() != NO_ERROR) )
  711. {
  712. BAIL_MACRO(win32strerror(), 0);
  713. } /* if */
  714. else
  715. {
  716. /* Combine the high/low order to create the 64-bit position value */
  717. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  718. assert(retval >= 0);
  719. } /* else */
  720. return(retval);
  721. } /* __PHYSFS_platformTell */
  722. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  723. {
  724. HANDLE Handle = ((win32file *) opaque)->handle;
  725. DWORD SizeHigh;
  726. DWORD SizeLow;
  727. PHYSFS_sint64 retval;
  728. SizeLow = GetFileSize(Handle, &SizeHigh);
  729. if ( (SizeLow == PHYSFS_INVALID_SET_FILE_POINTER) &&
  730. (GetLastError() != NO_ERROR) )
  731. {
  732. BAIL_MACRO(win32strerror(), -1);
  733. } /* if */
  734. else
  735. {
  736. /* Combine the high/low order to create the 64-bit position value */
  737. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  738. assert(retval >= 0);
  739. } /* else */
  740. return(retval);
  741. } /* __PHYSFS_platformFileLength */
  742. int __PHYSFS_platformEOF(void *opaque)
  743. {
  744. PHYSFS_sint64 FilePosition;
  745. int retval = 0;
  746. /* Get the current position in the file */
  747. if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
  748. {
  749. /* Non-zero if EOF is equal to the file length */
  750. retval = FilePosition == __PHYSFS_platformFileLength(opaque);
  751. } /* if */
  752. return(retval);
  753. } /* __PHYSFS_platformEOF */
  754. int __PHYSFS_platformFlush(void *opaque)
  755. {
  756. win32file *fh = ((win32file *) opaque);
  757. if (!fh->readonly)
  758. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), win32strerror(), 0);
  759. return(1);
  760. } /* __PHYSFS_platformFlush */
  761. int __PHYSFS_platformClose(void *opaque)
  762. {
  763. HANDLE Handle = ((win32file *) opaque)->handle;
  764. BAIL_IF_MACRO(!CloseHandle(Handle), win32strerror(), 0);
  765. allocator.Free(opaque);
  766. return(1);
  767. } /* __PHYSFS_platformClose */
  768. int __PHYSFS_platformDelete(const char *path)
  769. {
  770. /* If filename is a folder */
  771. if (GetFileAttributes(path) == FILE_ATTRIBUTE_DIRECTORY)
  772. {
  773. BAIL_IF_MACRO(!RemoveDirectory(path), win32strerror(), 0);
  774. } /* if */
  775. else
  776. {
  777. BAIL_IF_MACRO(!DeleteFile(path), win32strerror(), 0);
  778. } /* else */
  779. return(1); /* if you got here, it worked. */
  780. } /* __PHYSFS_platformDelete */
  781. void *__PHYSFS_platformCreateMutex(void)
  782. {
  783. return((void *) CreateMutex(NULL, FALSE, NULL));
  784. } /* __PHYSFS_platformCreateMutex */
  785. void __PHYSFS_platformDestroyMutex(void *mutex)
  786. {
  787. CloseHandle((HANDLE) mutex);
  788. } /* __PHYSFS_platformDestroyMutex */
  789. int __PHYSFS_platformGrabMutex(void *mutex)
  790. {
  791. return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
  792. } /* __PHYSFS_platformGrabMutex */
  793. void __PHYSFS_platformReleaseMutex(void *mutex)
  794. {
  795. ReleaseMutex((HANDLE) mutex);
  796. } /* __PHYSFS_platformReleaseMutex */
  797. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  798. {
  799. SYSTEMTIME st_utc;
  800. SYSTEMTIME st_localtz;
  801. TIME_ZONE_INFORMATION tzi;
  802. DWORD tzid;
  803. PHYSFS_sint64 retval;
  804. struct tm tm;
  805. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), win32strerror(), -1);
  806. tzid = GetTimeZoneInformation(&tzi);
  807. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, win32strerror(), -1);
  808. /* (This API is unsupported and fails on non-NT systems. */
  809. if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
  810. {
  811. /* do it by hand. Grumble... */
  812. ULARGE_INTEGER ui64;
  813. FILETIME new_ft;
  814. ui64.LowPart = ft->dwLowDateTime;
  815. ui64.HighPart = ft->dwHighDateTime;
  816. if (tzid == TIME_ZONE_ID_STANDARD)
  817. tzi.Bias += tzi.StandardBias;
  818. else if (tzid == TIME_ZONE_ID_DAYLIGHT)
  819. tzi.Bias += tzi.DaylightBias;
  820. /* convert from minutes to 100-nanosecond increments... */
  821. #if 0 /* For compilers that puke on 64-bit math. */
  822. /* goddamn this is inefficient... */
  823. while (tzi.Bias > 0)
  824. {
  825. DWORD tmp = ui64.LowPart - 60000000;
  826. if ((ui64.LowPart < tmp) && (tmp > 60000000))
  827. ui64.HighPart--;
  828. ui64.LowPart = tmp;
  829. tzi.Bias--;
  830. } /* while */
  831. while (tzi.Bias < 0)
  832. {
  833. DWORD tmp = ui64.LowPart + 60000000;
  834. if ((ui64.LowPart > tmp) && (tmp < 60000000))
  835. ui64.HighPart++;
  836. ui64.LowPart = tmp;
  837. tzi.Bias++;
  838. } /* while */
  839. #else
  840. ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
  841. #endif
  842. /* Move it back into a FILETIME structure... */
  843. new_ft.dwLowDateTime = ui64.LowPart;
  844. new_ft.dwHighDateTime = ui64.HighPart;
  845. /* Convert to something human-readable... */
  846. if (!FileTimeToSystemTime(&new_ft, &st_localtz))
  847. BAIL_MACRO(win32strerror(), -1);
  848. } /* if */
  849. /* Convert to a format that mktime() can grok... */
  850. tm.tm_sec = st_localtz.wSecond;
  851. tm.tm_min = st_localtz.wMinute;
  852. tm.tm_hour = st_localtz.wHour;
  853. tm.tm_mday = st_localtz.wDay;
  854. tm.tm_mon = st_localtz.wMonth - 1;
  855. tm.tm_year = st_localtz.wYear - 1900;
  856. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  857. tm.tm_yday = -1;
  858. tm.tm_isdst = -1;
  859. /* Convert to a format PhysicsFS can grok... */
  860. retval = (PHYSFS_sint64) mktime(&tm);
  861. BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
  862. return(retval);
  863. } /* FileTimeToPhysfsTime */
  864. PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
  865. {
  866. PHYSFS_sint64 retval = -1;
  867. WIN32_FILE_ATTRIBUTE_DATA attrData;
  868. memset(&attrData, '\0', sizeof (attrData));
  869. /* GetFileAttributesEx didn't show up until Win98 and NT4. */
  870. if (pGetFileAttributesEx != NULL)
  871. {
  872. if (pGetFileAttributesEx(fname, GetFileExInfoStandard, &attrData))
  873. {
  874. /* 0 return value indicates an error or not supported */
  875. if ( (attrData.ftLastWriteTime.dwHighDateTime != 0) ||
  876. (attrData.ftLastWriteTime.dwLowDateTime != 0) )
  877. {
  878. retval = FileTimeToPhysfsTime(&attrData.ftLastWriteTime);
  879. } /* if */
  880. } /* if */
  881. } /* if */
  882. /* GetFileTime() has been in the Win32 API since the start. */
  883. if (retval == -1) /* try a fallback... */
  884. {
  885. FILETIME ft;
  886. BOOL rc;
  887. const char *err;
  888. win32file *f = (win32file *) __PHYSFS_platformOpenRead(fname);
  889. BAIL_IF_MACRO(f == NULL, NULL, -1)
  890. rc = GetFileTime(f->handle, NULL, NULL, &ft);
  891. err = win32strerror();
  892. CloseHandle(f->handle);
  893. allocator.Free(f);
  894. BAIL_IF_MACRO(!rc, err, -1);
  895. retval = FileTimeToPhysfsTime(&ft);
  896. } /* if */
  897. return(retval);
  898. } /* __PHYSFS_platformGetLastModTime */
  899. /* !!! FIXME: Don't use C runtime for allocators? */
  900. int __PHYSFS_platformAllocatorInit(void)
  901. {
  902. return(1); /* always succeeds. */
  903. } /* __PHYSFS_platformAllocatorInit */
  904. void __PHYSFS_platformAllocatorDeinit(void)
  905. {
  906. /* no-op */
  907. } /* __PHYSFS_platformAllocatorInit */
  908. void *__PHYSFS_platformAllocatorMalloc(size_t s)
  909. {
  910. #undef malloc
  911. return(malloc(s));
  912. } /* __PHYSFS_platformMalloc */
  913. void *__PHYSFS_platformAllocatorRealloc(void *ptr, size_t s)
  914. {
  915. #undef realloc
  916. return(realloc(ptr, s));
  917. } /* __PHYSFS_platformRealloc */
  918. void __PHYSFS_platformAllocatorFree(void *ptr)
  919. {
  920. #undef free
  921. free(ptr);
  922. } /* __PHYSFS_platformAllocatorFree */
  923. #endif
  924. /* end of win32.c ... */