win32.c 30 KB

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