Segfault at process exit after dlclose() of a library using rclcpp: g_rmw_lib destructor unmaps librmw_implementation

Đang mở
#301 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
48/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
cpp, linux
Lĩnh vực
backend

Hướng nghiên cứu

Start with rmw_implementation/src/functions.cpp and trace how the RMW library handle is stored, loaded, and reset in get_library() and unload_library(). Reproduce the exit-time crash with the supplied host and ROS library example, then check whether the proposed lifetime change prevents it. Done means the reproducer exits successfully while unload_library() retains its test and benchmark behavior.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

Generated by Generative AI

Claude Opus 5.5 (Anthropic) via Claude Code: investigation (gdb, dynamic loader tracing), reproducer, proposed change, and this text.

Operating System
Linux 7.0.0-28-generic #28-Ubuntu SMP PREEMPT_DYNAMIC x86_64 GNU/Linux
Ubuntu 26.04.1 LTS, glibc 2.43-2ubuntu2.4
Also reproduced in a clean ros:lyrical Docker image after `apt-get upgrade`.
ROS version or commit hash

lyrical: rmw_implementation 3.1.6, rcl_logging_implementation 3.4.1, rclcpp 32.0.3, rmw_fastrtps_cpp 9.4.10

RMW implementation (if applicable)

rmw_fastrtps_cpp (default)

Client library (if applicable)

rclcpp

Steps to reproduce issue

An executable dlopen()s a library that uses rclcpp, dlclose()s it, and returns from main().

host.cpp:

// Loads a library that uses ROS 2, runs it, unloads it, and exits normally.
#include <dlfcn.h>
#include <cstdio>

int main()
{
  void * lib = dlopen("./libros_user.so", RTLD_NOW | RTLD_LOCAL);
  if (!lib) {
    std::fprintf(stderr, "dlopen failed: %s\n", dlerror());
    return 2;
  }
  auto run = reinterpret_cast<int (*)()>(dlsym(lib, "run"));
  int result = run();
  dlclose(lib);
  std::fprintf(stderr, "main returns %d\n", result);
  return result;
}

ros_user.cpp:

// Initializes ROS 2, creates a node with a publisher, spins once, and shuts down.
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/string.hpp>

extern "C" int run()
{
  rclcpp::init(0, nullptr);
  {
    auto node = std::make_shared<rclcpp::Node>("dlclose_repro");
    auto pub = node->create_publisher<std_msgs::msg::String>("chatter", 10);
    rclcpp::executors::SingleThreadedExecutor executor;
    executor.add_node(node);
    executor.spin_some();
  }
  rclcpp::shutdown();
  return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)
project(rmw_dlclose_repro CXX)

find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)

add_library(ros_user SHARED ros_user.cpp)
target_link_libraries(ros_user ${std_msgs_TARGETS} rclcpp::rclcpp)

add_executable(host host.cpp)
docker run --rm -it ros:lyrical bash
apt-get update && apt-get install -y clang && apt-get -y upgrade
# create the three files above in the current directory
source /opt/ros/lyrical/setup.bash
cmake -S . -B build -DCMAKE_CXX_COMPILER=clang++
cmake --build build
cd build && ./host; echo "exit code: $?"
Expected behavior

main returns 0 is printed and the exit code is 0.

Actual behavior

main returns 0 is printed, then the process crashes during exit: Segmentation fault (core dumped), exit code 139. It happens on every run.

Additional information

What happens (gdb, LD_DEBUG=files,bindings, and glibc's elf/dl-close.c):

  1. When the host calls dlclose() on its library, glibc cannot unload the ROS 2 libraries yet: librclcpp.so has a pending thread_local destructor registered on the main thread (l_tls_dtor_count > 0), and an object in that state is kept. So the library, rclcpp, and their dependencies, including librmw_implementation.so, stay loaded.
  2. During exit(), the main thread's thread_local destructors run first. After that, the only references keeping these libraries loaded are the plugin libraries opened at runtime: librmw_fastrtps_cpp.so (held by g_rmw_lib in rmw_implementation) and librcl_logging_spdlog.so (held by rcl_logging_implementation).
  3. The exit handlers run the static destructor of g_rmw_lib, which dlclose()s librmw_fastrtps_cpp.so. This dlclose() is not nested in another dlclose(), so glibc unloads all objects that are no longer used: the RMW library and the whole group the application closed, including librmw_implementation.so. When dlclose() returns, execution continues in the unmapped librmw_implementation.so and crashes:
Thread 1 "host" received signal SIGSEGV, Segmentation fault.
#0  0x00007ffff7a34b01 in ?? ()          <- in librmw_implementation.so, already unmapped
...
#4  __run_exit_handlers (...) at ./stdlib/exit.c:118

(0x...4b01 is the return address after rcpputils::SharedLibrary::~SharedLibrary() in the release of g_rmw_lib.)

rcl_logging_implementation has the same problem in its atexit(unload_logging_library) handler, which dlclose()s librcl_logging_spdlog.so and can unmap librcl_logging_implementation.so the same way. I have not reported it in ros2/rcl_logging yet; the fix there is analogous (keep the handle in storage that is never destroyed and drop the atexit() registration), and I can open an issue there as well. In this reproducer that handler runs before the g_rmw_lib destructor:

  • With both libraries unpatched, the process crashes when returning into unload_logging_library(). The g_rmw_lib destructor runs inside that dlclose(), as part of unloading the group.
  • With only rcl_logging_implementation fixed, the process crashes in the g_rmw_lib destructor as shown above.
  • With only rmw_implementation fixed, it still crashes in unload_logging_library().

Both changes are needed.

Observations:

  • Not reproducible on Jazzy (Ubuntu 24.04, rmw_implementation 2.15.6) with the same reproducer.
  • Not reproducible with the May 2026 Lyrical packages in the ros:lyrical image (rclcpp 32.0.0, rmw_implementation 3.1.5); reproducible after apt-get upgrade. The change that exposes it in this reproducer is ros2/rclcpp#3219 (b723878c, first released in rclcpp 32.0.3): its static thread_local std::unordered_set<const Context *> g_contexts_in_shutdown in context.cpp registers a thread_local destructor on the thread that calls rclcpp::shutdown(). That registration is the only one in the process and is what keeps librclcpp.so loaded after the host's dlclose() (step 1 above). When that registration is suppressed (LD_PRELOAD interposer for __cxa_thread_atexit_impl), the reproducer exits with 0. #3219 itself is not wrong; it only delays the unload to process exit, where the exit-time unload of the plugin libraries crashes. Other applications reach the same state without #3219, whenever something else keeps the ROS 2 libraries loaded after the application's dlclose().
  • Not reproducible when the library is built with GCC. The GCC-built library contains STB_GNU_UNIQUE symbols, which make glibc mark it as non-unloadable, so its dependencies are never unloaded either.
  • With target_link_libraries(ros_user rclcpp::rclcpp ${std_msgs_TARGETS}) (rclcpp first), it does not reproduce: message typesupport libraries that are still open at exit then resolve some C++ typeinfo symbols to librclcpp.so, which keeps rclcpp and librmw_implementation.so loaded.
  • elf/dl-close.c is functionally the same in glibc 2.39 and 2.43.
  • We first hit this in a real application (unit tests that load ROS 2 modules at runtime, built with clang).
Proposed solution

Do not unload the RMW library during process exit: keep the handle in a function-local static that is never destroyed. unload_library() (used by tests and benchmarks) still resets it.

--- a/rmw_implementation/src/functions.cpp
+++ b/rmw_implementation/src/functions.cpp
@@ -45,7 +45,17 @@
 #define STRINGIFY_(s) #s
 #define STRINGIFY(s) STRINGIFY_(s)
 
-static std::shared_ptr<rcpputils::SharedLibrary> g_rmw_lib = nullptr;
+// The RMW library handle is intentionally never destroyed, so the RMW library is not unloaded
+// by a static destructor at process exit. During exit, the RMW library can be the last object
+// keeping this library loaded (e.g. after the application dlclose()d the library that uses
+// ROS 2), and unloading it from a static destructor of this library would then unmap this
+// library while the destructor is still running.
+static std::shared_ptr<rcpputils::SharedLibrary> &
+rmw_lib()
+{
+  static auto * lib = new std::shared_ptr<rcpputils::SharedLibrary>();
+  return *lib;
+}
 
 static std::shared_ptr<rcpputils::SharedLibrary>
 attempt_to_load_one_rmw(const std::string & library)
@@ -132,10 +142,11 @@ load_library()
 std::shared_ptr<rcpputils::SharedLibrary>
 get_library()
 {
-  if (!g_rmw_lib) {
-    g_rmw_lib = load_library();
+  auto & lib = rmw_lib();
+  if (!lib) {
+    lib = load_library();
   }
-  return g_rmw_lib;
+  return lib;
 }
 
 void *
@@ -1036,5 +1047,5 @@ unload_library()
   symbol_rmw_take_dynamic_message = nullptr;
   symbol_rmw_take_dynamic_message_with_info = nullptr;
   symbol_rmw_serialization_support_init = nullptr;
-  g_rmw_lib.reset();
+  rmw_lib().reset();
 }

Tested on Ubuntu 26.04 with the lyrical branch of rmw_implementation and rcl_logging:

reproducer exit codes (3 runs)
unpatched 139 139 139
only rmw_implementation patched 139 139 139 (crash in unload_logging_library())
only rcl_logging_implementation patched 139 139 139 (crash after g_rmw_lib release)
both patched 0 0 0

rmw_implementation tests and linters pass (38 tests, 0 failures). In test_rmw_implementation, test_subscription__rmw_fastrtps_cpp take_with_info_publisher_gid_for_uint8_sequence_type fails with and without this change.

Trade-offs and alternatives:

  • If an application unloads librmw_implementation itself (for example, a host that unloads and reloads a module using ROS 2), the RMW library stays loaded after it. Each such cycle keeps one reference to the RMW library.
  • unload_library() keeps its current behavior; it is only used by tests and benchmarks.
  • Alternatives: load the RMW library with RTLD_NODELETE, or skip the reset only during process teardown. Both need changes to how rcpputils::SharedLibrary is used.

Happy to open a PR if the approach is acceptable.

Ngôn ngữ chính
C++
Star
25
Fork
66
Merge trung bình
5 ngày 17 giờ
Pull request đã merge (30 ngày)
8

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của ros2/rmw_implementation

Tất cả issue của ros2/rmw_implementation

Issue tương tự

Thêm issue về C++

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.