windows.c 30 KB

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