WinRTIO.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /* -*- mode: c; tab-width: 4; c-basic-offset: 4; c-file-style: "linux" -*- */
  2. //
  3. // WinRTIO.cpp: UWP C-style file I/O wrapper for SDLPal.
  4. // Author: Lou Yihua @ 2016-2017
  5. //
  6. // Copyright (c) 2009-2011, Wei Mingzhi <whistler_wmz@users.sf.net>.
  7. // Copyright (c) 2011-2017 SDLPAL development team.
  8. // All rights reserved.
  9. //
  10. // This file is part of SDLPAL.
  11. //
  12. // SDLPAL is free software: you can redistribute it and/or modify
  13. // it under the terms of the GNU General Public License as published by
  14. // the Free Software Foundation, either version 3 of the License, or
  15. // (at your option) any later version.
  16. //
  17. // This program is distributed in the hope that it will be useful,
  18. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. // GNU General Public License for more details.
  21. //
  22. // You should have received a copy of the GNU General Public License
  23. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. //
  25. #include <wrl.h>
  26. #include <string>
  27. #include <map>
  28. #include <DXGI.h>
  29. #include <shcore.h>
  30. #include <unordered_set>
  31. #include "AsyncHelper.h"
  32. #include "StringHelper.h"
  33. using namespace Windows::Storage;
  34. using namespace Windows::Storage::Streams;
  35. #pragma comment(lib, "ShCore.lib")
  36. #define PAL_PATH_NAME "SDLPAL"
  37. static const LARGE_INTEGER liZero = { 0 };
  38. static const void* const _SIGNATURE = &liZero;
  39. /*========================*/
  40. typedef struct WRT_FILE WRT_FILE;
  41. struct WRT_FILE
  42. {
  43. const void* sig;
  44. IStream* stream;
  45. CRITICAL_SECTION cs;
  46. bool readable;
  47. bool writable;
  48. bool binary;
  49. WRT_FILE() : sig(&liZero), stream(nullptr), readable(false), writable(false), binary(false) { InitializeCriticalSectionEx(&cs, 4000, 0); }
  50. WRT_FILE(IRandomAccessStream^ s, bool r, bool w, bool b)
  51. : sig(&liZero), stream(nullptr), readable(r), writable(w), binary(b)
  52. {
  53. HRESULT hr;
  54. InitializeCriticalSectionEx(&cs, 4000, 0);
  55. if (FAILED(hr = CreateStreamOverRandomAccessStream(s, IID_PPV_ARGS(&stream))))
  56. throw ref new Platform::Exception(hr);
  57. }
  58. ~WRT_FILE() { if (stream) stream->Release(); DeleteCriticalSection(&cs); }
  59. };
  60. static std::map<std::string, StorageFile^> g_specialFiles;
  61. static std::map<std::string, StorageFolder^> g_specialFolders;
  62. class CriticalSection
  63. {
  64. public:
  65. CriticalSection(CRITICAL_SECTION& cs) : m_cs(cs) { EnterCriticalSection(&m_cs); }
  66. ~CriticalSection() { LeaveCriticalSection(&m_cs); }
  67. private:
  68. CRITICAL_SECTION& m_cs;
  69. };
  70. class Event
  71. {
  72. public:
  73. Event() : _eventHandle(CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS)) {}
  74. ~Event() { CloseHandle(_eventHandle); }
  75. operator HANDLE() { return _eventHandle; }
  76. private:
  77. HANDLE _eventHandle;
  78. };
  79. static const std::string get_directory(const char* _Filename)
  80. {
  81. auto ptr = _Filename;
  82. while (*ptr == '/' || *ptr == '\\') ptr++;
  83. std::string directory((ptr != _Filename) ? "\\" : "");
  84. while (*ptr)
  85. {
  86. std::string temp;
  87. auto pos = ptr;
  88. while (*pos && *pos != '/' && *pos != '\\') pos++;
  89. if (*pos)
  90. {
  91. directory.append(ptr, pos - ptr);
  92. directory.append("\\");
  93. }
  94. while (*pos == '/' || *pos == '\\') pos++;
  95. ptr = pos;
  96. }
  97. return directory;
  98. }
  99. static const std::string get_filename(const char* _Filename)
  100. {
  101. auto ptr = _Filename + strlen(_Filename);
  102. while (ptr > _Filename && *ptr != '/' && *ptr != '\\') ptr--;
  103. if (*ptr == '/' || *ptr == '\\') ptr++;
  104. return ptr;
  105. }
  106. extern "C" std::map<std::string, StorageFile^>* get_special_files_map() { return &g_specialFiles; }
  107. extern "C" std::map<std::string, StorageFolder^>* get_special_folders_map() { return &g_specialFolders; }
  108. extern "C"
  109. errno_t WRT_fopen_s(WRT_FILE ** pFile, const char * _Filename, const char * _Mode)
  110. {
  111. if (nullptr == _Filename || nullptr == _Mode || nullptr == pFile) return EINVAL;
  112. *pFile = nullptr;
  113. bool r, w, b = false;
  114. switch (*_Mode)
  115. {
  116. case 'a': w = true; r = false; break;
  117. case 'w': w = true; r = false; break;
  118. case 'r': w = false; r = true; break;
  119. default: return EINVAL;
  120. }
  121. for (size_t i = 1; i < strlen(_Mode); i++)
  122. {
  123. switch (_Mode[i])
  124. {
  125. case '+': r = w = true; break;
  126. case 'b': b = true; break;
  127. case 't': b = false; break;
  128. default: return EINVAL;
  129. }
  130. }
  131. try
  132. {
  133. Event eventHandle;
  134. // If the file belongs to so-called 'special files' (i.e., specified in configuration file), then return its object directly
  135. if (g_specialFiles.find(_Filename) != g_specialFiles.end())
  136. {
  137. *pFile = new WRT_FILE(AWait(g_specialFiles[_Filename]->OpenAsync(w ? FileAccessMode::ReadWrite : FileAccessMode::Read), eventHandle), r, w, b);
  138. return 0;
  139. }
  140. auto directory = get_directory(_Filename);
  141. auto filename = get_filename(_Filename);
  142. StorageFolder^ folder = nullptr;
  143. // If the file's folder belongs to so-called 'special folders' (i.e., specified in configuration file), then use the cache folder object
  144. for (auto i = g_specialFolders.begin(); directory.length() > 0 && i != g_specialFolders.end(); i++)
  145. {
  146. if (_strnicmp(i->first.c_str(), directory.c_str(), i->first.size()) == 0)
  147. {
  148. folder = i->second;
  149. if (directory.length() > i->first.length())
  150. {
  151. size_t pos = i->first.length(), next = directory.find('\\', pos);
  152. while (next != std::string::npos)
  153. {
  154. folder = AWait(folder->GetFolderAsync(ConvertString(std::string(&directory[pos], next - pos))), eventHandle);
  155. next = directory.find('\\', pos = next + 1);
  156. }
  157. if (pos < directory.length())
  158. {
  159. folder = AWait(folder->GetFolderAsync(ConvertString(std::string(&directory[pos], directory.length() - pos))), eventHandle);
  160. }
  161. }
  162. }
  163. }
  164. // The try get folder directly by its full path
  165. if (!folder && directory.length())
  166. {
  167. folder = AWait(StorageFolder::GetFolderFromPathAsync(ConvertString(directory)), eventHandle);
  168. }
  169. // As a last sort, use app's local folder
  170. if (!folder)
  171. {
  172. folder = ApplicationData::Current->LocalFolder;
  173. }
  174. StorageFile^ file = nullptr;
  175. switch (*_Mode)
  176. {
  177. case 'a':
  178. file = AWait(folder->CreateFileAsync(ConvertString(filename), CreationCollisionOption::OpenIfExists), eventHandle);
  179. break;
  180. case 'w':
  181. file = AWait(folder->CreateFileAsync(ConvertString(filename), CreationCollisionOption::ReplaceExisting), eventHandle);
  182. break;
  183. case 'r':
  184. file = AWait(folder->GetFileAsync(ConvertString(filename)), eventHandle);
  185. break;
  186. }
  187. if (file)
  188. {
  189. *pFile = new WRT_FILE(AWait(file->OpenAsync(w ? FileAccessMode::ReadWrite : FileAccessMode::Read), eventHandle), r, w, b);
  190. }
  191. }
  192. catch (Platform::AccessDeniedException^)
  193. {
  194. return EACCES;
  195. }
  196. catch (Platform::Exception^)
  197. {
  198. return EIO;
  199. }
  200. return 0;
  201. }
  202. extern "C"
  203. WRT_FILE* WRT_fopen(const char * _Filename, const char * _Mode)
  204. {
  205. WRT_FILE* ret;
  206. int err = WRT_fopen_s(&ret, _Filename, _Mode);
  207. _set_errno(err);
  208. return err ? nullptr : ret;
  209. }
  210. extern "C"
  211. int WRT_fclose(WRT_FILE * _File)
  212. {
  213. if (!_File || _File->sig != _SIGNATURE) return fclose((FILE*)_File);
  214. delete _File;
  215. return 0;
  216. }
  217. extern "C"
  218. int WRT_feof(WRT_FILE * _File)
  219. {
  220. if (!_File || _File->sig != _SIGNATURE) return feof((FILE*)_File);
  221. STATSTG st;
  222. ULARGE_INTEGER uli;
  223. CriticalSection cs(_File->cs);
  224. if (SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, &uli)) &&
  225. SUCCEEDED(_File->stream->Stat(&st, STATFLAG_NONAME)))
  226. return uli.QuadPart >= st.cbSize.QuadPart;
  227. else
  228. return 1;
  229. }
  230. extern "C"
  231. int WRT_fseeki64(WRT_FILE * _File, long long _Offset, int _Origin)
  232. {
  233. if (!_File || _File->sig != _SIGNATURE) return _fseeki64((FILE*)_File, _Offset, _Origin);
  234. CriticalSection cs(_File->cs);
  235. LARGE_INTEGER liOffset;
  236. liOffset.QuadPart = _Offset;
  237. return SUCCEEDED(_File->stream->Seek(liOffset, _Origin, NULL)) ? 0 : -1;
  238. }
  239. extern "C"
  240. int WRT_fseek(WRT_FILE * _File, long _Offset, int _Origin)
  241. {
  242. return WRT_fseeki64(_File, _Offset, _Origin);
  243. }
  244. extern "C"
  245. long long WRT_ftelli64(WRT_FILE * _File)
  246. {
  247. if (!_File || _File->sig != _SIGNATURE) return _ftelli64((FILE*)_File);
  248. CriticalSection cs(_File->cs);
  249. unsigned long long pos;
  250. return SUCCEEDED(_File->stream->Seek(liZero, STREAM_SEEK_CUR, (PULARGE_INTEGER)&pos)) ? pos : -1;
  251. }
  252. extern "C"
  253. size_t WRT_ftell(WRT_FILE * _File)
  254. {
  255. return (size_t)WRT_ftelli64(_File);
  256. }
  257. extern "C"
  258. size_t WRT_fread(void * _DstBuf, size_t _ElementSize, size_t _Count, WRT_FILE * _File)
  259. {
  260. if (!_File || _File->sig != _SIGNATURE) return fread(_DstBuf, _ElementSize, _Count, (FILE*)_File);
  261. if (!_File->readable || _ElementSize == 0 || _Count == 0 || !_DstBuf) return 0;
  262. CriticalSection cs(_File->cs);
  263. unsigned long cbRead;
  264. return SUCCEEDED(_File->stream->Read(_DstBuf, (ULONG)(_ElementSize * _Count), &cbRead)) ? cbRead / _ElementSize : 0;
  265. }
  266. extern "C"
  267. size_t WRT_fwrite(const void * _Str, size_t _Size, size_t _Count, WRT_FILE * _File)
  268. {
  269. if (!_File || _File->sig != _SIGNATURE) return fwrite(_Str, _Size, _Count, (FILE*)_File);
  270. if (!_File->writable || !_Str || _Size == 0 || _Count == 0) return 0;
  271. CriticalSection cs(_File->cs);
  272. unsigned long cbWrite;
  273. return SUCCEEDED(_File->stream->Write(_Str, (ULONG)(_Size * _Count), &cbWrite)) ? cbWrite / _Size : 0;
  274. }
  275. extern "C"
  276. int WRT_fflush(WRT_FILE * _File)
  277. {
  278. if (!_File || _File->sig != _SIGNATURE) return fflush((FILE*)_File);
  279. if (!_File->writable) return 0;
  280. CriticalSection cs(_File->cs);
  281. return SUCCEEDED(_File->stream->Commit(STGC_DEFAULT)) ? 0 : EOF;
  282. }
  283. static int WRT_fgetc_nolock(WRT_FILE * _File)
  284. {
  285. unsigned long cbRead;
  286. unsigned char buf;
  287. return _File->stream->Read(&buf, 1, &cbRead) == S_OK ? buf : EOF;
  288. }
  289. extern "C"
  290. int WRT_fgetc(WRT_FILE * _File)
  291. {
  292. if (!_File || _File->sig != _SIGNATURE) return fgetc((FILE*)_File);
  293. CriticalSection cs(_File->cs);
  294. return _File->readable ? WRT_fgetc_nolock(_File) : EOF;
  295. }
  296. extern "C"
  297. char* WRT_fgets(char * _Buf, int _MaxCount, WRT_FILE * _File)
  298. {
  299. if (!_File || _File->sig != _SIGNATURE) return fgets(_Buf, _MaxCount, (FILE*)_File);
  300. if (!_File->readable || !_Buf || _MaxCount <= 0) return nullptr;
  301. CriticalSection cs(_File->cs);
  302. int n = 0, flag = 0, ch;
  303. while (n < _MaxCount - 1 && EOF != (ch = WRT_fgetc_nolock(_File)))
  304. {
  305. if (flag)
  306. {
  307. if (ch != '\n')
  308. _Buf[n++] = '\r';
  309. flag = 0;
  310. }
  311. if (ch != '\r')
  312. {
  313. _Buf[n++] = ch;
  314. if (ch == '\n') break;
  315. }
  316. else
  317. flag = 1;
  318. }
  319. if (n > 0)
  320. {
  321. _Buf[n] = '\0';
  322. return _Buf;
  323. }
  324. else
  325. return nullptr;
  326. }
  327. extern "C"
  328. int WRT_fputc(int _Ch, WRT_FILE * _File)
  329. {
  330. if (!_File || _File->sig != _SIGNATURE) return fputc(_Ch, (FILE*)_File);
  331. CriticalSection cs(_File->cs);
  332. unsigned long cbWrite;
  333. return _File->writable && _File->stream->Write(&_Ch, 1, &cbWrite) == S_OK ? cbWrite : EOF;
  334. }
  335. extern "C"
  336. int WRT_fputs(const char * _Str, WRT_FILE * _File)
  337. {
  338. if (!_File || _File->sig != _SIGNATURE) return fputs(_Str, (FILE*)_File);
  339. if (!_File->writable || !_Str) return EOF;
  340. const char *start = _Str;
  341. size_t length = strlen(_Str);
  342. unsigned long cbWrite;
  343. const char crlf[] = { '\r', '\n' };
  344. CriticalSection cs(_File->cs);
  345. while (true)
  346. {
  347. const char *ptr = start;
  348. while (*ptr && *ptr != '\n') ptr++;
  349. if (_File->stream->Write(start, (ULONG)(ptr - start), &cbWrite) != S_OK)
  350. return EOF;
  351. if (*ptr == '\n')
  352. {
  353. if (_File->stream->Write(crlf, 2, &cbWrite) != S_OK)
  354. return EOF;
  355. else
  356. start = ptr + 1;
  357. }
  358. else
  359. return (int)length;
  360. }
  361. }
  362. extern "C"
  363. int WRT_access(const char * const _FileName, int _AccessMode)
  364. {
  365. if (!_FileName || (_AccessMode & ~0x6) != 0)
  366. {
  367. _set_errno(EINVAL);
  368. return -1;
  369. }
  370. try
  371. {
  372. auto file = AWait(StorageFile::GetFileFromPathAsync(ConvertString(_FileName)));
  373. if ((file->Attributes & FileAttributes::Directory) != FileAttributes::Directory &&
  374. (file->Attributes & FileAttributes::ReadOnly) == FileAttributes::ReadOnly &&
  375. (_AccessMode & 0x2) != 0)
  376. {
  377. throw ref new Platform::AccessDeniedException();
  378. }
  379. return 0;
  380. }
  381. catch (AccessDeniedException^ e)
  382. {
  383. _set_errno(EACCES);
  384. return -1;
  385. }
  386. catch (Exception^ e)
  387. {
  388. if (e->HResult == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
  389. {
  390. _set_errno(ENOENT);
  391. }
  392. else
  393. {
  394. _set_errno(EINVAL);
  395. }
  396. return -1;
  397. }
  398. }