File.cpp 14 KB

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