File.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "../IO/File.h"
  24. #include "../IO/FileSystem.h"
  25. #include "../IO/Log.h"
  26. #include "../IO/MemoryBuffer.h"
  27. #include "../IO/PackageFile.h"
  28. #include "../Core/Profiler.h"
  29. #include <cstdio>
  30. #include <LZ4/lz4.h>
  31. #include "../DebugNew.h"
  32. namespace Atomic
  33. {
  34. #ifdef WIN32
  35. static const wchar_t* openMode[] =
  36. {
  37. L"rb",
  38. L"wb",
  39. L"r+b",
  40. L"w+b"
  41. };
  42. #else
  43. static const char* openMode[] =
  44. {
  45. "rb",
  46. "wb",
  47. "r+b",
  48. "w+b"
  49. };
  50. #endif
  51. #ifdef ANDROID
  52. static const unsigned READ_BUFFER_SIZE = 32768;
  53. #endif
  54. static const unsigned SKIP_BUFFER_SIZE = 1024;
  55. File::File(Context* context) :
  56. Object(context),
  57. mode_(FILE_READ),
  58. handle_(0),
  59. #ifdef ANDROID
  60. assetHandle_(0),
  61. #endif
  62. readBufferOffset_(0),
  63. readBufferSize_(0),
  64. offset_(0),
  65. checksum_(0),
  66. compressed_(false),
  67. readSyncNeeded_(false),
  68. writeSyncNeeded_(false)
  69. {
  70. }
  71. File::File(Context* context, const String& fileName, FileMode mode) :
  72. Object(context),
  73. mode_(FILE_READ),
  74. handle_(0),
  75. #ifdef ANDROID
  76. assetHandle_(0),
  77. #endif
  78. readBufferOffset_(0),
  79. readBufferSize_(0),
  80. offset_(0),
  81. checksum_(0),
  82. compressed_(false),
  83. readSyncNeeded_(false),
  84. writeSyncNeeded_(false)
  85. {
  86. Open(fileName, mode);
  87. fullPath_ = fileName;
  88. }
  89. File::File(Context* context, PackageFile* package, const String& fileName) :
  90. Object(context),
  91. mode_(FILE_READ),
  92. handle_(0),
  93. #ifdef ANDROID
  94. assetHandle_(0),
  95. #endif
  96. readBufferOffset_(0),
  97. readBufferSize_(0),
  98. offset_(0),
  99. checksum_(0),
  100. compressed_(false),
  101. readSyncNeeded_(false),
  102. writeSyncNeeded_(false)
  103. {
  104. Open(package, fileName);
  105. }
  106. File::~File()
  107. {
  108. Close();
  109. }
  110. bool File::Open(const String& fileName, FileMode mode)
  111. {
  112. Close();
  113. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  114. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  115. {
  116. LOGERROR("Access denied to " + fileName);
  117. return false;
  118. }
  119. #ifdef ANDROID
  120. if (fileName.StartsWith("/apk/"))
  121. {
  122. if (mode != FILE_READ)
  123. {
  124. LOGERROR("Only read mode is supported for asset files");
  125. return false;
  126. }
  127. assetHandle_ = SDL_RWFromFile(fileName.Substring(5).CString(), "rb");
  128. if (!assetHandle_)
  129. {
  130. LOGERROR("Could not open asset file " + fileName);
  131. return false;
  132. }
  133. else
  134. {
  135. fileName_ = fileName;
  136. mode_ = mode;
  137. position_ = 0;
  138. offset_ = 0;
  139. checksum_ = 0;
  140. size_ = assetHandle_->hidden.androidio.size;
  141. readBuffer_ = new unsigned char[READ_BUFFER_SIZE];
  142. readBufferOffset_ = 0;
  143. readBufferSize_ = 0;
  144. return true;
  145. }
  146. }
  147. #endif
  148. if (fileName.Empty())
  149. {
  150. LOGERROR("Could not open file with empty name");
  151. return false;
  152. }
  153. #ifdef WIN32
  154. handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode]);
  155. #else
  156. handle_ = fopen(GetNativePath(fileName).CString(), openMode[mode]);
  157. #endif
  158. // If file did not exist in readwrite mode, retry with write-update mode
  159. if (mode == FILE_READWRITE && !handle_)
  160. {
  161. #ifdef WIN32
  162. handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode + 1]);
  163. #else
  164. handle_ = fopen(GetNativePath(fileName).CString(), openMode[mode + 1]);
  165. #endif
  166. }
  167. if (!handle_)
  168. {
  169. LOGERROR("Could not open file " + fileName);
  170. return false;
  171. }
  172. fileName_ = fileName;
  173. mode_ = mode;
  174. position_ = 0;
  175. offset_ = 0;
  176. checksum_ = 0;
  177. compressed_ = false;
  178. readSyncNeeded_ = false;
  179. writeSyncNeeded_ = false;
  180. fseek((FILE*)handle_, 0, SEEK_END);
  181. size_ = ftell((FILE*)handle_);
  182. fseek((FILE*)handle_, 0, SEEK_SET);
  183. return true;
  184. }
  185. bool File::Open(PackageFile* package, const String& fileName)
  186. {
  187. Close();
  188. if (!package)
  189. return false;
  190. const PackageEntry* entry = package->GetEntry(fileName);
  191. if (!entry)
  192. return false;
  193. #ifdef WIN32
  194. handle_ = _wfopen(GetWideNativePath(package->GetName()).CString(), L"rb");
  195. #else
  196. handle_ = fopen(GetNativePath(package->GetName()).CString(), "rb");
  197. #endif
  198. if (!handle_)
  199. {
  200. LOGERROR("Could not open package file " + fileName);
  201. return false;
  202. }
  203. fileName_ = fileName;
  204. mode_ = FILE_READ;
  205. offset_ = entry->offset_;
  206. checksum_ = entry->checksum_;
  207. position_ = 0;
  208. size_ = entry->size_;
  209. compressed_ = package->IsCompressed();
  210. readSyncNeeded_ = false;
  211. writeSyncNeeded_ = false;
  212. fseek((FILE*)handle_, offset_, SEEK_SET);
  213. return true;
  214. }
  215. unsigned File::Read(void* dest, unsigned size)
  216. {
  217. #ifdef ANDROID
  218. if (!handle_ && !assetHandle_)
  219. #else
  220. if (!handle_)
  221. #endif
  222. {
  223. // Do not log the error further here to prevent spamming the stderr stream
  224. return 0;
  225. }
  226. if (mode_ == FILE_WRITE)
  227. {
  228. LOGERROR("File not opened for reading");
  229. return 0;
  230. }
  231. if (size + position_ > size_)
  232. size = size_ - position_;
  233. if (!size)
  234. return 0;
  235. #ifdef ANDROID
  236. if (assetHandle_)
  237. {
  238. unsigned sizeLeft = size;
  239. unsigned char* destPtr = (unsigned char*)dest;
  240. while (sizeLeft)
  241. {
  242. if (readBufferOffset_ >= readBufferSize_)
  243. {
  244. readBufferSize_ = Min((int)size_ - position_, (int)READ_BUFFER_SIZE);
  245. readBufferOffset_ = 0;
  246. SDL_RWread(assetHandle_, readBuffer_.Get(), readBufferSize_, 1);
  247. }
  248. unsigned copySize = Min((int)(readBufferSize_ - readBufferOffset_), (int)sizeLeft);
  249. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  250. destPtr += copySize;
  251. sizeLeft -= copySize;
  252. readBufferOffset_ += copySize;
  253. position_ += copySize;
  254. }
  255. return size;
  256. }
  257. #endif
  258. if (compressed_)
  259. {
  260. unsigned sizeLeft = size;
  261. unsigned char* destPtr = (unsigned char*)dest;
  262. while (sizeLeft)
  263. {
  264. if (!readBuffer_ || readBufferOffset_ >= readBufferSize_)
  265. {
  266. unsigned char blockHeaderBytes[4];
  267. fread(blockHeaderBytes, sizeof blockHeaderBytes, 1, (FILE*)handle_);
  268. MemoryBuffer blockHeader(&blockHeaderBytes[0], sizeof blockHeaderBytes);
  269. unsigned unpackedSize = blockHeader.ReadUShort();
  270. unsigned packedSize = blockHeader.ReadUShort();
  271. if (!readBuffer_)
  272. {
  273. readBuffer_ = new unsigned char[unpackedSize];
  274. inputBuffer_ = new unsigned char[LZ4_compressBound(unpackedSize)];
  275. }
  276. /// \todo Handle errors
  277. fread(inputBuffer_.Get(), packedSize, 1, (FILE*)handle_);
  278. LZ4_decompress_fast((const char*)inputBuffer_.Get(), (char *)readBuffer_.Get(), unpackedSize);
  279. readBufferSize_ = unpackedSize;
  280. readBufferOffset_ = 0;
  281. }
  282. unsigned copySize = Min((int)(readBufferSize_ - readBufferOffset_), (int)sizeLeft);
  283. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  284. destPtr += copySize;
  285. sizeLeft -= copySize;
  286. readBufferOffset_ += copySize;
  287. position_ += copySize;
  288. }
  289. return size;
  290. }
  291. // Need to reassign the position due to internal buffering when transitioning from writing to reading
  292. if (readSyncNeeded_)
  293. {
  294. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  295. readSyncNeeded_ = false;
  296. }
  297. size_t ret = fread(dest, size, 1, (FILE*)handle_);
  298. if (ret != 1)
  299. {
  300. // Return to the position where the read began
  301. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  302. LOGERROR("Error while reading from file " + GetName());
  303. return 0;
  304. }
  305. writeSyncNeeded_ = true;
  306. position_ += size;
  307. return size;
  308. }
  309. unsigned File::Seek(unsigned position)
  310. {
  311. #ifdef ANDROID
  312. if (!handle_ && !assetHandle_)
  313. #else
  314. if (!handle_)
  315. #endif
  316. {
  317. // Do not log the error further here to prevent spamming the stderr stream
  318. return 0;
  319. }
  320. // Allow sparse seeks if writing
  321. if (mode_ == FILE_READ && position > size_)
  322. position = size_;
  323. #ifdef ANDROID
  324. if (assetHandle_)
  325. {
  326. SDL_RWseek(assetHandle_, position, SEEK_SET);
  327. position_ = position;
  328. readBufferOffset_ = 0;
  329. readBufferSize_ = 0;
  330. return position_;
  331. }
  332. #endif
  333. if (compressed_)
  334. {
  335. // Start over from the beginning
  336. if (position == 0)
  337. {
  338. position_ = 0;
  339. readBufferOffset_ = 0;
  340. readBufferSize_ = 0;
  341. fseek((FILE*)handle_, offset_, SEEK_SET);
  342. }
  343. // Skip bytes
  344. else if (position >= position_)
  345. {
  346. unsigned char skipBuffer[SKIP_BUFFER_SIZE];
  347. while (position > position_)
  348. Read(skipBuffer, Min((int)position - position_, (int)SKIP_BUFFER_SIZE));
  349. }
  350. else
  351. LOGERROR("Seeking backward in a compressed file is not supported");
  352. return position_;
  353. }
  354. fseek((FILE*)handle_, position + offset_, SEEK_SET);
  355. position_ = position;
  356. readSyncNeeded_ = false;
  357. writeSyncNeeded_ = false;
  358. return position_;
  359. }
  360. unsigned File::Write(const void* data, unsigned size)
  361. {
  362. if (!handle_)
  363. {
  364. // Do not log the error further here to prevent spamming the stderr stream
  365. return 0;
  366. }
  367. if (mode_ == FILE_READ)
  368. {
  369. LOGERROR("File not opened for writing");
  370. return 0;
  371. }
  372. if (!size)
  373. return 0;
  374. // Need to reassign the position due to internal buffering when transitioning from reading to writing
  375. if (writeSyncNeeded_)
  376. {
  377. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  378. writeSyncNeeded_ = false;
  379. }
  380. if (fwrite(data, size, 1, (FILE*)handle_) != 1)
  381. {
  382. // Return to the position where the write began
  383. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  384. LOGERROR("Error while writing to file " + GetName());
  385. return 0;
  386. }
  387. readSyncNeeded_ = true;
  388. position_ += size;
  389. if (position_ > size_)
  390. size_ = position_;
  391. return size;
  392. }
  393. unsigned File::GetChecksum()
  394. {
  395. if (offset_ || checksum_)
  396. return checksum_;
  397. #ifdef ANDROID
  398. if ((!handle_ && !assetHandle_) || mode_ == FILE_WRITE)
  399. #else
  400. if (!handle_ || mode_ == FILE_WRITE)
  401. #endif
  402. return 0;
  403. PROFILE(CalculateFileChecksum);
  404. unsigned oldPos = position_;
  405. checksum_ = 0;
  406. Seek(0);
  407. while (!IsEof())
  408. {
  409. unsigned char block[1024];
  410. unsigned readBytes = Read(block, 1024);
  411. for (unsigned i = 0; i < readBytes; ++i)
  412. checksum_ = SDBMHash(checksum_, block[i]);
  413. }
  414. Seek(oldPos);
  415. return checksum_;
  416. }
  417. void File::Close()
  418. {
  419. #ifdef ANDROID
  420. if (assetHandle_)
  421. {
  422. SDL_RWclose(assetHandle_);
  423. assetHandle_ = 0;
  424. }
  425. #endif
  426. readBuffer_.Reset();
  427. inputBuffer_.Reset();
  428. if (handle_)
  429. {
  430. fclose((FILE*)handle_);
  431. handle_ = 0;
  432. position_ = 0;
  433. size_ = 0;
  434. offset_ = 0;
  435. checksum_ = 0;
  436. }
  437. }
  438. void File::Flush()
  439. {
  440. if (handle_)
  441. fflush((FILE*)handle_);
  442. }
  443. void File::SetName(const String& name)
  444. {
  445. fileName_ = name;
  446. }
  447. bool File::IsOpen() const
  448. {
  449. #ifdef ANDROID
  450. return handle_ != 0 || assetHandle_ != 0;
  451. #else
  452. return handle_ != 0;
  453. #endif
  454. }
  455. void File::ReadText(String& text)
  456. {
  457. text.Clear();
  458. if (!size_)
  459. return;
  460. text.Resize(size_ + 1);
  461. Read((void*)text.CString(), size_);
  462. text[size_] = '\0';
  463. }
  464. }