From 091c604675c07497cfa87fd21cfa9eeb848bdb5a Mon Sep 17 00:00:00 2001 From: momo5502 Date: Sun, 13 Nov 2016 11:58:23 +0100 Subject: [PATCH] [FileSystem] Even safer filesystem interaction --- src/Components/Modules/FileSystem.cpp | 27 ++++++++++++++++++++++----- src/Components/Modules/FileSystem.hpp | 3 ++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/Components/Modules/FileSystem.cpp b/src/Components/Modules/FileSystem.cpp index d6a813e7..7657a771 100644 --- a/src/Components/Modules/FileSystem.cpp +++ b/src/Components/Modules/FileSystem.cpp @@ -2,6 +2,7 @@ namespace Components { + std::mutex FileSystem::Mutex; Utils::Memory::Allocator FileSystem::MemAllocator; void FileSystem::File::Read() @@ -34,7 +35,7 @@ namespace Components bool FileSystem::FileReader::Exists() { - return (this->Size >= 0); + return (this->Size >= 0 && this->Handle); } std::string FileSystem::FileReader::GetName() @@ -159,9 +160,26 @@ namespace Components 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 _(FileSystem::Mutex); + FileSystem::FileReader reader(path); + + int size = reader.GetSize(); + if (reader.Exists() && size >= 0) + { + *buffer = FileSystem::MemAllocator.AllocateArray(size + 1); + if (reader.Read(*buffer, size)) return size; + + FileSystem::FreeFile(*buffer); + *buffer = nullptr; + } + + return -1; } void FileSystem::FreeFile(void* buffer) @@ -217,8 +235,7 @@ namespace Components FileSystem::MemAllocator.Clear(); // Thread safe file system interaction - Utils::Hook(0x4F4BFF, FileSystem::AllocateFile, HOOK_CALL).Install()->Quick(); - Utils::Hook(0x4F4BC0, Game::FS_FOpenFileReadCurrentThread, HOOK_CALL).Install()->Quick(); + Utils::Hook(Game::FS_ReadFile, FileSystem::ReadFile, HOOK_JUMP).Install()->Quick(); Utils::Hook(Game::FS_FreeFile, FileSystem::FreeFile, HOOK_JUMP).Install()->Quick(); // Filesystem config checks diff --git a/src/Components/Modules/FileSystem.hpp b/src/Components/Modules/FileSystem.hpp index 6120869a..8999b5b5 100644 --- a/src/Components/Modules/FileSystem.hpp +++ b/src/Components/Modules/FileSystem.hpp @@ -69,9 +69,10 @@ namespace Components static void DeleteFile(std::string folder, std::string file); private: + static std::mutex Mutex; 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 RegisterFolder(const char* folder);