win32.c 30 KB

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