win32.c 26 KB

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