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) {