win32.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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 <ctype.h>
  15. #include <time.h>
  16. #include <assert.h>
  17. #define __PHYSICSFS_INTERNAL__
  18. #include "physfs_internal.h"
  19. #ifndef _MSC_VER /* for Cygwin, etc. */
  20. #define _alloca alloca
  21. #endif
  22. #define LOWORDER_UINT64(pos) (PHYSFS_uint32)(pos & 0x00000000FFFFFFFF)
  23. #define HIGHORDER_UINT64(pos) (PHYSFS_uint32)(pos & 0xFFFFFFFF00000000)
  24. const char *__PHYSFS_platformDirSeparator = "\\";
  25. static int runningNT = 0; /* TRUE if NT derived OS */
  26. static OSVERSIONINFO OSVersionInfo; /* Information about the OS */
  27. static char *ProfileDirectory = NULL; /* User profile folder */
  28. /* Users without the platform SDK don't have this defined. The original docs
  29. for SetFilePointer() just said to compare with 0xFFFFFFF, so this should
  30. work as desired */
  31. #ifndef INVALID_SET_FILE_POINTER
  32. #define INVALID_SET_FILE_POINTER 0xFFFFFFFF
  33. #endif
  34. /*
  35. * Figure out what the last failing Win32 API call was, and
  36. * generate a human-readable string for the error message.
  37. *
  38. * The return value is a static buffer that is overwritten with
  39. * each call to this function.
  40. */
  41. static const char *win32strerror(void)
  42. {
  43. static TCHAR msgbuf[255];
  44. FormatMessage(
  45. FORMAT_MESSAGE_FROM_SYSTEM |
  46. FORMAT_MESSAGE_IGNORE_INSERTS,
  47. NULL,
  48. GetLastError(),
  49. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
  50. msgbuf,
  51. sizeof (msgbuf) / sizeof (TCHAR),
  52. NULL
  53. );
  54. return((const char *) msgbuf);
  55. } /* win32strerror */
  56. /*
  57. * Uninitialize any NT specific stuff done in doNTInit().
  58. *
  59. * Return zero if there was a catastrophic failure and non-zero otherwise.
  60. */
  61. static int doNTDeinit(void)
  62. {
  63. /* nothing NT-specific to deinit at this point. */
  64. return 1; /* It's all good */
  65. } /* doNTDeinit */
  66. typedef BOOL (STDMETHODCALLTYPE FAR * LPFNGETUSERPROFILEDIR) (
  67. HANDLE hToken,
  68. LPTSTR lpProfileDir,
  69. LPDWORD lpcchSize);
  70. /*
  71. * Initialize any NT specific stuff. This includes any OS based on NT.
  72. *
  73. * Return zero if there was a catastrophic failure and non-zero otherwise.
  74. */
  75. static int doNTInit(void)
  76. {
  77. DWORD pathsize = 0;
  78. char dummy[1];
  79. BOOL rc = 0;
  80. HANDLE ProcessHandle = NULL; /* Current process handle */
  81. HANDLE AccessTokenHandle = NULL; /* Security handle to process */
  82. LPFNGETUSERPROFILEDIR GetUserProfileDirectory = NULL;
  83. HMODULE lib = NULL;
  84. const char *err = NULL;
  85. /* Hooray for spaghetti code! */
  86. lib = LoadLibrary("userenv.dll");
  87. if (!lib)
  88. goto ntinit_failed;
  89. /* !!! FIXME: Handle Unicode? */
  90. GetUserProfileDirectory = (LPFNGETUSERPROFILEDIR)
  91. GetProcAddress(lib, "GetUserProfileDirectoryA");
  92. if (!GetUserProfileDirectory)
  93. goto ntinit_failed;
  94. /* Create a process handle associated with the current process ID */
  95. ProcessHandle = GetCurrentProcess();
  96. /* Create a process access token handle */
  97. if(!OpenProcessToken(ProcessHandle, TOKEN_QUERY, &AccessTokenHandle))
  98. goto ntinit_failed; /* we need that token to get the profile dir. */
  99. /* Should fail. Will write the size of the profile path in pathsize */
  100. /* Second parameter can't be NULL or the function fails. */
  101. rc = GetUserProfileDirectory(AccessTokenHandle, dummy, &pathsize);
  102. assert(!rc); /* success?! */
  103. /* Allocate memory for the profile directory */
  104. ProfileDirectory = (char *) malloc(pathsize);
  105. if (ProfileDirectory == NULL)
  106. {
  107. err = ERR_OUT_OF_MEMORY;
  108. goto ntinit_failed;
  109. } /* if */
  110. /* Try to get the profile directory */
  111. if(!GetUserProfileDirectory(AccessTokenHandle, ProfileDirectory, &pathsize))
  112. goto ntinit_failed;
  113. goto ntinit_succeeded; /* We made it: hit the showers. */
  114. ntinit_failed:
  115. if (err == NULL) /* set an error string if we haven't yet. */
  116. __PHYSFS_setError(win32strerror());
  117. if (ProfileDirectory != NULL)
  118. {
  119. free(ProfileDirectory);
  120. ProfileDirectory = NULL;
  121. } /* if */
  122. /* drop through and clean up the rest of the stuff... */
  123. ntinit_succeeded:
  124. if (lib != NULL)
  125. FreeLibrary(lib);
  126. if (AccessTokenHandle != NULL)
  127. CloseHandle(AccessTokenHandle);
  128. return ((err == NULL) ? 1 : 0);
  129. } /* doNTInit */
  130. static BOOL MediaInDrive(const char *DriveLetter)
  131. {
  132. UINT OldErrorMode;
  133. DWORD DummyValue;
  134. BOOL ReturnValue;
  135. /* Prevent windows warning message to appear when checking media size */
  136. OldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);
  137. /* If this function succeeds, there's media in the drive */
  138. ReturnValue = GetDiskFreeSpace(DriveLetter, &DummyValue, &DummyValue, &DummyValue, &DummyValue);
  139. /* Revert back to old windows error handler */
  140. SetErrorMode(OldErrorMode);
  141. return ReturnValue;
  142. } /* MediaInDrive */
  143. char **__PHYSFS_platformDetectAvailableCDs(void)
  144. {
  145. char **retval = (char **) malloc(sizeof (char *));
  146. int cd_count = 1; /* We count the NULL entry. */
  147. char drive_str[4] = "x:\\";
  148. for (drive_str[0] = 'A'; drive_str[0] <= 'Z'; drive_str[0]++)
  149. {
  150. if (GetDriveType(drive_str) == DRIVE_CDROM && MediaInDrive(drive_str))
  151. {
  152. char **tmp = realloc(retval, sizeof (char *) * cd_count + 1);
  153. if (tmp)
  154. {
  155. retval = tmp;
  156. retval[cd_count-1] = (char *) malloc(4);
  157. if (retval[cd_count-1])
  158. {
  159. strcpy(retval[cd_count-1], drive_str);
  160. cd_count++;
  161. } /* if */
  162. } /* if */
  163. } /* if */
  164. } /* for */
  165. retval[cd_count - 1] = NULL;
  166. return(retval);
  167. } /* __PHYSFS_detectAvailableCDs */
  168. static char *getExePath(const char *argv0)
  169. {
  170. char *filepart = NULL;
  171. char *retval;
  172. DWORD buflen;
  173. retval = (char *) malloc(sizeof (TCHAR) * (MAX_PATH + 1));
  174. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  175. buflen = GetModuleFileName(NULL, retval, MAX_PATH + 1);
  176. if (buflen == 0)
  177. {
  178. const char *err = win32strerror();
  179. free(retval);
  180. BAIL_MACRO(err, NULL);
  181. } /* if */
  182. retval[buflen] = '\0'; /* does API always null-terminate the string? */
  183. /* make sure the string was not truncated. */
  184. if (__PHYSFS_platformStricmp(&retval[buflen - 4], ".exe") == 0)
  185. {
  186. char *ptr = strrchr(retval, '\\');
  187. if (ptr != NULL)
  188. {
  189. *(ptr + 1) = '\0'; /* chop off filename. */
  190. /* free up the bytes we didn't actually use. */
  191. ptr = (char *) realloc(retval, strlen(retval) + 1);
  192. if (ptr != NULL)
  193. retval = ptr;
  194. return(retval);
  195. } /* if */
  196. } /* if */
  197. /* if any part of the previous approach failed, try SearchPath()... */
  198. buflen = SearchPath(NULL, argv0, NULL, buflen, NULL, NULL);
  199. retval = (char *) realloc(retval, buflen);
  200. BAIL_IF_MACRO(!retval, ERR_OUT_OF_MEMORY, NULL);
  201. SearchPath(NULL, argv0, NULL, buflen, retval, &filepart);
  202. return(retval);
  203. } /* getExePath */
  204. char *__PHYSFS_platformCalcBaseDir(const char *argv0)
  205. {
  206. if (strchr(argv0, '\\') != NULL) /* default behaviour can handle this. */
  207. return(NULL);
  208. return(getExePath(argv0));
  209. } /* __PHYSFS_platformCalcBaseDir */
  210. char *__PHYSFS_platformGetUserName(void)
  211. {
  212. DWORD bufsize = 0;
  213. LPTSTR retval = NULL;
  214. if (GetUserName(NULL, &bufsize) == 0) /* This SHOULD fail. */
  215. {
  216. retval = (LPTSTR) malloc(bufsize);
  217. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  218. if (GetUserName(retval, &bufsize) == 0) /* ?! */
  219. {
  220. __PHYSFS_setError(win32strerror());
  221. free(retval);
  222. retval = NULL;
  223. } /* if */
  224. } /* if */
  225. return((char *) retval);
  226. } /* __PHYSFS_platformGetUserName */
  227. char *__PHYSFS_platformGetUserDir(void)
  228. {
  229. char *retval = (char *) malloc(strlen(ProfileDirectory) + 1);
  230. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  231. strcpy(retval, ProfileDirectory); /* calculated at init time. */
  232. return retval;
  233. } /* __PHYSFS_platformGetUserDir */
  234. PHYSFS_uint64 __PHYSFS_platformGetThreadID(void)
  235. {
  236. return((PHYSFS_uint64)GetCurrentThreadId());
  237. } /* __PHYSFS_platformGetThreadID */
  238. /* ...make this Cygwin AND Visual C friendly... */
  239. int __PHYSFS_platformStricmp(const char *x, const char *y)
  240. {
  241. #if (defined _MSC_VER)
  242. return(stricmp(x, y));
  243. #else
  244. int ux, uy;
  245. do
  246. {
  247. ux = toupper((int) *x);
  248. uy = toupper((int) *y);
  249. if (ux > uy)
  250. return(1);
  251. else if (ux < uy)
  252. return(-1);
  253. x++;
  254. y++;
  255. } while ((ux) && (uy));
  256. return(0);
  257. #endif
  258. } /* __PHYSFS_platformStricmp */
  259. int __PHYSFS_platformExists(const char *fname)
  260. {
  261. return(GetFileAttributes(fname) != 0xffffffff);
  262. } /* __PHYSFS_platformExists */
  263. int __PHYSFS_platformIsSymLink(const char *fname)
  264. {
  265. return(0); /* no symlinks on win32. */
  266. } /* __PHYSFS_platformIsSymlink */
  267. int __PHYSFS_platformIsDirectory(const char *fname)
  268. {
  269. return((GetFileAttributes(fname) & FILE_ATTRIBUTE_DIRECTORY) != 0);
  270. } /* __PHYSFS_platformIsDirectory */
  271. char *__PHYSFS_platformCvtToDependent(const char *prepend,
  272. const char *dirName,
  273. const char *append)
  274. {
  275. int len = ((prepend) ? strlen(prepend) : 0) +
  276. ((append) ? strlen(append) : 0) +
  277. strlen(dirName) + 1;
  278. char *retval = malloc(len);
  279. char *p;
  280. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  281. if (prepend)
  282. strcpy(retval, prepend);
  283. else
  284. retval[0] = '\0';
  285. strcat(retval, dirName);
  286. if (append)
  287. strcat(retval, append);
  288. for (p = strchr(retval, '/'); p != NULL; p = strchr(p + 1, '/'))
  289. *p = '\\';
  290. return(retval);
  291. } /* __PHYSFS_platformCvtToDependent */
  292. /* Much like my college days, try to sleep for 10 milliseconds at a time... */
  293. void __PHYSFS_platformTimeslice(void)
  294. {
  295. Sleep(10);
  296. } /* __PHYSFS_platformTimeslice */
  297. LinkedStringList *__PHYSFS_platformEnumerateFiles(const char *dirname,
  298. int omitSymLinks)
  299. {
  300. LinkedStringList *retval = NULL;
  301. LinkedStringList *l = NULL;
  302. LinkedStringList *prev = NULL;
  303. HANDLE dir;
  304. WIN32_FIND_DATA ent;
  305. char *SearchPath;
  306. size_t len = strlen(dirname);
  307. /* Allocate a new string for path, maybe '\\', "*", and NULL terminator */
  308. SearchPath = (char *) _alloca(len + 3);
  309. BAIL_IF_MACRO(SearchPath == NULL, ERR_OUT_OF_MEMORY, NULL);
  310. /* Copy current dirname */
  311. strcpy(SearchPath, dirname);
  312. /* if there's no '\\' at the end of the path, stick one in there. */
  313. if (SearchPath[len - 1] != '\\')
  314. {
  315. SearchPath[len++] = '\\';
  316. SearchPath[len] = '\0';
  317. } /* if */
  318. /* Append the "*" to the end of the string */
  319. strcat(SearchPath, "*");
  320. dir = FindFirstFile(SearchPath, &ent);
  321. BAIL_IF_MACRO(dir == INVALID_HANDLE_VALUE, win32strerror(), NULL);
  322. do
  323. {
  324. if (strcmp(ent.cFileName, ".") == 0)
  325. continue;
  326. if (strcmp(ent.cFileName, "..") == 0)
  327. continue;
  328. l = (LinkedStringList *) malloc(sizeof (LinkedStringList));
  329. if (l == NULL)
  330. break;
  331. l->str = (char *) malloc(strlen(ent.cFileName) + 1);
  332. if (l->str == NULL)
  333. {
  334. free(l);
  335. break;
  336. } /* if */
  337. strcpy(l->str, ent.cFileName);
  338. if (retval == NULL)
  339. retval = l;
  340. else
  341. prev->next = l;
  342. prev = l;
  343. l->next = NULL;
  344. } while (FindNextFile(dir, &ent) != 0);
  345. FindClose(dir);
  346. return(retval);
  347. } /* __PHYSFS_platformEnumerateFiles */
  348. char *__PHYSFS_platformCurrentDir(void)
  349. {
  350. LPTSTR retval;
  351. DWORD buflen = 0;
  352. buflen = GetCurrentDirectory(buflen, NULL);
  353. retval = (LPTSTR) malloc(sizeof (TCHAR) * (buflen + 2));
  354. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  355. GetCurrentDirectory(buflen, retval);
  356. if (retval[buflen - 2] != '\\')
  357. strcat(retval, "\\");
  358. return((char *) retval);
  359. } /* __PHYSFS_platformCurrentDir */
  360. /* this could probably use a cleanup. */
  361. char *__PHYSFS_platformRealPath(const char *path)
  362. {
  363. char *retval = NULL;
  364. char *p = NULL;
  365. BAIL_IF_MACRO(path == NULL, ERR_INVALID_ARGUMENT, NULL);
  366. BAIL_IF_MACRO(*path == '\0', ERR_INVALID_ARGUMENT, NULL);
  367. retval = (char *) malloc(MAX_PATH);
  368. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  369. /*
  370. * If in \\server\path format, it's already an absolute path.
  371. * We'll need to check for "." and ".." dirs, though, just in case.
  372. */
  373. if ((path[0] == '\\') && (path[1] == '\\'))
  374. strcpy(retval, path);
  375. else
  376. {
  377. char *currentDir = __PHYSFS_platformCurrentDir();
  378. if (currentDir == NULL)
  379. {
  380. free(retval);
  381. BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
  382. } /* if */
  383. if (path[1] == ':') /* drive letter specified? */
  384. {
  385. /*
  386. * Apparently, "D:mypath" is the same as "D:\\mypath" if
  387. * D: is not the current drive. However, if D: is the
  388. * current drive, then "D:mypath" is a relative path. Ugh.
  389. */
  390. if (path[2] == '\\') /* maybe an absolute path? */
  391. strcpy(retval, path);
  392. else /* definitely an absolute path. */
  393. {
  394. if (path[0] == currentDir[0]) /* current drive; relative. */
  395. {
  396. strcpy(retval, currentDir);
  397. strcat(retval, path + 2);
  398. } /* if */
  399. else /* not current drive; absolute. */
  400. {
  401. retval[0] = path[0];
  402. retval[1] = ':';
  403. retval[2] = '\\';
  404. strcpy(retval + 3, path + 2);
  405. } /* else */
  406. } /* else */
  407. } /* if */
  408. else /* no drive letter specified. */
  409. {
  410. if (path[0] == '\\') /* absolute path. */
  411. {
  412. retval[0] = currentDir[0];
  413. retval[1] = ':';
  414. strcpy(retval + 2, path);
  415. } /* if */
  416. else
  417. {
  418. strcpy(retval, currentDir);
  419. strcat(retval, path);
  420. } /* else */
  421. } /* else */
  422. free(currentDir);
  423. } /* else */
  424. /* (whew.) Ok, now take out "." and ".." path entries... */
  425. p = retval;
  426. while ( (p = strstr(p, "\\.")) != NULL)
  427. {
  428. /* it's a "." entry that doesn't end the string. */
  429. if (p[2] == '\\')
  430. memmove(p + 1, p + 3, strlen(p + 3) + 1);
  431. /* it's a "." entry that ends the string. */
  432. else if (p[2] == '\0')
  433. p[0] = '\0';
  434. /* it's a ".." entry. */
  435. else if (p[2] == '.')
  436. {
  437. char *prevEntry = p - 1;
  438. while ((prevEntry != retval) && (*prevEntry != '\\'))
  439. prevEntry--;
  440. if (prevEntry == retval) /* make it look like a "." entry. */
  441. memmove(p + 1, p + 2, strlen(p + 2) + 1);
  442. else
  443. {
  444. if (p[3] != '\0') /* doesn't end string. */
  445. *prevEntry = '\0';
  446. else /* ends string. */
  447. memmove(prevEntry + 1, p + 4, strlen(p + 4) + 1);
  448. p = prevEntry;
  449. } /* else */
  450. } /* else if */
  451. else
  452. {
  453. p++; /* look past current char. */
  454. } /* else */
  455. } /* while */
  456. /* shrink the retval's memory block if possible... */
  457. p = (char *) realloc(retval, strlen(retval) + 1);
  458. if (p != NULL)
  459. retval = p;
  460. return(retval);
  461. } /* __PHYSFS_platformRealPath */
  462. int __PHYSFS_platformMkDir(const char *path)
  463. {
  464. DWORD rc = CreateDirectory(path, NULL);
  465. BAIL_IF_MACRO(rc == 0, win32strerror(), 0);
  466. return(1);
  467. } /* __PHYSFS_platformMkDir */
  468. /*
  469. * Get OS info and save it.
  470. *
  471. * Returns non-zero if successful, otherwise it returns zero on failure.
  472. */
  473. int getOSInfo(void)
  474. {
  475. /* Get OS info */
  476. OSVersionInfo.dwOSVersionInfoSize = sizeof(OSVersionInfo);
  477. BAIL_IF_MACRO(!GetVersionEx(&OSVersionInfo), win32strerror(), 0);
  478. /* Set to TRUE if we are runnign a WinNT based OS 4.0 or greater */
  479. runningNT = (OSVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) &&
  480. (OSVersionInfo.dwMajorVersion > 3);
  481. return 1;
  482. }
  483. int __PHYSFS_platformInit(void)
  484. {
  485. BAIL_IF_MACRO(!getOSInfo(), NULL, 0);
  486. /* If running an NT system (NT/Win2k/XP, etc...) */
  487. if(runningNT)
  488. {
  489. BAIL_IF_MACRO(!doNTInit(), NULL, 0);
  490. } /* if */
  491. else
  492. {
  493. /* Profile directory is the exe path on 95/98/ME systems. */
  494. ProfileDirectory = getExePath(NULL);
  495. BAIL_IF_MACRO(ProfileDirectory == NULL, win32strerror(), 0);
  496. } /* else */
  497. return 1; /* It's all good */
  498. }
  499. int __PHYSFS_platformDeinit(void)
  500. {
  501. if (runningNT)
  502. {
  503. BAIL_IF_MACRO(!doNTDeinit(), NULL, 0);
  504. } /* if */
  505. if (ProfileDirectory != NULL)
  506. {
  507. free(ProfileDirectory);
  508. ProfileDirectory = NULL;
  509. } /* if */
  510. return 1; /* It's all good */
  511. }
  512. void *__PHYSFS_platformOpenRead(const char *filename)
  513. {
  514. HANDLE FileHandle;
  515. /* Open an existing file for read only. File can be opened by others
  516. who request read access on the file only. */
  517. FileHandle = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
  518. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  519. BAIL_IF_MACRO(FileHandle == INVALID_HANDLE_VALUE, win32strerror(), NULL);
  520. return (void *)FileHandle;
  521. }
  522. void *__PHYSFS_platformOpenWrite(const char *filename)
  523. {
  524. HANDLE FileHandle;
  525. /* Open an existing file for write only. File can be opened by others
  526. who request read access to the file only */
  527. FileHandle = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  528. CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  529. BAIL_IF_MACRO(FileHandle == INVALID_HANDLE_VALUE, win32strerror(), NULL);
  530. return (void *)FileHandle;
  531. }
  532. void *__PHYSFS_platformOpenAppend(const char *filename)
  533. {
  534. HANDLE FileHandle;
  535. /* Open an existing file for appending only. File can be opened by others
  536. who request read access to the file only. */
  537. FileHandle = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  538. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  539. BAIL_IF_MACRO(FileHandle == INVALID_HANDLE_VALUE, win32strerror(), NULL);
  540. return (void *)FileHandle;
  541. }
  542. PHYSFS_sint64 __PHYSFS_platformRead(void *opaque, void *buffer,
  543. PHYSFS_uint32 size, PHYSFS_uint32 count)
  544. {
  545. HANDLE FileHandle;
  546. DWORD CountOfBytesRead;
  547. PHYSFS_sint64 retval;
  548. /* Cast the generic handle to a Win32 handle */
  549. FileHandle = (HANDLE)opaque;
  550. /* Read data from the file */
  551. /*!!! - uint32 might be a greater # than DWORD */
  552. if(!ReadFile(FileHandle, buffer, count * size, &CountOfBytesRead, NULL))
  553. {
  554. BAIL_MACRO(win32strerror(), -1);
  555. } /* if */
  556. else
  557. {
  558. /* Return the number of "objects" read. */
  559. /* !!! - What if not the right amount of bytes was read to make an object? */
  560. retval = CountOfBytesRead / size;
  561. } /* else */
  562. return retval;
  563. }
  564. PHYSFS_sint64 __PHYSFS_platformWrite(void *opaque, const void *buffer,
  565. PHYSFS_uint32 size, PHYSFS_uint32 count)
  566. {
  567. HANDLE FileHandle;
  568. DWORD CountOfBytesWritten;
  569. PHYSFS_sint64 retval;
  570. /* Cast the generic handle to a Win32 handle */
  571. FileHandle = (HANDLE)opaque;
  572. /* Read data from the file */
  573. /*!!! - uint32 might be a greater # than DWORD */
  574. if(!WriteFile(FileHandle, buffer, count * size, &CountOfBytesWritten, NULL))
  575. {
  576. BAIL_MACRO(win32strerror(), -1);
  577. } /* if */
  578. else
  579. {
  580. /* Return the number of "objects" read. */
  581. /*!!! - What if not the right number of bytes was written? */
  582. retval = CountOfBytesWritten / size;
  583. } /* else */
  584. return retval;
  585. }
  586. int __PHYSFS_platformSeek(void *opaque, PHYSFS_uint64 pos)
  587. {
  588. HANDLE FileHandle;
  589. int retval;
  590. DWORD HighOrderPos;
  591. /* Cast the generic handle to a Win32 handle */
  592. FileHandle = (HANDLE)opaque;
  593. /* Get the high order 32-bits of the position */
  594. HighOrderPos = HIGHORDER_UINT64(pos);
  595. /*!!! SetFilePointer needs a signed 64-bit value. */
  596. /* Move pointer "pos" count from start of file */
  597. if((SetFilePointer(FileHandle, LOWORDER_UINT64(pos), &HighOrderPos, FILE_BEGIN)
  598. == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
  599. {
  600. /* An error occured. Set the error to GetLastError */
  601. __PHYSFS_setError(win32strerror());
  602. retval = 0;
  603. }
  604. else
  605. {
  606. /* No error occured */
  607. retval = 1;
  608. }
  609. return retval;
  610. }
  611. PHYSFS_sint64 __PHYSFS_platformTell(void *opaque)
  612. {
  613. HANDLE FileHandle;
  614. DWORD HighOrderPos = 0;
  615. DWORD LowOrderPos;
  616. PHYSFS_sint64 retval;
  617. /* Cast the generic handle to a Win32 handle */
  618. FileHandle = (HANDLE)opaque;
  619. /* Get current position */
  620. if(((LowOrderPos = SetFilePointer(FileHandle, 0, &HighOrderPos, FILE_CURRENT))
  621. == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
  622. {
  623. /* Set the error to GetLastError */
  624. __PHYSFS_setError(win32strerror());
  625. /* We errored out */
  626. retval = 0;
  627. }
  628. else
  629. {
  630. /* Combine the high/low order to create the 64-bit position value */
  631. retval = HighOrderPos;
  632. retval = retval << 32;
  633. retval |= LowOrderPos;
  634. }
  635. /*!!! Can't find a file pointer routine?!?!?!!?!?*/
  636. return retval;
  637. }
  638. PHYSFS_sint64 __PHYSFS_platformFileLength(void *handle)
  639. {
  640. HANDLE FileHandle;
  641. DWORD FileSizeHigh;
  642. DWORD FileSizeLow;
  643. PHYSFS_sint64 retval;
  644. /* Cast the generic handle to a Win32 handle */
  645. FileHandle = (HANDLE)handle;
  646. /* Get the file size. Condition evaluates to TRUE if an error occured */
  647. if(((FileSizeLow = GetFileSize(FileHandle, &FileSizeHigh))
  648. == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR))
  649. {
  650. BAIL_MACRO(win32strerror(), -1);
  651. } /* if */
  652. else
  653. {
  654. /* Combine the high/low order to create the 64-bit position value */
  655. retval = FileSizeHigh;
  656. retval = retval << 32;
  657. retval |= FileSizeLow;
  658. } /* else */
  659. return retval;
  660. }
  661. int __PHYSFS_platformEOF(void *opaque)
  662. {
  663. HANDLE FileHandle;
  664. PHYSFS_sint64 FilePosition;
  665. int retval = 0;
  666. /* Cast the generic handle to a Win32 handle */
  667. FileHandle = (HANDLE)opaque;
  668. /* Get the current position in the file */
  669. if((FilePosition = __PHYSFS_platformTell(opaque)) != 0)
  670. {
  671. /* Non-zero if EOF is equal to the file length */
  672. retval = FilePosition == __PHYSFS_platformFileLength(opaque);
  673. }
  674. return retval;
  675. }
  676. int __PHYSFS_platformFlush(void *opaque)
  677. {
  678. HANDLE FileHandle;
  679. int retval;
  680. /* Cast the generic handle to a Win32 handle */
  681. FileHandle = (HANDLE)opaque;
  682. /* Close the file */
  683. if(!(retval = FlushFileBuffers(FileHandle)))
  684. {
  685. /* Set the error to GetLastError */
  686. __PHYSFS_setError(win32strerror());
  687. }
  688. return retval;
  689. }
  690. int __PHYSFS_platformClose(void *opaque)
  691. {
  692. HANDLE FileHandle;
  693. int retval;
  694. /* Cast the generic handle to a Win32 handle */
  695. FileHandle = (HANDLE)opaque;
  696. /* Close the file */
  697. if(!(retval = CloseHandle(FileHandle)))
  698. {
  699. /* Set the error to GetLastError */
  700. __PHYSFS_setError(win32strerror());
  701. }
  702. return retval;
  703. }
  704. int __PHYSFS_platformDelete(const char *path)
  705. {
  706. int retval;
  707. /* If filename is a folder */
  708. if(GetFileAttributes(path) == FILE_ATTRIBUTE_DIRECTORY)
  709. {
  710. retval = RemoveDirectory(path);
  711. }
  712. else
  713. {
  714. retval = DeleteFile(path);
  715. }
  716. if(!retval)
  717. {
  718. /* Set the error to GetLastError */
  719. __PHYSFS_setError(win32strerror());
  720. }
  721. return retval;
  722. }
  723. void *__PHYSFS_platformCreateMutex(void)
  724. {
  725. return (void *)CreateMutex(NULL, FALSE, NULL);
  726. }
  727. void __PHYSFS_platformDestroyMutex(void *mutex)
  728. {
  729. CloseHandle((HANDLE)mutex);
  730. }
  731. int __PHYSFS_platformGrabMutex(void *mutex)
  732. {
  733. int retval;
  734. if(WaitForSingleObject((HANDLE)mutex, INFINITE) == WAIT_FAILED)
  735. {
  736. /* Our wait failed for some unknown reason */
  737. retval = 0;
  738. }
  739. else
  740. {
  741. /* Good to go */
  742. retval = 1;
  743. }
  744. return retval;
  745. }
  746. void __PHYSFS_platformReleaseMutex(void *mutex)
  747. {
  748. ReleaseMutex((HANDLE)mutex);
  749. }
  750. static time_t FileTimeToTimeT(FILETIME *ft)
  751. {
  752. SYSTEMTIME st_utc;
  753. SYSTEMTIME st_localtz;
  754. TIME_ZONE_INFORMATION TimeZoneInfo;
  755. struct tm tm;
  756. FileTimeToSystemTime(ft, &st_utc);
  757. GetTimeZoneInformation(&TimeZoneInfo);
  758. SystemTimeToTzSpecificLocalTime(&TimeZoneInfo, &st_utc, &st_localtz);
  759. tm.tm_sec = st_localtz.wSecond;
  760. tm.tm_min = st_localtz.wMinute;
  761. tm.tm_hour = st_localtz.wHour;
  762. tm.tm_mday = st_localtz.wDay;
  763. tm.tm_mon = st_localtz.wMonth - 1;
  764. tm.tm_year = st_localtz.wYear - 1900;
  765. tm.tm_wday = st_localtz.wDayOfWeek;
  766. tm.tm_yday = -1;
  767. tm.tm_isdst = -1;
  768. return mktime(&tm);
  769. } /* FileTimeToTimeT */
  770. PHYSFS_sint64 __PHYSFS_platformGetLastModTime(const char *fname)
  771. {
  772. WIN32_FILE_ATTRIBUTE_DATA AttributeData;
  773. GetFileAttributesEx(fname, GetFileExInfoStandard, &AttributeData);
  774. /* 0 return value indicates an error or not supported */
  775. if(AttributeData.ftLastWriteTime.dwHighDateTime == 0 &&
  776. AttributeData.ftLastWriteTime.dwLowDateTime == 0)
  777. {
  778. /* Return error */
  779. BAIL_MACRO(win32strerror(), -1);
  780. }
  781. /* Return UNIX time_t version of last write time */
  782. return (PHYSFS_sint64)FileTimeToTimeT(&AttributeData.ftLastWriteTime);
  783. /*return (PHYSFS_sint64)FileTimeToTimeT(&AttributeData.ftCreationTime);*/
  784. } /* __PHYSFS_platformGetLastModTime */
  785. /* end of win32.c ... */