File.cpp 14 KB

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