File.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. //
  2. // Copyright (c) 2008-2015 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 "../Core/Profiler.h"
  24. #include "../IO/File.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../IO/PackageFile.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. L"a+b"
  42. };
  43. #else
  44. static const char* openMode[] =
  45. {
  46. "rb",
  47. "wb",
  48. "r+b",
  49. "w+b",
  50. "a+b"
  51. };
  52. #endif
  53. #ifdef ANDROID
  54. const char* APK = "/apk/";
  55. static const unsigned READ_BUFFER_SIZE = 32768;
  56. #endif
  57. static const unsigned SKIP_BUFFER_SIZE = 1024;
  58. File::File(Context* context) :
  59. Object(context),
  60. mode_(FILE_READ),
  61. handle_(0),
  62. #ifdef ANDROID
  63. assetHandle_(0),
  64. #endif
  65. readBufferOffset_(0),
  66. readBufferSize_(0),
  67. offset_(0),
  68. checksum_(0),
  69. compressed_(false),
  70. readSyncNeeded_(false),
  71. writeSyncNeeded_(false)
  72. {
  73. }
  74. File::File(Context* context, const String& fileName, FileMode mode) :
  75. Object(context),
  76. mode_(FILE_READ),
  77. handle_(0),
  78. #ifdef ANDROID
  79. assetHandle_(0),
  80. #endif
  81. readBufferOffset_(0),
  82. readBufferSize_(0),
  83. offset_(0),
  84. checksum_(0),
  85. compressed_(false),
  86. readSyncNeeded_(false),
  87. writeSyncNeeded_(false)
  88. {
  89. Open(fileName, mode);
  90. fullPath_ = fileName;
  91. }
  92. File::File(Context* context, PackageFile* package, const String& fileName) :
  93. Object(context),
  94. mode_(FILE_READ),
  95. handle_(0),
  96. #ifdef ANDROID
  97. assetHandle_(0),
  98. #endif
  99. readBufferOffset_(0),
  100. readBufferSize_(0),
  101. offset_(0),
  102. checksum_(0),
  103. compressed_(false),
  104. readSyncNeeded_(false),
  105. writeSyncNeeded_(false)
  106. {
  107. Open(package, fileName);
  108. }
  109. File::~File()
  110. {
  111. Close();
  112. }
  113. bool File::Open(const String& fileName, FileMode mode)
  114. {
  115. Close();
  116. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  117. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  118. {
  119. LOGERRORF("Access denied to %s", fileName.CString());
  120. return false;
  121. }
  122. #ifdef ANDROID
  123. if (IS_ASSET(fileName))
  124. {
  125. if (mode != FILE_READ)
  126. {
  127. LOGERROR("Only read mode is supported for asset files");
  128. return false;
  129. }
  130. assetHandle_ = SDL_RWFromFile(ASSET(fileName), "rb");
  131. if (!assetHandle_)
  132. {
  133. LOGERRORF("Could not open asset file %s", fileName.CString());
  134. return false;
  135. }
  136. else
  137. {
  138. fileName_ = fileName;
  139. mode_ = mode;
  140. position_ = 0;
  141. offset_ = 0;
  142. checksum_ = 0;
  143. size_ = assetHandle_->hidden.androidio.size;
  144. readBuffer_ = new unsigned char[READ_BUFFER_SIZE];
  145. readBufferOffset_ = 0;
  146. readBufferSize_ = 0;
  147. return true;
  148. }
  149. }
  150. #endif
  151. if (fileName.Empty())
  152. {
  153. LOGERROR("Could not open file with empty name");
  154. return false;
  155. }
  156. #ifdef WIN32
  157. handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode]);
  158. #else
  159. handle_ = fopen(GetNativePath(fileName).CString(), openMode[mode]);
  160. #endif
  161. // If file did not exist in readwrite mode, retry with write-update mode
  162. if (mode == FILE_READWRITE && !handle_)
  163. {
  164. #ifdef WIN32
  165. handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode + 1]);
  166. #else
  167. handle_ = fopen(GetNativePath(fileName).CString(), openMode[mode + 1]);
  168. #endif
  169. }
  170. if (!handle_)
  171. {
  172. LOGERRORF("Could not open file %s", fileName.CString());
  173. return false;
  174. }
  175. fileName_ = fileName;
  176. mode_ = mode;
  177. position_ = 0;
  178. offset_ = 0;
  179. checksum_ = 0;
  180. compressed_ = false;
  181. readSyncNeeded_ = false;
  182. writeSyncNeeded_ = false;
  183. fseek((FILE*)handle_, 0, SEEK_END);
  184. long size = ftell((FILE*)handle_);
  185. fseek((FILE*)handle_, 0, SEEK_SET);
  186. if (size > M_MAX_UNSIGNED)
  187. {
  188. LOGERRORF("Could not open file %s which is larger than 4GB", fileName.CString());
  189. Close();
  190. size_ = 0;
  191. return false;
  192. }
  193. size_ = (unsigned)size;
  194. return true;
  195. }
  196. bool File::Open(PackageFile* package, const String& fileName)
  197. {
  198. Close();
  199. if (!package)
  200. return false;
  201. const PackageEntry* entry = package->GetEntry(fileName);
  202. if (!entry)
  203. return false;
  204. #ifdef WIN32
  205. handle_ = _wfopen(GetWideNativePath(package->GetName()).CString(), L"rb");
  206. #else
  207. handle_ = fopen(GetNativePath(package->GetName()).CString(), "rb");
  208. #endif
  209. if (!handle_)
  210. {
  211. LOGERROR("Could not open package file " + fileName);
  212. return false;
  213. }
  214. fileName_ = fileName;
  215. mode_ = FILE_READ;
  216. offset_ = entry->offset_;
  217. checksum_ = entry->checksum_;
  218. position_ = 0;
  219. size_ = entry->size_;
  220. compressed_ = package->IsCompressed();
  221. readSyncNeeded_ = false;
  222. writeSyncNeeded_ = false;
  223. fseek((FILE*)handle_, offset_, SEEK_SET);
  224. return true;
  225. }
  226. unsigned File::Read(void* dest, unsigned size)
  227. {
  228. #ifdef ANDROID
  229. if (!handle_ && !assetHandle_)
  230. #else
  231. if (!handle_)
  232. #endif
  233. {
  234. // Do not log the error further here to prevent spamming the stderr stream
  235. return 0;
  236. }
  237. if (mode_ == FILE_WRITE)
  238. {
  239. LOGERROR("File not opened for reading");
  240. return 0;
  241. }
  242. if (size + position_ > size_)
  243. size = size_ - position_;
  244. if (!size)
  245. return 0;
  246. #ifdef ANDROID
  247. if (assetHandle_)
  248. {
  249. unsigned sizeLeft = size;
  250. unsigned char* destPtr = (unsigned char*)dest;
  251. while (sizeLeft)
  252. {
  253. if (readBufferOffset_ >= readBufferSize_)
  254. {
  255. readBufferSize_ = Min((int)size_ - position_, (int)READ_BUFFER_SIZE);
  256. readBufferOffset_ = 0;
  257. SDL_RWread(assetHandle_, readBuffer_.Get(), readBufferSize_, 1);
  258. }
  259. unsigned copySize = Min((int)(readBufferSize_ - readBufferOffset_), (int)sizeLeft);
  260. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  261. destPtr += copySize;
  262. sizeLeft -= copySize;
  263. readBufferOffset_ += copySize;
  264. position_ += copySize;
  265. }
  266. return size;
  267. }
  268. #endif
  269. if (compressed_)
  270. {
  271. unsigned sizeLeft = size;
  272. unsigned char* destPtr = (unsigned char*)dest;
  273. while (sizeLeft)
  274. {
  275. if (!readBuffer_ || readBufferOffset_ >= readBufferSize_)
  276. {
  277. unsigned char blockHeaderBytes[4];
  278. fread(blockHeaderBytes, sizeof blockHeaderBytes, 1, (FILE*)handle_);
  279. MemoryBuffer blockHeader(&blockHeaderBytes[0], sizeof blockHeaderBytes);
  280. unsigned unpackedSize = blockHeader.ReadUShort();
  281. unsigned packedSize = blockHeader.ReadUShort();
  282. if (!readBuffer_)
  283. {
  284. readBuffer_ = new unsigned char[unpackedSize];
  285. inputBuffer_ = new unsigned char[LZ4_compressBound(unpackedSize)];
  286. }
  287. /// \todo Handle errors
  288. fread(inputBuffer_.Get(), packedSize, 1, (FILE*)handle_);
  289. LZ4_decompress_fast((const char*)inputBuffer_.Get(), (char*)readBuffer_.Get(), unpackedSize);
  290. readBufferSize_ = unpackedSize;
  291. readBufferOffset_ = 0;
  292. }
  293. unsigned copySize = (unsigned)Min((int)(readBufferSize_ - readBufferOffset_), (int)sizeLeft);
  294. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  295. destPtr += copySize;
  296. sizeLeft -= copySize;
  297. readBufferOffset_ += copySize;
  298. position_ += copySize;
  299. }
  300. return size;
  301. }
  302. // Need to reassign the position due to internal buffering when transitioning from writing to reading
  303. if (readSyncNeeded_)
  304. {
  305. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  306. readSyncNeeded_ = false;
  307. }
  308. size_t ret = fread(dest, size, 1, (FILE*)handle_);
  309. if (ret != 1)
  310. {
  311. // Return to the position where the read began
  312. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  313. LOGERROR("Error while reading from file " + GetName());
  314. return 0;
  315. }
  316. writeSyncNeeded_ = true;
  317. position_ += size;
  318. return size;
  319. }
  320. unsigned File::Seek(unsigned position)
  321. {
  322. #ifdef ANDROID
  323. if (!handle_ && !assetHandle_)
  324. #else
  325. if (!handle_)
  326. #endif
  327. {
  328. // Do not log the error further here to prevent spamming the stderr stream
  329. return 0;
  330. }
  331. // Allow sparse seeks if writing
  332. if (mode_ == FILE_READ && position > size_)
  333. position = size_;
  334. #ifdef ANDROID
  335. if (assetHandle_)
  336. {
  337. SDL_RWseek(assetHandle_, position, SEEK_SET);
  338. position_ = position;
  339. readBufferOffset_ = 0;
  340. readBufferSize_ = 0;
  341. return position_;
  342. }
  343. #endif
  344. if (compressed_)
  345. {
  346. // Start over from the beginning
  347. if (position == 0)
  348. {
  349. position_ = 0;
  350. readBufferOffset_ = 0;
  351. readBufferSize_ = 0;
  352. fseek((FILE*)handle_, offset_, SEEK_SET);
  353. }
  354. // Skip bytes
  355. else if (position >= position_)
  356. {
  357. unsigned char skipBuffer[SKIP_BUFFER_SIZE];
  358. while (position > position_)
  359. Read(skipBuffer, (unsigned)Min((int)position - position_, (int)SKIP_BUFFER_SIZE));
  360. }
  361. else
  362. LOGERROR("Seeking backward in a compressed file is not supported");
  363. return position_;
  364. }
  365. fseek((FILE*)handle_, position + offset_, SEEK_SET);
  366. position_ = position;
  367. readSyncNeeded_ = false;
  368. writeSyncNeeded_ = false;
  369. return position_;
  370. }
  371. unsigned File::Write(const void* data, unsigned size)
  372. {
  373. if (!handle_)
  374. {
  375. // Do not log the error further here to prevent spamming the stderr stream
  376. return 0;
  377. }
  378. if (mode_ == FILE_READ)
  379. {
  380. LOGERROR("File not opened for writing");
  381. return 0;
  382. }
  383. if (!size)
  384. return 0;
  385. // Need to reassign the position due to internal buffering when transitioning from reading to writing
  386. if (writeSyncNeeded_)
  387. {
  388. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  389. writeSyncNeeded_ = false;
  390. }
  391. if (fwrite(data, size, 1, (FILE*)handle_) != 1)
  392. {
  393. // Return to the position where the write began
  394. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  395. LOGERROR("Error while writing to file " + GetName());
  396. return 0;
  397. }
  398. readSyncNeeded_ = true;
  399. position_ += size;
  400. if (position_ > size_)
  401. size_ = position_;
  402. return size;
  403. }
  404. unsigned File::GetChecksum()
  405. {
  406. if (offset_ || checksum_)
  407. return checksum_;
  408. #ifdef ANDROID
  409. if ((!handle_ && !assetHandle_) || mode_ == FILE_WRITE)
  410. #else
  411. if (!handle_ || mode_ == FILE_WRITE)
  412. #endif
  413. return 0;
  414. PROFILE(CalculateFileChecksum);
  415. unsigned oldPos = position_;
  416. checksum_ = 0;
  417. Seek(0);
  418. while (!IsEof())
  419. {
  420. unsigned char block[1024];
  421. unsigned readBytes = Read(block, 1024);
  422. for (unsigned i = 0; i < readBytes; ++i)
  423. checksum_ = SDBMHash(checksum_, block[i]);
  424. }
  425. Seek(oldPos);
  426. return checksum_;
  427. }
  428. void File::Close()
  429. {
  430. #ifdef ANDROID
  431. if (assetHandle_)
  432. {
  433. SDL_RWclose(assetHandle_);
  434. assetHandle_ = 0;
  435. }
  436. #endif
  437. readBuffer_.Reset();
  438. inputBuffer_.Reset();
  439. if (handle_)
  440. {
  441. fclose((FILE*)handle_);
  442. handle_ = 0;
  443. position_ = 0;
  444. size_ = 0;
  445. offset_ = 0;
  446. checksum_ = 0;
  447. }
  448. }
  449. void File::Flush()
  450. {
  451. if (handle_)
  452. fflush((FILE*)handle_);
  453. }
  454. void File::SetName(const String& name)
  455. {
  456. fileName_ = name;
  457. }
  458. bool File::IsOpen() const
  459. {
  460. #ifdef ANDROID
  461. return handle_ != 0 || assetHandle_ != 0;
  462. #else
  463. return handle_ != 0;
  464. #endif
  465. }
  466. void File::ReadText(String& text)
  467. {
  468. text.Clear();
  469. if (!size_)
  470. return;
  471. text.Resize(size_);
  472. Read((void*)text.CString(), size_);
  473. }
  474. // ATOMIC BEGIN
  475. bool File::Copy(File* srcFile)
  476. {
  477. if (!srcFile || !srcFile->IsOpen() || srcFile->GetMode() != FILE_READ)
  478. return false;
  479. if (!IsOpen() || GetMode() != FILE_WRITE)
  480. return false;
  481. unsigned fileSize = srcFile->GetSize();
  482. SharedArrayPtr<unsigned char> buffer(new unsigned char[fileSize]);
  483. unsigned bytesRead = srcFile->Read(buffer.Get(), fileSize);
  484. unsigned bytesWritten = Write(buffer.Get(), fileSize);
  485. return bytesRead == fileSize && bytesWritten == fileSize;
  486. }
  487. // ATOMIC END
  488. }