Skip to content

Commit 0e4c1e7

Browse files
committed
feat(utils): load modules relative to executable, not cwd
1 parent c9e10a7 commit 0e4c1e7

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

include/loom/utils/load_modules.hpp

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,37 @@
22
#include "spdlog/spdlog.h"
33
#include <RLL/RLL.hpp>
44
#include <filesystem>
5-
#include <iostream>
5+
#include <string>
6+
7+
#if defined(_WIN32)
8+
#include <windows.h>
9+
#else
10+
#include <climits>
11+
#include <unistd.h>
12+
#endif
613

714
namespace loom::utils {
815

16+
inline auto get_executable_dir() -> std::filesystem::path {
17+
#if defined(_WIN32)
18+
std::array<wchar_t, MAX_PATH> buffer{};
19+
DWORD len = GetModuleFileNameW(NULL, buffer.data(),
20+
static_cast<DWORD>(buffer.size()));
21+
if (len == 0 || len == buffer.size()) {
22+
throw std::runtime_error("Failed to get executable path");
23+
}
24+
return std::filesystem::path(buffer.data()).parent_path();
25+
#else
26+
constexpr size_t bufferSize = PATH_MAX;
27+
std::array<char, bufferSize> buffer{};
28+
ssize_t len = readlink("/proc/self/exe", buffer.data(), buffer.size());
29+
if (len == -1) {
30+
throw std::runtime_error("Failed to get executable path");
31+
}
32+
return std::filesystem::path(std::string(buffer.data(), len)).parent_path();
33+
#endif
34+
}
35+
936
// Global module list, otherwise they get unloaded and no longer can be called
1037
// from lua
1138
static std::vector<std::unique_ptr<rll::shared_library>>
@@ -14,7 +41,7 @@ static std::vector<std::unique_ptr<rll::shared_library>>
1441
inline void load_and_run_register(sol::state &lua, sol::environment &sandbox) {
1542
namespace fs = std::filesystem;
1643

17-
for (const auto &entry : fs::directory_iterator(fs::current_path())) {
44+
for (const auto &entry : fs::directory_iterator(get_executable_dir())) {
1845
if (!entry.is_regular_file()) {
1946
continue;
2047
}

0 commit comments

Comments
 (0)