win32.c 30 KB

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