win32.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. #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 <assert.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("WIN32: GetModuleFileName() got truncated.");
  106. else
  107. {
  108. ptr = strrchr(retval, '\\');
  109. if (ptr == NULL)
  110. __PHYSFS_setError("WIN32: GetModuleFileName() had 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("WIN32: 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("Win32: SearchPath() got truncated.");
  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 *driveLetter)
  213. {
  214. UINT oldErrorMode;
  215. DWORD dummyValue;
  216. BOOL returnValue;
  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. returnValue = GetDiskFreeSpace(driveLetter, &dummyValue, &dummyValue, &dummyValue, &dummyValue);
  221. /* Revert back to old windows error handler */
  222. SetErrorMode(oldErrorMode);
  223. return(returnValue);
  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. return(GetFileAttributes(fname) != INVALID_FILE_ATTRIBUTES);
  308. } /* __PHYSFS_platformExists */
  309. int __PHYSFS_platformIsSymLink(const char *fname)
  310. {
  311. return(0); /* no symlinks on win32. */
  312. } /* __PHYSFS_platformIsSymlink */
  313. int __PHYSFS_platformIsDirectory(const char *fname)
  314. {
  315. return((GetFileAttributes(fname) & FILE_ATTRIBUTE_DIRECTORY) != 0);
  316. } /* __PHYSFS_platformIsDirectory */
  317. char *__PHYSFS_platformCvtToDependent(const char *prepend,
  318. const char *dirName,
  319. const char *append)
  320. {
  321. int len = ((prepend) ? strlen(prepend) : 0) +
  322. ((append) ? strlen(append) : 0) +
  323. strlen(dirName) + 1;
  324. char *retval = malloc(len);
  325. char *p;
  326. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  327. if (prepend)
  328. strcpy(retval, prepend);
  329. else
  330. retval[0] = '\0';
  331. strcat(retval, dirName);
  332. if (append)
  333. strcat(retval, append);
  334. for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
  335. *p = '\\';
  336. return(retval);
  337. } /* __PHYSFS_platformCvtToDependent */
  338. /* Much like my college days, try to sleep for 10 milliseconds at a time... */
  339. void __PHYSFS_platformTimeslice(void)
  340. {
  341. Sleep(10);
  342. } /* __PHYSFS_platformTimeslice */
  343. LinkedStringList *__PHYSFS_platformEnumerateFiles(const char *dirname,
  344. int omitSymLinks)
  345. {
  346. LinkedStringList *retval = NULL;
  347. LinkedStringList *l = NULL;
  348. LinkedStringList *prev = 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. l = (LinkedStringList *) malloc(sizeof (LinkedStringList));
  375. if (l == NULL)
  376. break;
  377. l->str = (char *) malloc(strlen(ent.cFileName) + 1);
  378. if (l->str == NULL)
  379. {
  380. free(l);
  381. break;
  382. } /* if */
  383. strcpy(l->str, ent.cFileName);
  384. if (retval == NULL)
  385. retval = l;
  386. else
  387. prev->next = l;
  388. prev = l;
  389. l->next = NULL;
  390. } while (FindNextFile(dir, &ent) != 0);
  391. FindClose(dir);
  392. return(retval);
  393. } /* __PHYSFS_platformEnumerateFiles */
  394. char *__PHYSFS_platformCurrentDir(void)
  395. {
  396. LPTSTR retval;
  397. DWORD buflen = 0;
  398. buflen = GetCurrentDirectory(buflen, NULL);
  399. retval = (LPTSTR) malloc(sizeof (TCHAR) * (buflen + 2));
  400. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  401. GetCurrentDirectory(buflen, retval);
  402. if (retval[buflen - 2] != '\\')
  403. strcat(retval, "\\");
  404. return((char *) retval);
  405. } /* __PHYSFS_platformCurrentDir */
  406. /* this could probably use a cleanup. */
  407. char *__PHYSFS_platformRealPath(const char *path)
  408. {
  409. char *retval = NULL;
  410. char *p = NULL;
  411. BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
  412. BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
  413. retval = (char *) malloc(MAX_PATH);
  414. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  415. /*
  416. * If in \\server\path format, it's already an absolute path.
  417. * We'll need to check for "." and ".." dirs, though, just in case.
  418. */
  419. if ((path[0] == '\\') && (path[1] == '\\'))
  420. strcpy(retval, path);
  421. else
  422. {
  423. char *currentDir = __PHYSFS_platformCurrentDir();
  424. if (currentDir == NULL)
  425. {
  426. free(retval);
  427. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  428. } /* if */
  429. if (path[1] == ':') /* drive letter specified? */
  430. {
  431. /*
  432. * Apparently, "D:mypath" is the same as "D:\\mypath" if
  433. * D: is not the current drive. However, if D: is the
  434. * current drive, then "D:mypath" is a relative path. Ugh.
  435. */
  436. if (path[2] == '\\') /* maybe an absolute path? */
  437. strcpy(retval, path);
  438. else /* definitely an absolute path. */
  439. {
  440. if (path[0] == currentDir[0]) /* current drive; relative. */
  441. {
  442. strcpy(retval, currentDir);
  443. strcat(retval, path + 2);
  444. } /* if */
  445. else /* not current drive; absolute. */
  446. {
  447. retval[0] = path[0];
  448. retval[1] = ':';
  449. retval[2] = '\\';
  450. strcpy(retval + 3, path + 2);
  451. } /* else */
  452. } /* else */
  453. } /* if */
  454. else /* no drive letter specified. */
  455. {
  456. if (path[0] == '\\') /* absolute path. */
  457. {
  458. retval[0] = currentDir[0];
  459. retval[1] = ':';
  460. strcpy(retval + 2, path);
  461. } /* if */
  462. else
  463. {
  464. strcpy(retval, currentDir);
  465. strcat(retval, path);
  466. } /* else */
  467. } /* else */
  468. free(currentDir);
  469. } /* else */
  470. /* (whew.) Ok, now take out "." and ".." path entries... */
  471. p = retval;
  472. while ( (p = strstr(p, "\\.")) != NULL)
  473. {
  474. /* it's a "." entry that doesn't end the string. */
  475. if (p[2] == '\\')
  476. memmove(p + 1, p + 3, strlen(p + 3) + 1);
  477. /* it's a "." entry that ends the string. */
  478. else if (p[2] == '\0')
  479. p[0] = '\0';
  480. /* it's a ".." entry. */
  481. else if (p[2] == '.')
  482. {
  483. char *prevEntry = p - 1;
  484. while ((prevEntry != retval) && (*prevEntry != '\\'))
  485. prevEntry--;
  486. if (prevEntry == retval) /* make it look like a "." entry. */
  487. memmove(p + 1, p + 2, strlen(p + 2) + 1);
  488. else
  489. {
  490. if (p[3] != '\0') /* doesn't end string. */
  491. *prevEntry = '\0';
  492. else /* ends string. */
  493. memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
  494. p = prevEntry;
  495. } /* else */
  496. } /* else if */
  497. else
  498. {
  499. p++; /* look past current char. */
  500. } /* else */
  501. } /* while */
  502. /* shrink the retval's memory block if possible... */
  503. p = (char *) realloc(retval, strlen(retval) + 1);
  504. if (p != NULL)
  505. retval = p;
  506. return(retval);
  507. } /* __PHYSFS_platformRealPath */
  508. int __PHYSFS_platformMkDir(const char *path)
  509. {
  510. DWORD rc = CreateDirectory(path, NULL);
  511. BAIL_IF_MACRO(rc == 0, win32strerror(), 0);
  512. return(1);
  513. } /* __PHYSFS_platformMkDir */
  514. /*
  515. * Get OS info and save the important parts.
  516. *
  517. * Returns non-zero if successful, otherwise it returns zero on failure.
  518. */
  519. static int getOSInfo(void)
  520. {
  521. #if 0 /* we don't actually use this at the moment, but may in the future. */
  522. OSVERSIONINFO OSVersionInfo; /* Information about the OS */
  523. OSVersionInfo.dwOSVersionInfoSize = sizeof(OSVersionInfo);
  524. BAIL_IF_MACRO(!GetVersionEx(&OSVersionInfo), win32strerror(), 0);
  525. /* Set to TRUE if we are runnign a WinNT based OS 4.0 or greater */
  526. runningNT = ((OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) &&
  527. (OSVersionInfo.dwMajorVersion >= 4));
  528. #endif
  529. return(1);
  530. } /* getOSInfo */
  531. /*
  532. * Some things we want/need are in external DLLs that may or may not be
  533. * available, based on the operating system, etc. This function loads those
  534. * libraries and hunts down the needed pointers.
  535. *
  536. * Libraries that are one-shot deals, or better loaded as needed, are loaded
  537. * elsewhere (see determineUserDir()).
  538. *
  539. * Returns zero if a needed library couldn't load, non-zero if we have enough
  540. * to go on (which means some useful but non-crucial libraries may _NOT_ be
  541. * loaded; check the related module-scope variables).
  542. */
  543. static int loadLibraries(void)
  544. {
  545. /* !!! FIXME: Make this table driven? */
  546. int allNeededLibrariesLoaded = 1; /* flip to zero as needed. */
  547. libKernel32 = LoadLibrary("kernel32.dll");
  548. if (libKernel32)
  549. {
  550. pGetFileAttributesEx = (LPFNGETFILEATTRIBUTESEX)
  551. GetProcAddress(libKernel32, "GetFileAttributesExA");
  552. } /* if */
  553. /* add other DLLs here... */
  554. /* see if there's any reason to keep kernel32.dll around... */
  555. if (libKernel32)
  556. {
  557. if ((pGetFileAttributesEx == NULL) /* && (somethingElse == NULL) */ )
  558. {
  559. FreeLibrary(libKernel32);
  560. libKernel32 = NULL;
  561. } /* if */
  562. } /* if */
  563. return(allNeededLibrariesLoaded);
  564. } /* loadLibraries */
  565. int __PHYSFS_platformInit(void)
  566. {
  567. BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
  568. BAIL_IF_MACRO(!loadLibraries(), NULL, 0);
  569. BAIL_IF_MACRO(!determineUserDir(), NULL, 0);
  570. return(1); /* It's all good */
  571. } /* __PHYSFS_platformInit */
  572. int __PHYSFS_platformDeinit(void)
  573. {
  574. if (userDir != NULL)
  575. {
  576. free(userDir);
  577. userDir = NULL;
  578. } /* if */
  579. return(1); /* It's all good */
  580. } /* __PHYSFS_platformDeinit */
  581. static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly)
  582. {
  583. HANDLE fileHandle;
  584. win32file *retval;
  585. fileHandle = CreateFile(fname, mode, FILE_SHARE_READ, NULL,
  586. creation, FILE_ATTRIBUTE_NORMAL, NULL);
  587. BAIL_IF_MACRO(fileHandle == INVALID_HANDLE_VALUE, win32strerror(), NULL);
  588. retval = malloc(sizeof (win32file));
  589. if (retval == NULL)
  590. {
  591. CloseHandle(fileHandle);
  592. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  593. } /* if */
  594. retval->readonly = rdonly;
  595. retval->handle = fileHandle;
  596. return(retval);
  597. } /* doOpen */
  598. void *__PHYSFS_platformOpenRead(const char *filename)
  599. {
  600. return(doOpen(filename, GENERIC_READ, OPEN_EXISTING, 1));
  601. } /* __PHYSFS_platformOpenRead */
  602. void *__PHYSFS_platformOpenWrite(const char *filename)
  603. {
  604. return(doOpen(filename, GENERIC_WRITE, CREATE_ALWAYS, 0));
  605. } /* __PHYSFS_platformOpenWrite */
  606. void *__PHYSFS_platformOpenAppend(const char *filename)
  607. {
  608. void *retval = doOpen(filename, GENERIC_WRITE, OPEN_ALWAYS, 0);
  609. if (retval != NULL)
  610. {
  611. HANDLE h = ((win32file *) retval)->handle;
  612. if (SetFilePointer(h, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER)
  613. {
  614. const char *err = win32strerror();
  615. CloseHandle(h);
  616. free(retval);
  617. BAIL_MACRO(err, NULL);
  618. } /* if */
  619. } /* if */
  620. return(retval);
  621. } /* __PHYSFS_platformOpenAppend */
  622. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
  623. PHYSFS_uint32 size, PHYSFS_uint32 count)
  624. {
  625. HANDLE FileHandle = ((win32file *) opaque)->handle;
  626. DWORD CountOfBytesRead;
  627. PHYSFS_sint64 retval;
  628. /* Read data from the file */
  629. /*!!! - uint32 might be a greater # than DWORD */
  630. if(!ReadFile(FileHandle, buffer, count * size, &CountOfBytesRead, NULL))
  631. {
  632. BAIL_MACRO(win32strerror(), -1);
  633. } /* if */
  634. else
  635. {
  636. /* Return the number of "objects" read. */
  637. /* !!! - What if not the right amount of bytes was read to make an object? */
  638. retval = CountOfBytesRead / size;
  639. } /* else */
  640. return(retval);
  641. } /* __PHYSFS_platformRead */
  642. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  643. PHYSFS_uint32 size, PHYSFS_uint32 count)
  644. {
  645. HANDLE FileHandle = ((win32file *) opaque)->handle;
  646. DWORD CountOfBytesWritten;
  647. PHYSFS_sint64 retval;
  648. /* Read data from the file */
  649. /*!!! - uint32 might be a greater # than DWORD */
  650. if(!WriteFile(FileHandle, buffer, count * size, &CountOfBytesWritten, NULL))
  651. {
  652. BAIL_MACRO(win32strerror(), -1);
  653. } /* if */
  654. else
  655. {
  656. /* Return the number of "objects" read. */
  657. /*!!! - What if not the right number of bytes was written? */
  658. retval = CountOfBytesWritten / size;
  659. } /* else */
  660. return(retval);
  661. } /* __PHYSFS_platformWrite */
  662. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  663. {
  664. HANDLE FileHandle = ((win32file *) opaque)->handle;
  665. DWORD HighOrderPos;
  666. DWORD rc;
  667. /* Get the high order 32-bits of the position */
  668. HighOrderPos = HIGHORDER_UINT64(pos);
  669. /*!!! SetFilePointer needs a signed 64-bit value. */
  670. /* Move pointer "pos" count from start of file */
  671. rc = SetFilePointer(FileHandle, LOWORDER_UINT64(pos),
  672. &HighOrderPos, FILE_BEGIN);
  673. if ((rc == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
  674. BAIL_MACRO(win32strerror(), 0);
  675. return(1); /* No error occured */
  676. } /* __PHYSFS_platformSeek */
  677. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  678. {
  679. HANDLE FileHandle = ((win32file *) opaque)->handle;
  680. DWORD HighPos = 0;
  681. DWORD LowPos;
  682. PHYSFS_sint64 retval;
  683. /* Get current position */
  684. LowPos = SetFilePointer(FileHandle, 0, &HighPos, FILE_CURRENT);
  685. if ((LowPos == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
  686. {
  687. BAIL_MACRO(win32strerror(), 0);
  688. } /* if */
  689. else
  690. {
  691. /* Combine the high/low order to create the 64-bit position value */
  692. retval = (((PHYSFS_uint64) HighPos) << 32) | LowPos;
  693. assert(retval >= 0);
  694. } /* else */
  695. return(retval);
  696. } /* __PHYSFS_platformTell */
  697. PHYSFS_sint64 __PHYSFS_platformFileLength(void *opaque)
  698. {
  699. HANDLE FileHandle = ((win32file *) opaque)->handle;
  700. DWORD SizeHigh;
  701. DWORD SizeLow;
  702. PHYSFS_sint64 retval;
  703. SizeLow = GetFileSize(FileHandle, &SizeHigh);
  704. if ((SizeLow == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
  705. {
  706. BAIL_MACRO(win32strerror(), -1);
  707. } /* if */
  708. else
  709. {
  710. /* Combine the high/low order to create the 64-bit position value */
  711. retval = (((PHYSFS_uint64) SizeHigh) << 32) | SizeLow;
  712. assert(retval >= 0);
  713. } /* else */
  714. return(retval);
  715. } /* __PHYSFS_platformFileLength */
  716. int __PHYSFS_platformEOF(void *opaque)
  717. {
  718. PHYSFS_sint64 FilePosition;
  719. int retval = 0;
  720. /* Get the current position in the file */
  721. if ((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
  722. {
  723. /* Non-zero if EOF is equal to the file length */
  724. retval = FilePosition == __PHYSFS_platformFileLength(opaque);
  725. } /* if */
  726. return(retval);
  727. } /* __PHYSFS_platformEOF */
  728. int __PHYSFS_platformFlush(void *opaque)
  729. {
  730. win32file *fh = ((win32file *) opaque);
  731. if (!fh->readonly)
  732. BAIL_IF_MACRO(!FlushFileBuffers(fh->handle), win32strerror(), 0);
  733. return(1);
  734. } /* __PHYSFS_platformFlush */
  735. int __PHYSFS_platformClose(void *opaque)
  736. {
  737. HANDLE FileHandle = ((win32file *) opaque)->handle;
  738. BAIL_IF_MACRO(!CloseHandle(FileHandle), win32strerror(), 0);
  739. free(opaque);
  740. return(1);
  741. } /* __PHYSFS_platformClose */
  742. int __PHYSFS_platformDelete(const char *path)
  743. {
  744. /* If filename is a folder */
  745. if (GetFileAttributes(path) == FILE_ATTRIBUTE_DIRECTORY)
  746. {
  747. BAIL_IF_MACRO(!RemoveDirectory(path), win32strerror(), 0);
  748. } /* if */
  749. else
  750. {
  751. BAIL_IF_MACRO(!DeleteFile(path), win32strerror(), 0);
  752. } /* else */
  753. return(1); /* if you got here, it worked. */
  754. } /* __PHYSFS_platformDelete */
  755. void *__PHYSFS_platformCreateMutex(void)
  756. {
  757. return((void *) CreateMutex(NULL, FALSE, NULL));
  758. } /* __PHYSFS_platformCreateMutex */
  759. void __PHYSFS_platformDestroyMutex(void *mutex)
  760. {
  761. CloseHandle((HANDLE) mutex);
  762. } /* __PHYSFS_platformDestroyMutex */
  763. int __PHYSFS_platformGrabMutex(void *mutex)
  764. {
  765. return(WaitForSingleObject((HANDLE) mutex, INFINITE) != WAIT_FAILED);
  766. } /* __PHYSFS_platformGrabMutex */
  767. void __PHYSFS_platformReleaseMutex(void *mutex)
  768. {
  769. ReleaseMutex((HANDLE) mutex);
  770. } /* __PHYSFS_platformReleaseMutex */
  771. static PHYSFS_sint64 FileTimeToPhysfsTime(const FILETIME *ft)
  772. {
  773. SYSTEMTIME st_utc;
  774. SYSTEMTIME st_localtz;
  775. TIME_ZONE_INFORMATION tzi;
  776. DWORD tzid;
  777. PHYSFS_sint64 retval;
  778. struct tm tm;
  779. BAIL_IF_MACRO(!FileTimeToSystemTime(ft, &st_utc), win32strerror(), -1);
  780. tzid = GetTimeZoneInformation(&tzi);
  781. BAIL_IF_MACRO(tzid == TIME_ZONE_ID_INVALID, win32strerror(), -1);
  782. /* (This API is unsupported and fails on non-NT systems. */
  783. if (!SystemTimeToTzSpecificLocalTime(&tzi, &st_utc, &st_localtz))
  784. {
  785. /* do it by hand. Grumble... */
  786. ULARGE_INTEGER ui64;
  787. FILETIME new_ft;
  788. ui64.LowPart = ft->dwLowDateTime;
  789. ui64.HighPart = ft->dwHighDateTime;
  790. if (tzid == TIME_ZONE_ID_STANDARD)
  791. tzi.Bias += tzi.StandardBias;
  792. else if (tzid == TIME_ZONE_ID_DAYLIGHT)
  793. tzi.Bias += tzi.DaylightBias;
  794. /* convert from minutes to 100-nanosecond increments... */
  795. #if 0 /* For compilers that puke on 64-bit math. */
  796. /* goddamn this is inefficient... */
  797. while (tzi.Bias > 0)
  798. {
  799. DWORD tmp = ui64.LowPart - 60000000;
  800. if ((ui64.LowPart < tmp) && (tmp > 60000000))
  801. ui64.HighPart--;
  802. ui64.LowPart = tmp;
  803. tzi.Bias--;
  804. } /* while */
  805. while (tzi.Bias < 0)
  806. {
  807. DWORD tmp = ui64.LowPart + 60000000;
  808. if ((ui64.LowPart > tmp) && (tmp < 60000000))
  809. ui64.HighPart++;
  810. ui64.LowPart = tmp;
  811. tzi.Bias++;
  812. } /* while */
  813. #else
  814. ui64.QuadPart -= (((LONGLONG) tzi.Bias) * (600000000));
  815. #endif
  816. /* Move it back into a FILETIME structure... */
  817. new_ft.dwLowDateTime = ui64.LowPart;
  818. new_ft.dwHighDateTime = ui64.HighPart;
  819. /* Convert to something human-readable... */
  820. if (!FileTimeToSystemTime(&new_ft, &st_localtz))
  821. BAIL_MACRO(win32strerror(), -1);
  822. } /* if */
  823. /* Convert to a format that mktime() can grok... */
  824. tm.tm_sec = st_localtz.wSecond;
  825. tm.tm_min = st_localtz.wMinute;
  826. tm.tm_hour = st_localtz.wHour;
  827. tm.tm_mday = st_localtz.wDay;
  828. tm.tm_mon = st_localtz.wMonth - 1;
  829. tm.tm_year = st_localtz.wYear - 1900;
  830. tm.tm_wday = -1 /*st_localtz.wDayOfWeek*/;
  831. tm.tm_yday = -1;
  832. tm.tm_isdst = -1;
  833. /* Convert to a format PhysicsFS can grok... */
  834. retval = (PHYSFS_sint64) mktime(&tm);
  835. BAIL_IF_MACRO(retval == -1, strerror(errno), -1);
  836. return(retval);
  837. } /* FileTimeToPhysfsTime */
  838. PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
  839. {
  840. PHYSFS_sint64 retval = -1;
  841. WIN32_FILE_ATTRIBUTE_DATA attrData;
  842. memset(&attrData, '\0', sizeof (attrData));
  843. if (pGetFileAttributesEx != NULL)
  844. {
  845. if (pGetFileAttributesEx(fname, GetFileExInfoStandard, &attrData))
  846. {
  847. /* 0 return value indicates an error or not supported */
  848. if ( (attrData.ftLastWriteTime.dwHighDateTime != 0) ||
  849. (attrData.ftLastWriteTime.dwLowDateTime != 0) )
  850. {
  851. retval = FileTimeToPhysfsTime(&attrData.ftLastWriteTime);
  852. } /* if */
  853. } /* if */
  854. } /* if */
  855. if (retval == -1) /* try a fallback... */
  856. {
  857. /* !!! FIXME: uhh...? */
  858. } /* if */
  859. return(retval);
  860. /*return(FileTimeToPhysfsTime(&attrData.ftCreationTime));*/
  861. } /* __PHYSFS_platformGetLastModTime */
  862. /* end of win32.c ... */