win32.c 25 KB

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