windows.c 31 KB

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