File.cpp 15 KB

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