windows.c 32 KB

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