windows.c 32 KB

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