win32.c 30 KB

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