win32.c 31 KB

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