diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 28a90d2..13e1c12 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -22,12 +22,14 @@ jobs: NAME: Thread Sanitizer - TARGET_CMAKE_ARGS: -DENABLE_SANITIZER_UNDEFINED_BEHAVIOR=ON -DCMAKE_BUILD_TYPE=Debug NAME: Undefined Behavior Sanitizer + - TARGET_CMAKE_ARGS: -DCLASS_LOADER_USE_RCPPUTILS=OFF + NAME: Without rcpputils env: ROS_DISTRO: rolling runs-on: ubuntu-latest name: ${{ matrix.env.NAME }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v7 # ThreadSanitizer fails with "incompatible memory layout" under the # runner kernel's default ASLR entropy (vm.mmap_rnd_bits=32). The # industrial_ci container shares the host kernel, so lower it here. @@ -35,3 +37,54 @@ jobs: run: sudo sysctl vm.mmap_rnd_bits=28 - uses: 'ros-industrial/industrial_ci@master' env: ${{matrix.env}} + + # Build and test without ament and ROS (CLASS_LOADER_IGNORE_AMENT=ON, dependencies from the + # system's package manager), install, and check the installed library via CMake and + # pkg-config (not on Windows). + standalone: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + name: Standalone (without ROS, ${{ matrix.os }}) + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v7 + - name: Install dependencies (Linux) + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y libconsole-bridge-dev libgtest-dev pkg-config + echo "INSTALL_PREFIX=$GITHUB_WORKSPACE/install" >> "$GITHUB_ENV" + - name: Install dependencies (macOS) + if: runner.os == 'macOS' + run: | + brew install console_bridge googletest pkgconf + echo "INSTALL_PREFIX=$GITHUB_WORKSPACE/install" >> "$GITHUB_ENV" + - name: Install dependencies (Windows) + if: runner.os == 'Windows' + run: | + vcpkg install console-bridge gtest --triplet x64-windows + vcpkg_root=$(cygpath -m "$VCPKG_INSTALLATION_ROOT") + echo "CMAKE_TOOLCHAIN_FILE=$vcpkg_root/scripts/buildsystems/vcpkg.cmake" >> "$GITHUB_ENV" + cygpath -w "$vcpkg_root/installed/x64-windows/bin" >> "$GITHUB_PATH" + echo "INSTALL_PREFIX=$(cygpath -m "$GITHUB_WORKSPACE/install")" >> "$GITHUB_ENV" + - name: Build + run: | + cmake -S . -B build -DCLASS_LOADER_IGNORE_AMENT=ON -DBUILD_TESTING=ON \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$INSTALL_PREFIX" + cmake --build build --parallel --config Release + - name: Test + run: ctest --test-dir build --output-on-failure --build-config Release + - name: Install + run: cmake --install build --config Release + - name: Test installed library + run: | + export PKG_CONFIG_PATH="$INSTALL_PREFIX/lib/pkgconfig" + cmake -S test/standalone -B build_test -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_PREFIX_PATH="$INSTALL_PREFIX" + cmake --build build_test --parallel --config Release + ctest --test-dir build_test --output-on-failure --build-config Release diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 7ae6501..e36ce6c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -2,6 +2,12 @@ Changelog for package class_loader ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Forthcoming +----------- +* Make rcpputils optional (new CMake option ``CLASS_LOADER_USE_RCPPUTILS``), so class_loader can be built without any ROS packages (`#251 `_) +* Builds without ament (``CLASS_LOADER_IGNORE_AMENT``): don't require console_bridge_vendor, fix the pkg-config file, install a CMake package configuration, and allow running the tests (`#251 `_) +* Contributors: Christoph Hertzberg + 3.0.3 (2026-10-22) ------------------ * Include missing dependency in package.xml (`#235 `_) diff --git a/CMakeLists.txt b/CMakeLists.txt index 78ae257..8ef015a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,14 +23,30 @@ else() set(explicit_library_type "SHARED") endif() -find_package(console_bridge_vendor REQUIRED) # Provides console_bridge 0.4.0 on platforms without it. +if(CLASS_LOADER_IGNORE_AMENT) + set(_use_rcpputils_default OFF) +else() + set(_use_rcpputils_default ON) +endif() +option(CLASS_LOADER_USE_RCPPUTILS + "Load libraries with rcpputils (otherwise with a minimal built-in replacement)" + ${_use_rcpputils_default}) + +if(NOT CLASS_LOADER_IGNORE_AMENT) + # Provides console_bridge 0.4.0 on platforms without it. + find_package(console_bridge_vendor REQUIRED) +endif() find_package(console_bridge REQUIRED) -find_package(rcpputils REQUIRED) +if(CLASS_LOADER_USE_RCPPUTILS) + find_package(rcpputils REQUIRED) +endif() -if(ament_cmake_FOUND) +if(NOT CLASS_LOADER_IGNORE_AMENT) ament_export_dependencies(console_bridge) - ament_export_dependencies(rcpputils) + if(CLASS_LOADER_USE_RCPPUTILS) + ament_export_dependencies(rcpputils) + endif() endif() add_library(${PROJECT_NAME} ${explicit_library_type} @@ -42,11 +58,22 @@ add_library(${PROJECT_NAME} ${explicit_library_type} target_include_directories(${PROJECT_NAME} PUBLIC "$" "$") +# The public headers use C++20 (e.g. concepts), so users need it as well. +# (Previously, this was only propagated through rcpputils.) +target_compile_features(${PROJECT_NAME} INTERFACE cxx_std_20) +# dlopen() is used directly (and by the built-in shared library wrapper). +target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_DL_LIBS}) +if(CLASS_LOADER_USE_RCPPUTILS) + target_link_libraries(${PROJECT_NAME} PUBLIC rcpputils::rcpputils) +else() + target_sources(${PROJECT_NAME} PRIVATE src/shared_library.cpp) + # Also needed by users, as the public headers select the shared library wrapper with it. + target_compile_definitions(${PROJECT_NAME} PUBLIC CLASS_LOADER_NO_RCPPUTILS) +endif() -if(ament_cmake_FOUND) +if(NOT CLASS_LOADER_IGNORE_AMENT) target_link_libraries(${PROJECT_NAME} PUBLIC - console_bridge::console_bridge - rcpputils::rcpputils) + console_bridge::console_bridge) # ament_ros_defaults is an INTERFACE target providing cxx_std_20 / c_std_17. # Linked PRIVATE so the standard applies to our own sources without leaking # into the exported interface (a SHARED library does not propagate PRIVATE @@ -54,9 +81,14 @@ if(ament_cmake_FOUND) target_link_libraries(${PROJECT_NAME} PRIVATE ament_cmake_ros_core::ament_ros_defaults) ament_export_targets(${PROJECT_NAME}) else() - target_include_directories(${PROJECT_NAME} - PUBLIC ${console_bridge_INCLUDE_DIRS}) - target_link_libraries(${PROJECT_NAME} ${console_bridge_LIBRARIES}) + if(TARGET console_bridge::console_bridge) + target_link_libraries(${PROJECT_NAME} PUBLIC console_bridge::console_bridge) + else() + # Older console_bridge versions do not provide an imported target. + target_include_directories(${PROJECT_NAME} + PUBLIC ${console_bridge_INCLUDE_DIRS}) + target_link_libraries(${PROJECT_NAME} PUBLIC ${console_bridge_LIBRARIES}) + endif() # Standalone (non-ament) build: request C++20 for our own translation units. target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20) endif() @@ -67,7 +99,11 @@ if(WIN32) endif() if(BUILD_TESTING) - find_package(ament_lint_auto QUIET) + if(CLASS_LOADER_IGNORE_AMENT) + enable_testing() + else() + find_package(ament_lint_auto QUIET) + endif() if(ament_lint_auto_FOUND) # TODO(mikaelarguedas) add copyright test once the linter accepts /** block comments list(APPEND AMENT_LINT_AUTO_EXCLUDE @@ -85,15 +121,27 @@ if(BUILD_TESTING) add_subdirectory(test) endif() -if(ament_cmake_FOUND) +if(NOT CLASS_LOADER_IGNORE_AMENT) ament_package( CONFIG_EXTRAS "class_loader-extras.cmake" ) else() set(TARGET_NAME ${PROJECT_NAME}) - set(PKGCONFIG_LIBS - ${console_bridge_LIBRARIES} - ) + file(READ "${CMAKE_CURRENT_SOURCE_DIR}/package.xml" _package_xml) + string(REGEX MATCH "]*>([^<]*)" _ "${_package_xml}") + set(PROJECT_VERSION "${CMAKE_MATCH_1}") + if(NOT PROJECT_VERSION) + message(FATAL_ERROR "Could not read the version from package.xml") + endif() + set(PROJECT_DESCRIPTION "Library for loading plugins at runtime") + set(PKGCONFIG_REQUIRES console_bridge) + if(CLASS_LOADER_USE_RCPPUTILS) + message(WARNING "The pkg-config file of class_loader does not provide the flags for " + "rcpputils (which does not provide a pkg-config file). Use the CMake package " + "configuration instead, or build with CLASS_LOADER_USE_RCPPUTILS=OFF.") + else() + set(PKGCONFIG_CFLAGS "-DCLASS_LOADER_NO_RCPPUTILS") + endif() # Prepare and install necessary files to support finding of the library # using pkg-config @@ -102,7 +150,27 @@ else() "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc" @ONLY) - install(FILES "${CMAKE_BINARY_DIR}/${PROJECT_NAME}.pc" DESTINATION lib/pkgconfig) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc" DESTINATION lib/pkgconfig) + + # Prepare and install a CMake package configuration, providing the target + # class_loader::class_loader as in ament builds + install(EXPORT ${PROJECT_NAME} + NAMESPACE ${PROJECT_NAME}:: + FILE ${PROJECT_NAME}Targets.cmake + DESTINATION share/${PROJECT_NAME}/cmake) + include(CMakePackageConfigHelpers) + configure_package_config_file( + "${CMAKE_CURRENT_SOURCE_DIR}/src/${PROJECT_NAME}Config.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + INSTALL_DESTINATION share/${PROJECT_NAME}/cmake) + write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" + VERSION ${PROJECT_VERSION} + COMPATIBILITY AnyNewerVersion) # as in ament builds + install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" + DESTINATION share/${PROJECT_NAME}/cmake) endif() install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} diff --git a/README.md b/README.md index 20094cb..fc629aa 100644 --- a/README.md +++ b/README.md @@ -51,3 +51,21 @@ int main() ``` Visit the [class_loader](https://docs.ros.org/en/rolling/p/class_loader/) API documentation for a complete list of its main components. + +# Building without ROS + +class_loader can also be built and used without ament and other ROS packages; only [console_bridge](https://github.com/ros/console_bridge) is required (and GoogleTest for the tests). For example, with plain CMake: +``` +cmake -S . -B build -DCLASS_LOADER_IGNORE_AMENT=ON +cmake --build build +cmake --install build +``` + +The following CMake options control this: + + - `CLASS_LOADER_IGNORE_AMENT` (default: `OFF`): Build without ament. Instead of the ament package, a CMake package configuration (`find_package(class_loader)`, providing the target `class_loader::class_loader`) and a pkg-config file (`class_loader.pc`) are installed. With `BUILD_TESTING=ON`, the tests use GoogleTest from the system. + - `CLASS_LOADER_USE_RCPPUTILS` (default: `ON`, or `OFF` if `CLASS_LOADER_IGNORE_AMENT` is `ON`): Load libraries with `rcpputils::SharedLibrary`. If `OFF`, a minimal built-in replacement is used, and rcpputils (and rcutils) are not required. + +With `CLASS_LOADER_USE_RCPPUTILS=OFF`, the preprocessor symbol `CLASS_LOADER_NO_RCPPUTILS` is defined publicly, i.e., for class_loader and for all its users (via the CMake target and the pkg-config file), because it changes types used in the public headers. All code using class_loader must be compiled with the same setting as class_loader itself; anything else violates the one definition rule (ODR). + +The public headers require C++20. The CMake target provides this requirement, users of the pkg-config file need to enable C++20 themselves. The pkg-config file does not provide the flags for rcpputils, so with `CLASS_LOADER_USE_RCPPUTILS=ON` (and without ament), use the CMake package configuration. diff --git a/include/class_loader/class_loader_core.hpp b/include/class_loader/class_loader_core.hpp index 7605d00..a304ebf 100644 --- a/include/class_loader/class_loader_core.hpp +++ b/include/class_loader/class_loader_core.hpp @@ -58,10 +58,9 @@ #include "class_loader/exceptions.hpp" #include "class_loader/interface_traits.hpp" #include "class_loader/meta_object.hpp" +#include "class_loader/shared_library.hpp" #include "class_loader/visibility_control.hpp" -#include "rcpputils/shared_library.hpp" - /** * @note This header file is the internal implementation of the plugin system which is exposed * via the ClassLoader class @@ -81,7 +80,7 @@ using ClassName = std::string; using BaseClassName = std::string; using FactoryMap = std::map; using BaseToFactoryMapMap = std::map; -using LibraryPair = std::pair>; +using LibraryPair = std::pair>; using LibraryVector = std::vector; using MetaObjectVector = std::vector; class MetaObjectGraveyardVector : public MetaObjectVector diff --git a/include/class_loader/shared_library.hpp b/include/class_loader/shared_library.hpp new file mode 100644 index 0000000..c482eae --- /dev/null +++ b/include/class_loader/shared_library.hpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2026, DFKI GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef CLASS_LOADER__SHARED_LIBRARY_HPP_ +#define CLASS_LOADER__SHARED_LIBRARY_HPP_ + +/** + * @note This header is part of the internal implementation. It selects the shared library + * wrapper used by class_loader: rcpputils::SharedLibrary by default, or a minimal built-in + * replacement if class_loader was built without rcpputils (CMake option + * CLASS_LOADER_USE_RCPPUTILS=OFF), in which case CLASS_LOADER_NO_RCPPUTILS is defined for the + * library and all its users. + */ + +#include + +#ifdef CLASS_LOADER_NO_RCPPUTILS + +#include "class_loader/visibility_control.hpp" + +namespace class_loader +{ +namespace impl +{ + +/// Minimal replacement for the subset of rcpputils::SharedLibrary used by class_loader. +class CLASS_LOADER_PUBLIC SharedLibrary +{ +public: + /// Loads the library at the given path (or found by the system's library search). + /** + * \throws std::runtime_error if the library cannot be loaded + */ + explicit SharedLibrary(const std::string & library_path); + + /// Unloads the library, if it has not been unloaded with unload_library() before. + ~SharedLibrary(); + + SharedLibrary(const SharedLibrary &) = delete; + SharedLibrary & operator=(const SharedLibrary &) = delete; + + /// Unloads the library. + /** + * \throws std::runtime_error if the library is not loaded or cannot be unloaded + */ + void unload_library(); + + /// Returns the path of the loaded library (resolved by the system loader where supported). + /** + * \throws std::runtime_error if the library is not loaded + */ + std::string get_library_path() const; + +private: + void * handle_ = nullptr; + std::string library_path_; +}; + +/// Same as rcpputils::get_platform_library_name(): adds the platform's prefix and suffix. +/** + * E.g. "foo" becomes "libfoo.so" on Linux, "libfoo.dylib" on macOS and "foo.dll" on Windows. + * With debug=true, a "d" is appended to the library name ("libfood.so"). + */ +CLASS_LOADER_PUBLIC +std::string get_platform_library_name(std::string library_name, bool debug = false); + +} // namespace impl +} // namespace class_loader + +#else // CLASS_LOADER_NO_RCPPUTILS + +#include "rcpputils/shared_library.hpp" + +namespace class_loader +{ +namespace impl +{ + +using SharedLibrary = rcpputils::SharedLibrary; +using rcpputils::get_platform_library_name; + +} // namespace impl +} // namespace class_loader + +#endif // CLASS_LOADER_NO_RCPPUTILS + +#endif // CLASS_LOADER__SHARED_LIBRARY_HPP_ diff --git a/src/class_loader.cpp b/src/class_loader.cpp index 66d98a8..20971dc 100644 --- a/src/class_loader.cpp +++ b/src/class_loader.cpp @@ -48,7 +48,7 @@ void ClassLoader::setUnmanagedInstanceBeenCreated(bool state) std::string systemLibraryFormat(const std::string & library_name) { - return rcpputils::get_platform_library_name(library_name); + return impl::get_platform_library_name(library_name); } ClassLoader::ClassLoader(const std::string & library_path, bool ondemand_load_unload) diff --git a/src/class_loader.pc.in b/src/class_loader.pc.in index dff22b9..ddbff4a 100644 --- a/src/class_loader.pc.in +++ b/src/class_loader.pc.in @@ -8,5 +8,5 @@ Description: @PROJECT_DESCRIPTION@ Version: @PROJECT_VERSION@ Requires: @PKGCONFIG_REQUIRES@ Libs: -L${libdir} -l@TARGET_NAME@ @PKGCONFIG_LIBS@ -Cflags: -I${includedir} @PKGCONFIG_CFLAGS@ +Cflags: -I${includedir}/@TARGET_NAME@ @PKGCONFIG_CFLAGS@ diff --git a/src/class_loaderConfig.cmake.in b/src/class_loaderConfig.cmake.in new file mode 100644 index 0000000..b9f9ebd --- /dev/null +++ b/src/class_loaderConfig.cmake.in @@ -0,0 +1,14 @@ +# CMake package configuration for builds without ament (CLASS_LOADER_IGNORE_AMENT=ON) + +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +find_dependency(console_bridge) +if(@CLASS_LOADER_USE_RCPPUTILS@) + find_dependency(rcpputils) +endif() + +include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/class_loader_hide_library_symbols.cmake") + +check_required_components(@PROJECT_NAME@) diff --git a/src/class_loader_core.cpp b/src/class_loader_core.cpp index 6f0f71e..46cd205 100644 --- a/src/class_loader_core.cpp +++ b/src/class_loader_core.cpp @@ -426,13 +426,13 @@ void loadLibrary(const std::string & library_path, ClassLoader * loader) return; } - std::shared_ptr library_handle; + std::shared_ptr library_handle; { setCurrentlyActiveClassLoader(loader); setCurrentlyLoadingLibraryName(library_path); try { - library_handle = std::make_shared(library_path.c_str()); + library_handle = std::make_shared(library_path.c_str()); } catch (const std::runtime_error & e) { setCurrentlyLoadingLibraryName(""); setCurrentlyActiveClassLoader(nullptr); @@ -474,7 +474,7 @@ void loadLibrary(const std::string & library_path, ClassLoader * loader) // Insert library into global loaded library vectory std::lock_guard llv_lock(getLoadedLibraryVectorMutex()); LibraryVector & open_libraries = getLoadedLibraryVector(); - // Note: rcpputils::SharedLibrary automatically calls load() when library passed to constructor + // Note: SharedLibrary automatically calls load() when library passed to constructor open_libraries.push_back(LibraryPair(library_path, library_handle)); } @@ -553,7 +553,7 @@ void unloadLibrary(const std::string & library_path, ClassLoader * loader) return; } catch (const std::runtime_error & e) { throw class_loader::LibraryUnloadException( - "Could not unload library (rcpputils exception = " + std::string(e.what()) + ")"); + "Could not unload library (exception = " + std::string(e.what()) + ")"); } } else { CONSOLE_BRIDGE_logDebug( diff --git a/src/shared_library.cpp b/src/shared_library.cpp new file mode 100644 index 0000000..57adb28 --- /dev/null +++ b/src/shared_library.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2026, DFKI GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Built-in replacement for rcpputils::SharedLibrary, only compiled if class_loader is built +// without rcpputils. It mirrors the behavior of rcutils_load_shared_library(): the library is +// opened with RTLD_LAZY (LoadLibrary on Windows) and its path is resolved where supported. + +#include "class_loader/shared_library.hpp" + +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#if defined(_GNU_SOURCE) && defined(__GLIBC__) +#include +#define CLASS_LOADER_HAS_DLINFO +#elif defined(__APPLE__) +#include +#include +#endif +#endif + +namespace class_loader +{ +namespace impl +{ + +namespace +{ + +/// Closes the given library handle; returns an error message on failure, an empty string otherwise. +std::string closeLibrary(void * handle) +{ +#ifdef _WIN32 + if (!FreeLibrary(static_cast(handle))) { + return "FreeLibrary error: " + std::to_string(GetLastError()); + } +#else + if (dlclose(handle) != 0) { + const char * error = dlerror(); + return std::string("dlclose error: ") + (error ? error : "unknown error"); + } +#endif + return ""; +} + +} // namespace + +SharedLibrary::SharedLibrary(const std::string & library_path) +{ +#ifdef _WIN32 + HMODULE module = LoadLibraryA(library_path.c_str()); + if (!module) { + throw std::runtime_error("LoadLibrary error: " + std::to_string(GetLastError())); + } + std::string path(MAX_PATH, '\0'); + while (true) { + DWORD size = GetModuleFileNameA(module, path.data(), static_cast(path.size())); + if (size == 0) { + const std::string error = "GetModuleFileName error: " + std::to_string(GetLastError()); + FreeLibrary(module); + throw std::runtime_error(error); + } + if (size < path.size()) { + path.resize(size); + break; + } + // The path was truncated, retry with a larger buffer. + path.resize(path.size() * 2); + } + handle_ = module; + library_path_ = path; +#else + handle_ = dlopen(library_path.c_str(), RTLD_LAZY); + if (!handle_) { + const char * error = dlerror(); + throw std::runtime_error(std::string("dlopen error: ") + (error ? error : "unknown error")); + } + library_path_ = library_path; +#ifdef CLASS_LOADER_HAS_DLINFO + struct link_map * map = nullptr; + if (dlinfo(handle_, RTLD_DI_LINKMAP, &map) == 0 && map && map->l_name && map->l_name[0]) { + library_path_ = map->l_name; + } +#elif defined(__APPLE__) + // As rcutils: find the loaded image with the same handle (likely near the end of the list). + // This resolves e.g. a bare file name found via DYLD_LIBRARY_PATH, which pinLibrary() needs. + for (uint32_t i = _dyld_image_count(); i > 0; --i) { + const char * name = _dyld_get_image_name(i - 1); + void * handle = name ? dlopen(name, RTLD_LAZY | RTLD_NOLOAD) : nullptr; + if (handle) { + dlclose(handle); // still loaded through handle_ + if (handle == handle_) { + library_path_ = name; + break; + } + } + } +#endif +#endif +} + +SharedLibrary::~SharedLibrary() +{ + if (handle_) { + const std::string error = closeLibrary(handle_); + if (!error.empty()) { + std::cerr << error << std::endl; + } + } +} + +void SharedLibrary::unload_library() +{ + if (!handle_) { + throw std::runtime_error("Library is not loaded"); + } + const std::string error = closeLibrary(handle_); + handle_ = nullptr; + library_path_.clear(); + if (!error.empty()) { + throw std::runtime_error(error); + } +} + +std::string SharedLibrary::get_library_path() const +{ + if (!handle_) { + throw std::runtime_error("Library path is not defined"); + } + return library_path_; +} + +std::string get_platform_library_name(std::string library_name, bool debug) +{ + if (debug) { + library_name += "d"; + } +#if defined(_WIN32) && !defined(__MINGW64__) + return library_name + ".dll"; +#elif defined(_WIN32) + return "lib" + library_name + ".dll"; +#elif defined(__APPLE__) + return "lib" + library_name + ".dylib"; +#else + return "lib" + library_name + ".so"; +#endif +} + +} // namespace impl +} // namespace class_loader diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index dea7701..4cbca6d 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,4 +1,51 @@ -find_package(ament_cmake_gtest REQUIRED) +if(NOT CLASS_LOADER_IGNORE_AMENT) + find_package(ament_cmake_gtest REQUIRED) +else() + find_package(GTest REQUIRED) + + # Minimal replacement for ament_add_gtest() without ament, using GoogleTest from the system. + # Only APPEND_LIBRARY_DIRS is supported, the other arguments of ament_add_gtest() are ignored + # (with a warning). The library dirs and the dir of class_loader itself are prepended (not + # appended as by ament), so that the tests do not pick up an installed class_loader. + function(ament_add_gtest target) + set(_options SKIP_LINKING_MAIN_LIBRARIES SKIP_TEST) + set(_one_value_args RUNNER TIMEOUT WORKING_DIRECTORY) + set(_multi_value_args APPEND_ENV ENV) + cmake_parse_arguments(ARG "${_options}" "${_one_value_args}" + "${_multi_value_args};APPEND_LIBRARY_DIRS" ${ARGN}) + set(_ignored) + foreach(_arg ${_options}) + if(ARG_${_arg}) + list(APPEND _ignored ${_arg}) + endif() + endforeach() + foreach(_arg ${_one_value_args} ${_multi_value_args}) + if(DEFINED ARG_${_arg} OR _arg IN_LIST ARG_KEYWORDS_MISSING_VALUES) + list(APPEND _ignored ${_arg}) + endif() + endforeach() + if(_ignored) + list(JOIN _ignored ", " _ignored) + message(WARNING "ament_add_gtest(${target}): ignoring ${_ignored} without ament") + endif() + add_executable(${target} ${ARG_UNPARSED_ARGUMENTS}) + target_link_libraries(${target} GTest::gtest_main) + add_test(NAME ${target} COMMAND ${target}) + if(WIN32) + set(_var PATH) + set(_sep "\\;") + elseif(APPLE) + set(_var DYLD_LIBRARY_PATH) + set(_sep ":") + else() + set(_var LD_LIBRARY_PATH) + set(_sep ":") + endif() + set(_dirs "$" ${ARG_APPEND_LIBRARY_DIRS} "$ENV{${_var}}") + string(REPLACE ";" "${_sep}" _dirs "${_dirs}") + set_tests_properties(${target} PROPERTIES ENVIRONMENT "${_var}=${_dirs}") + endfunction() +endif() include("../cmake/class_loader_hide_library_symbols.cmake") @@ -14,6 +61,10 @@ add_library(${PROJECT_NAME}_TestPlugins3 EXCLUDE_FROM_ALL SHARED plugins3.cpp) target_link_libraries(${PROJECT_NAME}_TestPlugins3 ${PROJECT_NAME}) class_loader_hide_library_symbols(${PROJECT_NAME}_TestPlugins3) +# A library without plugins, for testing SharedLibrary. +add_library(${PROJECT_NAME}_TestSharedLibrary EXCLUDE_FROM_ALL SHARED + shared_library_test_library.cpp) + # These plugins are loaded using dlopen() with RTLD_GLOBAL in utest and may cause side effects # in other tests if they are used elsewhere. add_library(${PROJECT_NAME}_TestGlobalPlugins EXCLUDE_FROM_ALL SHARED global_plugins.cpp) @@ -31,7 +82,7 @@ ament_add_gtest(${PROJECT_NAME}_utest utest.cpp ) if(TARGET ${PROJECT_NAME}_utest) - if(ament_cmake_FOUND) + if(NOT CLASS_LOADER_IGNORE_AMENT) target_include_directories(${PROJECT_NAME}_utest PUBLIC "../include") target_link_libraries(${PROJECT_NAME}_utest @@ -85,4 +136,12 @@ if(TARGET ${PROJECT_NAME}_multi_library_exit_test) add_dependencies(${PROJECT_NAME}_multi_library_exit_test ${PROJECT_NAME}_TestPlugins1) endif() +ament_add_gtest(${PROJECT_NAME}_shared_library_test shared_library_test.cpp + APPEND_LIBRARY_DIRS "${append_library_dirs}" +) +if(TARGET ${PROJECT_NAME}_shared_library_test) + target_link_libraries(${PROJECT_NAME}_shared_library_test ${PROJECT_NAME}) + add_dependencies(${PROJECT_NAME}_shared_library_test ${PROJECT_NAME}_TestSharedLibrary) +endif() + add_subdirectory(fviz_case_study) diff --git a/test/external_load_test.cpp b/test/external_load_test.cpp index 984c2b0..f0543cf 100644 --- a/test/external_load_test.cpp +++ b/test/external_load_test.cpp @@ -34,7 +34,7 @@ #include #include "class_loader/class_loader.hpp" -#include "rcpputils/shared_library.hpp" +#include "class_loader/shared_library.hpp" #include "gtest/gtest.h" @@ -52,7 +52,7 @@ const std::string LIBRARY_2 = class_loader::systemLibraryFormat("class_loader_Te // maps, destroyed later, still need to delete the library's MetaObjects. void openLibrary1Externally() { - static const auto * library = new rcpputils::SharedLibrary(LIBRARY_1); + static const auto * library = new class_loader::impl::SharedLibrary(LIBRARY_1); (void)library; ASSERT_TRUE(class_loader::impl::hasANonPurePluginLibraryBeenOpened()); } diff --git a/test/shared_library_test.cpp b/test/shared_library_test.cpp new file mode 100644 index 0000000..28418b2 --- /dev/null +++ b/test/shared_library_test.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, DFKI GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Tests class_loader::impl::SharedLibrary, i.e., the built-in implementation or +// rcpputils::SharedLibrary (depending on CLASS_LOADER_USE_RCPPUTILS). + +#include +#include +#include + +#include "class_loader/class_loader.hpp" +#include "class_loader/shared_library.hpp" + +#include "gtest/gtest.h" + +using class_loader::impl::SharedLibrary; + +// A library without plugins, so it can be unloaded safely. +const std::string LIBRARY = // NOLINT + class_loader::systemLibraryFormat("class_loader_TestSharedLibrary"); + +TEST(SharedLibraryTest, loadAndUnload) { + SharedLibrary library(LIBRARY); + const std::string path = library.get_library_path(); + EXPECT_NE(std::string::npos, path.find("class_loader_TestSharedLibrary")) << path; + + library.unload_library(); + EXPECT_THROW(library.unload_library(), std::runtime_error); + EXPECT_THROW(std::ignore = library.get_library_path(), std::runtime_error); +} + +TEST(SharedLibraryTest, unloadOnDestruction) { + { + SharedLibrary library(LIBRARY); + } + // Loading again works after the destructor has unloaded the library. + SharedLibrary library(LIBRARY); + EXPECT_FALSE(library.get_library_path().empty()); +} + +TEST(SharedLibraryTest, nonexistentLibrary) { + EXPECT_THROW( + SharedLibrary{class_loader::systemLibraryFormat("class_loader_nonexistent")}, + std::runtime_error); +} + +TEST(SharedLibraryTest, platformLibraryName) { +#ifdef _WIN32 + const std::string suffix = ".dll"; +#elif defined(__APPLE__) + const std::string suffix = ".dylib"; +#else + const std::string suffix = ".so"; +#endif + EXPECT_TRUE(class_loader::impl::get_platform_library_name("foo").ends_with("foo" + suffix)); + EXPECT_TRUE( + class_loader::impl::get_platform_library_name("foo", true).ends_with("food" + suffix)); + EXPECT_EQ( + class_loader::impl::get_platform_library_name("foo"), class_loader::systemLibraryFormat("foo")); +} diff --git a/test/shared_library_test_library.cpp b/test/shared_library_test_library.cpp new file mode 100644 index 0000000..35e9c4e --- /dev/null +++ b/test/shared_library_test_library.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026, DFKI GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// A shared library without plugins, loaded and unloaded by shared_library_test.cpp. + +int class_loader_test_shared_library_function() +{ + return 42; +} diff --git a/test/standalone/CMakeLists.txt b/test/standalone/CMakeLists.txt new file mode 100644 index 0000000..1f49db3 --- /dev/null +++ b/test/standalone/CMakeLists.txt @@ -0,0 +1,57 @@ +# Checks an installed class_loader built without ament (CLASS_LOADER_IGNORE_AMENT=ON) by building +# one of the tests against it, once using its CMake package configuration and once using its +# pkg-config file (if pkg-config is available and not on Windows). +cmake_minimum_required(VERSION 3.20) + +project(class_loader_standalone_test CXX) + +enable_testing() + +find_package(class_loader REQUIRED) +find_package(GTest REQUIRED) +if(NOT WIN32) + find_package(PkgConfig) +endif() + +# The plugin libraries need the names expected by the test. +foreach(_i 1 2) + add_library(class_loader_TestPlugins${_i} SHARED ../plugins${_i}.cpp) + target_link_libraries(class_loader_TestPlugins${_i} class_loader::class_loader) + class_loader_hide_library_symbols(class_loader_TestPlugins${_i}) +endforeach() + +set(_variants cmake) +add_executable(external_load_test_cmake ../external_load_test.cpp) +target_link_libraries(external_load_test_cmake class_loader::class_loader GTest::gtest_main) + +if(PKG_CONFIG_FOUND) + pkg_check_modules(class_loader_pc REQUIRED IMPORTED_TARGET class_loader) + list(APPEND _variants pkgconfig) + add_executable(external_load_test_pkgconfig ../external_load_test.cpp) + target_link_libraries(external_load_test_pkgconfig + PkgConfig::class_loader_pc GTest::gtest_main) + # pkg-config cannot express the C++ standard required by the headers. + target_compile_features(external_load_test_pkgconfig PRIVATE cxx_std_20) +endif() + +# The tests load the plugin libraries by name, and need to find class_loader at runtime. +if(WIN32) + set(_var PATH) + set(_sep "\\;") +elseif(APPLE) + set(_var DYLD_LIBRARY_PATH) + set(_sep ":") +else() + set(_var LD_LIBRARY_PATH) + set(_sep ":") +endif() +set(_dirs + "$" + "$" + "$ENV{${_var}}") +string(REPLACE ";" "${_sep}" _dirs "${_dirs}") + +foreach(_variant ${_variants}) + add_test(NAME external_load_test_${_variant} COMMAND external_load_test_${_variant}) + set_tests_properties(external_load_test_${_variant} PROPERTIES ENVIRONMENT "${_var}=${_dirs}") +endforeach()