win32.c 31 KB

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