Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ add_library(mrtrix-common INTERFACE)
add_library(mrtrix::common ALIAS mrtrix-common)
target_compile_definitions(mrtrix-common INTERFACE
MRTRIX_BUILD_TYPE="${CMAKE_BUILD_TYPE}"
$<$<PLATFORM_ID:Linux>:MRTRIX_LINUX>
$<$<PLATFORM_ID:Windows>:MRTRIX_WINDOWS>
$<$<PLATFORM_ID:Darwin>:MRTRIX_MACOSX>
$<$<PLATFORM_ID:FreeBSD>:MRTRIX_FREEBSD>
Expand Down
103 changes: 103 additions & 0 deletions cpp/core/platform.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/* Copyright (c) 2008-2025 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/

#include "platform.h"

#ifdef MRTRIX_WINDOWS
#include <windows.h>
#elif defined(MRTRIX_MACOSX)
#include <mach-o/dyld.h>
#elif defined(MRTRIX_FREEBSD)
#include <sys/sysctl.h>
#include <sys/types.h>
#else
#include <unistd.h>
#endif

#include <cstdint>
#include <filesystem>
#include <stdexcept>
#include <string>

namespace MR::Platform {
std::filesystem::path get_executable_path() {
#ifdef MRTRIX_WINDOWS
std::vector<wchar_t> buffer;
buffer.resize(MAX_PATH);
for (;;) {
DWORD len = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
if (len == 0) {
throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()),
"GetModuleFileNameW failed");
}
if (static_cast<size_t>(len) < buffer.size()) {
return std::filesystem::path(std::wstring(buffer.data(), len));
}
size_t new_size = buffer.size() * 2;
if (new_size <= buffer.size())
throw std::runtime_error("Executable path too long");
buffer.resize(new_size);
}
#elif defined(MRTRIX_MACOSX)
uint32_t size = 0;
if (_NSGetExecutablePath(nullptr, &size) != -1)
throw std::runtime_error("Unexpected success getting buffer size");
std::string buffer;
buffer.resize(size);
if (_NSGetExecutablePath(buffer.data(), &size) != 0)
throw std::runtime_error("_NSGetExecutablePath failed to fill buffer");
try {
return std::filesystem::canonical(std::filesystem::path(buffer));
} catch (const std::filesystem::filesystem_error &) {
return std::filesystem::weakly_canonical(std::filesystem::path(buffer));
}
return std::filesystem::canonical(std::filesystem::path(buffer));
#elif defined(MRTRIX_LINUX)
const std::filesystem::path link("/proc/self/exe");
try {
const auto p = std::filesystem::read_symlink(link);
try {
return std::filesystem::canonical(p);
} catch (const std::filesystem::filesystem_error &) {
return std::filesystem::weakly_canonical(p);
}
} catch (const std::filesystem::filesystem_error &e) {
throw std::system_error(std::error_code(errno, std::system_category()),
std::string("read_symlink(\"/proc/self/exe\") failed: ") + e.what());
}
#elif defined(MRTRIX_FREEBSD)
// See https://github.com/chromium/chromium/blob/db87c489ae756af10467897d653518f321db2f4d/base/base_paths_posix.cc
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
size_t size = 0;
if (sysctl(mib, 4, nullptr, &size, nullptr, 0) == -1)
throw std::system_error(std::error_code(errno, std::system_category()),
"sysctl(KERN_PROC_PATHNAME) failed to get size");
std::string buffer;
buffer.resize(size);
if (sysctl(mib, 4, buffer.data(), &size, nullptr, 0) == -1)
throw std::system_error(std::error_code(errno, std::system_category()),
"sysctl(KERN_PROC_PATHNAME) failed to get path");
// Ensure we use the null-terminated string
try {
return std::filesystem::canonical(std::filesystem::path(buffer.c_str()));
} catch (const std::filesystem::filesystem_error &) {
return std::filesystem::weakly_canonical(std::filesystem::path(buffer.c_str()));
}
#else
static_assert(false, "Unsupported platform");
#endif
}
} // namespace MR::Platform
23 changes: 23 additions & 0 deletions cpp/core/platform.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* Copyright (c) 2008-2025 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/

#include <filesystem>

namespace MR::Platform {
// A cross-platform function to get the (absolute) path of the current executable.
// Throws an exception on failure.
std::filesystem::path get_executable_path();
} // namespace MR::Platform
1 change: 1 addition & 0 deletions testing/unit_tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ set(UNIT_TESTS_CPP_SRCS
icls_tests.cpp
ordered_queue_tests.cpp
parse_ints_tests.cpp
platform_tests.cpp
roi_tests.cpp
sh_precomputer_tests.cpp
shuffle_tests.cpp
Expand Down
65 changes: 65 additions & 0 deletions testing/unit_tests/platform_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/* Copyright (c) 2008-2025 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/

#include "platform.h"
#include <gtest/gtest.h>

#if defined(MRTRIX_LINUX) || defined(MRTRIX_MACOSX) || defined(MRTRIX_FREEBSD)
#include <sys/unistd.h>
#include <unistd.h>
#endif

#if defined(MRTRIX_WINDOWS)
#include <algorithm>
#endif

#include <filesystem>

using namespace MR::Platform;

TEST(ExecutablePathTest, ReturnsExistingAbsolutePath) {
std::filesystem::path p;
EXPECT_NO_THROW(p = get_executable_path());
EXPECT_FALSE(p.empty()) << "Returned path should not be empty";
EXPECT_TRUE(p.is_absolute()) << "Returned path should be absolute: " << p;
EXPECT_TRUE(std::filesystem::exists(p)) << "Path must exist: " << p;
EXPECT_TRUE(std::filesystem::is_regular_file(p)) << "Path should be a regular file: " << p;

// canonicalize should succeed for a valid on-disk executable.
EXPECT_NO_THROW({
auto c = std::filesystem::canonical(p);
(void)c;
});
}

TEST(ExecutablePathTest, PlatformExecutableCheck) {
const auto p = get_executable_path();

#if defined(MRTRIX_WINDOWS)
ASSERT_TRUE(p.has_extension()) << "Executable should have an extension on Windows: " << p;
std::string ext = p.extension().string();
std::transform(
ext.begin(), ext.end(), ext.begin(), [](auto ch) -> char { return static_cast<char>(std::tolower(ch)); });
EXPECT_EQ(ext, ".exe") << "Expected .exe extension for test binary on Windows: " << p;
#elif defined(MRTRIX_LINUX) || defined(MRTRIX_MACOSX) || defined(MRTRIX_FREEBSD)
// On POSIX, check that the file is marked executable for current user.
const char *cpath = p.c_str();
const int ok = access(cpath, X_OK);
EXPECT_EQ(ok, 0) << "Executable should be executable for current user: " << p;
#else
static_assert(false, "Unsupported platform");
#endif
}
Loading