windows.c 31 KB

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