From 4d6e6cf75a23ae045e323e998aa39039890bf4a2 Mon Sep 17 00:00:00 2001 From: iTrooz Date: Sun, 30 Jul 2023 21:36:48 +0200 Subject: [PATCH] fix: Magic compile dumping files into cwd (#1212) This PR fix libmagic dumping files in the imhex cwd when compiling them This code was actually written by you (notice the source branch), this PR is just a reminder that the fix works and you can merge it ^^ --------- Co-authored-by: WerWolv --- lib/libimhex/source/helpers/magic.cpp | 29 ++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/libimhex/source/helpers/magic.cpp b/lib/libimhex/source/helpers/magic.cpp index a7b38c6a6..26c0396a6 100644 --- a/lib/libimhex/source/helpers/magic.cpp +++ b/lib/libimhex/source/helpers/magic.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -13,6 +14,7 @@ #include #include +#include #if defined(OS_WINDOWS) #define MAGIC_PATH_SEPARATOR ";" @@ -52,7 +54,32 @@ namespace hex::magic { if (!magicFiles.has_value()) return false; - return magic_compile(ctx, magicFiles->c_str()) == 0; + std::array cwd = { 0x00 }; + if (getcwd(cwd.data(), cwd.size()) == nullptr) + return false; + + std::optional magicFolder; + for (const auto &dir : fs::getDefaultPaths(fs::ImHexPath::Magic)) { + if (std::fs::exists(dir) && fs::isPathWritable(dir)) { + magicFolder = dir; + break; + } + } + + if (!magicFolder.has_value()) { + log::error("Could not find a writable magic folder"); + return false; + } + + if (chdir(wolv::util::toUTF8String(*magicFolder).c_str()) != 0) + return false; + + auto result = magic_compile(ctx, magicFiles->c_str()) == 0; + + if (chdir(cwd.data()) != 0) + return false; + + return result; } std::string getDescription(const std::vector &data) {