win32.c 30 KB

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