File.cpp 15 KB

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