windows.c 31 KB

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