win32.c 31 KB

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