File.cpp 15 KB

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