win32.c 30 KB

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