File.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Profiler.h"
  5. #include "../IO/File.h"
  6. #include "../IO/FileSystem.h"
  7. #include "../IO/Log.h"
  8. #include "../IO/MemoryBuffer.h"
  9. #include "../IO/PackageFile.h"
  10. #ifdef __ANDROID__
  11. #include <SDL/SDL_rwops.h>
  12. #endif
  13. #include <cstdio>
  14. #include <LZ4/lz4.h>
  15. #include "../DebugNew.h"
  16. namespace Urho3D
  17. {
  18. #ifdef _WIN32
  19. static const wchar_t* openMode[] =
  20. {
  21. L"rb",
  22. L"wb",
  23. L"r+b",
  24. L"w+b"
  25. };
  26. #else
  27. static const char* openMode[] =
  28. {
  29. "rb",
  30. "wb",
  31. "r+b",
  32. "w+b"
  33. };
  34. #endif
  35. #ifdef __ANDROID__
  36. const char* APK = "/apk/";
  37. static constexpr i32 READ_BUFFER_SIZE = 32768;
  38. #endif
  39. static constexpr i32 SKIP_BUFFER_SIZE = 1024;
  40. static i32 FSeek64(FILE* stream, i64 offset, i32 origin)
  41. {
  42. #ifdef _MSC_VER
  43. return _fseeki64(stream, offset, origin);
  44. #else
  45. return fseeko64(stream, offset, origin);
  46. #endif
  47. }
  48. static i64 FTell64(FILE* stream)
  49. {
  50. #ifdef _MSC_VER
  51. return _ftelli64(stream);
  52. #else
  53. return ftello64(stream);
  54. #endif
  55. }
  56. File::File(Context* context) :
  57. Object(context),
  58. mode_(FILE_READ),
  59. handle_(nullptr),
  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_(nullptr),
  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_(nullptr),
  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. return OpenInternal(fileName, mode);
  113. }
  114. bool File::Open(PackageFile* package, const String& fileName)
  115. {
  116. if (!package)
  117. return false;
  118. const PackageEntry* entry = package->GetEntry(fileName);
  119. if (!entry)
  120. return false;
  121. bool success = OpenInternal(package->GetName(), FILE_READ, true);
  122. if (!success)
  123. {
  124. URHO3D_LOGERROR("Could not open package file " + fileName);
  125. return false;
  126. }
  127. name_ = fileName;
  128. offset_ = entry->offset_;
  129. checksum_ = entry->checksum_;
  130. size_ = entry->size_;
  131. compressed_ = package->IsCompressed();
  132. // Seek to beginning of package entry's file data
  133. SeekInternal(offset_);
  134. return true;
  135. }
  136. i32 File::Read(void* dest, i32 size)
  137. {
  138. assert(size >= 0);
  139. if (!IsOpen())
  140. {
  141. // If file not open, do not log the error further here to prevent spamming the stderr stream
  142. return 0;
  143. }
  144. if (mode_ == FILE_WRITE)
  145. {
  146. URHO3D_LOGERROR("File not opened for reading");
  147. return 0;
  148. }
  149. if (size + position_ > size_)
  150. size = size_ - position_;
  151. if (!size)
  152. return 0;
  153. #ifdef __ANDROID__
  154. if (assetHandle_ && !compressed_)
  155. {
  156. // If not using a compressed package file, buffer file reads on Android for better performance
  157. if (!readBuffer_)
  158. {
  159. readBuffer_ = new u8[READ_BUFFER_SIZE];
  160. readBufferOffset_ = 0;
  161. readBufferSize_ = 0;
  162. }
  163. i32 sizeLeft = size;
  164. u8* destPtr = (u8*)dest;
  165. while (sizeLeft)
  166. {
  167. if (readBufferOffset_ >= readBufferSize_)
  168. {
  169. readBufferSize_ = Min(size_ - position_, READ_BUFFER_SIZE);
  170. readBufferOffset_ = 0;
  171. ReadInternal(readBuffer_.Get(), readBufferSize_);
  172. }
  173. i32 copySize = Min((readBufferSize_ - readBufferOffset_), sizeLeft);
  174. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  175. destPtr += copySize;
  176. sizeLeft -= copySize;
  177. readBufferOffset_ += copySize;
  178. position_ += copySize;
  179. }
  180. return size;
  181. }
  182. #endif
  183. if (compressed_)
  184. {
  185. i32 sizeLeft = size;
  186. u8* destPtr = (u8*)dest;
  187. while (sizeLeft)
  188. {
  189. if (!readBuffer_ || readBufferOffset_ >= readBufferSize_)
  190. {
  191. u8 blockHeaderBytes[4];
  192. ReadInternal(blockHeaderBytes, sizeof blockHeaderBytes);
  193. MemoryBuffer blockHeader(&blockHeaderBytes[0], sizeof blockHeaderBytes);
  194. i32 unpackedSize = blockHeader.ReadUShort();
  195. i32 packedSize = blockHeader.ReadUShort();
  196. if (!readBuffer_)
  197. {
  198. readBuffer_ = new u8[unpackedSize];
  199. inputBuffer_ = new u8[LZ4_compressBound(unpackedSize)];
  200. }
  201. /// \todo Handle errors
  202. ReadInternal(inputBuffer_.Get(), packedSize);
  203. LZ4_decompress_fast((const char*)inputBuffer_.Get(), (char*)readBuffer_.Get(), unpackedSize);
  204. readBufferSize_ = unpackedSize;
  205. readBufferOffset_ = 0;
  206. }
  207. i32 copySize = Min((readBufferSize_ - readBufferOffset_), sizeLeft);
  208. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  209. destPtr += copySize;
  210. sizeLeft -= copySize;
  211. readBufferOffset_ += copySize;
  212. position_ += copySize;
  213. }
  214. return size;
  215. }
  216. // Need to reassign the position due to internal buffering when transitioning from writing to reading
  217. if (readSyncNeeded_)
  218. {
  219. SeekInternal(position_ + offset_);
  220. readSyncNeeded_ = false;
  221. }
  222. if (!ReadInternal(dest, size))
  223. {
  224. // Return to the position where the read began
  225. SeekInternal(position_ + offset_);
  226. URHO3D_LOGERROR("Error while reading from file " + GetName());
  227. return 0;
  228. }
  229. writeSyncNeeded_ = true;
  230. position_ += size;
  231. return size;
  232. }
  233. i64 File::Seek(i64 position)
  234. {
  235. assert(position >= 0);
  236. if (!IsOpen())
  237. {
  238. // If file not open, do not log the error further here to prevent spamming the stderr stream
  239. return 0;
  240. }
  241. // Allow sparse seeks if writing
  242. if (mode_ == FILE_READ && position > size_)
  243. position = size_;
  244. if (compressed_)
  245. {
  246. // Start over from the beginning
  247. if (position == 0)
  248. {
  249. position_ = 0;
  250. readBufferOffset_ = 0;
  251. readBufferSize_ = 0;
  252. SeekInternal(offset_);
  253. }
  254. // Skip bytes
  255. else if (position >= position_)
  256. {
  257. u8 skipBuffer[SKIP_BUFFER_SIZE];
  258. while (position > position_)
  259. Read(skipBuffer, Min(position - position_, SKIP_BUFFER_SIZE));
  260. }
  261. else
  262. URHO3D_LOGERROR("Seeking backward in a compressed file is not supported");
  263. return position_;
  264. }
  265. SeekInternal(position + offset_);
  266. position_ = position;
  267. readSyncNeeded_ = false;
  268. writeSyncNeeded_ = false;
  269. return position_;
  270. }
  271. i32 File::Write(const void* data, i32 size)
  272. {
  273. assert(size >= 0);
  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. FSeek64((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. FSeek64((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. hash32 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. i64 oldPos = position_;
  317. checksum_ = 0;
  318. Seek(0);
  319. while (!IsEof())
  320. {
  321. u8 block[1024];
  322. i32 readBytes = Read(block, 1024);
  323. for (i32 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. bool File::IsOpen() const
  356. {
  357. #ifdef __ANDROID__
  358. return handle_ != 0 || assetHandle_ != 0;
  359. #else
  360. return handle_ != nullptr;
  361. #endif
  362. }
  363. bool File::OpenInternal(const String& fileName, FileMode mode, bool fromPackage)
  364. {
  365. Close();
  366. compressed_ = false;
  367. readSyncNeeded_ = false;
  368. writeSyncNeeded_ = false;
  369. auto* fileSystem = GetSubsystem<FileSystem>();
  370. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  371. {
  372. URHO3D_LOGERRORF("Access denied to %s", fileName.CString());
  373. return false;
  374. }
  375. if (fileName.Empty())
  376. {
  377. URHO3D_LOGERROR("Could not open file with empty name");
  378. return false;
  379. }
  380. #ifdef __ANDROID__
  381. if (URHO3D_IS_ASSET(fileName))
  382. {
  383. if (mode != FILE_READ)
  384. {
  385. URHO3D_LOGERROR("Only read mode is supported for Android asset files");
  386. return false;
  387. }
  388. assetHandle_ = SDL_RWFromFile(URHO3D_ASSET(fileName), "rb");
  389. if (!assetHandle_)
  390. {
  391. URHO3D_LOGERRORF("Could not open Android asset file %s", fileName.CString());
  392. return false;
  393. }
  394. else
  395. {
  396. name_ = fileName;
  397. mode_ = mode;
  398. position_ = 0;
  399. if (!fromPackage)
  400. {
  401. size_ = SDL_RWsize(assetHandle_);
  402. offset_ = 0;
  403. }
  404. checksum_ = 0;
  405. return true;
  406. }
  407. }
  408. #endif
  409. #ifdef _WIN32
  410. handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode]);
  411. #else
  412. handle_ = fopen64(GetNativePath(fileName).CString(), openMode[mode]);
  413. #endif
  414. // If file did not exist in readwrite mode, retry with write-update mode
  415. if (mode == FILE_READWRITE && !handle_)
  416. {
  417. #ifdef _WIN32
  418. handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode + 1]);
  419. #else
  420. handle_ = fopen64(GetNativePath(fileName).CString(), openMode[mode + 1]);
  421. #endif
  422. }
  423. if (!handle_)
  424. {
  425. URHO3D_LOGERRORF("Could not open file %s", fileName.CString());
  426. return false;
  427. }
  428. if (!fromPackage)
  429. {
  430. FSeek64((FILE*)handle_, 0, SEEK_END);
  431. i64 size = FTell64((FILE*)handle_);
  432. FSeek64((FILE*)handle_, 0, SEEK_SET);
  433. if (size > M_MAX_UNSIGNED)
  434. {
  435. URHO3D_LOGERRORF("Could not open file %s which is larger than 4GB", fileName.CString());
  436. Close();
  437. size_ = 0;
  438. return false;
  439. }
  440. size_ = (unsigned)size;
  441. offset_ = 0;
  442. }
  443. name_ = fileName;
  444. mode_ = mode;
  445. position_ = 0;
  446. checksum_ = 0;
  447. return true;
  448. }
  449. bool File::ReadInternal(void* dest, i32 size)
  450. {
  451. assert(size >= 0);
  452. #ifdef __ANDROID__
  453. if (assetHandle_)
  454. {
  455. return SDL_RWread(assetHandle_, dest, size, 1) == 1;
  456. }
  457. else
  458. #endif
  459. return fread(dest, size, 1, (FILE*)handle_) == 1;
  460. }
  461. void File::SeekInternal(i64 newPosition)
  462. {
  463. assert(newPosition >= 0);
  464. #ifdef __ANDROID__
  465. if (assetHandle_)
  466. {
  467. SDL_RWseek(assetHandle_, newPosition, SEEK_SET);
  468. // Reset buffering after seek
  469. readBufferOffset_ = 0;
  470. readBufferSize_ = 0;
  471. }
  472. else
  473. #endif
  474. {
  475. FSeek64((FILE*)handle_, newPosition, SEEK_SET);
  476. }
  477. }
  478. }