File.cpp 13 KB

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