[FileSystem] Even safer filesystem interaction

This commit is contained in:
momo5502 2016-11-13 11:58:23 +01:00
parent 4b9d9e11a0
commit 091c604675
2 changed files with 24 additions and 6 deletions

View File

@ -2,6 +2,7 @@
namespace Components namespace Components
{ {
std::mutex FileSystem::Mutex;
Utils::Memory::Allocator FileSystem::MemAllocator; Utils::Memory::Allocator FileSystem::MemAllocator;
void FileSystem::File::Read() void FileSystem::File::Read()
@ -34,7 +35,7 @@ namespace Components
bool FileSystem::FileReader::Exists() bool FileSystem::FileReader::Exists()
{ {
return (this->Size >= 0); return (this->Size >= 0 && this->Handle);
} }
std::string FileSystem::FileReader::GetName() std::string FileSystem::FileReader::GetName()
@ -159,9 +160,26 @@ namespace Components
Game::FS_Remove(path); Game::FS_Remove(path);
} }
void* FileSystem::AllocateFile(int size) int FileSystem::ReadFile(const char* path, char** buffer)
{ {
return FileSystem::MemAllocator.Allocate(size); if (!buffer) return -1;
else *buffer = nullptr;
if (!path) return -1;
std::lock_guard<std::mutex> _(FileSystem::Mutex);
FileSystem::FileReader reader(path);
int size = reader.GetSize();
if (reader.Exists() && size >= 0)
{
*buffer = FileSystem::MemAllocator.AllocateArray<char>(size + 1);
if (reader.Read(*buffer, size)) return size;
FileSystem::FreeFile(*buffer);
*buffer = nullptr;
}
return -1;
} }
void FileSystem::FreeFile(void* buffer) void FileSystem::FreeFile(void* buffer)
@ -217,8 +235,7 @@ namespace Components
FileSystem::MemAllocator.Clear(); FileSystem::MemAllocator.Clear();
// Thread safe file system interaction // Thread safe file system interaction
Utils::Hook(0x4F4BFF, FileSystem::AllocateFile, HOOK_CALL).Install()->Quick(); Utils::Hook(Game::FS_ReadFile, FileSystem::ReadFile, HOOK_JUMP).Install()->Quick();
Utils::Hook(0x4F4BC0, Game::FS_FOpenFileReadCurrentThread, HOOK_CALL).Install()->Quick();
Utils::Hook(Game::FS_FreeFile, FileSystem::FreeFile, HOOK_JUMP).Install()->Quick(); Utils::Hook(Game::FS_FreeFile, FileSystem::FreeFile, HOOK_JUMP).Install()->Quick();
// Filesystem config checks // Filesystem config checks

View File

@ -69,9 +69,10 @@ namespace Components
static void DeleteFile(std::string folder, std::string file); static void DeleteFile(std::string folder, std::string file);
private: private:
static std::mutex Mutex;
static Utils::Memory::Allocator MemAllocator; static Utils::Memory::Allocator MemAllocator;
static void* AllocateFile(int size); static int ReadFile(const char* path, char** buffer);
static void FreeFile(void* buffer); static void FreeFile(void* buffer);
static void RegisterFolder(const char* folder); static void RegisterFolder(const char* folder);