From f2c3ab45d1bde3fd9a70cc5000a888bb6019d8e7 Mon Sep 17 00:00:00 2001 From: Julian Oes Date: Wed, 18 Nov 2026 13:10:08 +1300 Subject: [PATCH] fix(mavlink): close log files in the receiver thread (#29854) The log handler opens the log file in the receiver thread, but on 'mavlink stop' its destructor runs in the stop task and fclose()s it there. On NuttX a FILE belongs to the task group that opened it: fclose() from another task frees it while it stays linked in the owner's stream list, and the owner frees it again on exit. This double free corrupts the heap when USB is unplugged during a log download (hardfault in mm_free, or load_mon hanging in mallinfo()). Close the files at the end of MavlinkReceiver::run(), in the owning thread. Ported from the v1.18 fix in #29187. Signed-off-by: Julian Oes --- src/modules/mavlink/mavlink_log_handler.cpp | 6 ++++++ src/modules/mavlink/mavlink_log_handler.h | 9 +++++++++ src/modules/mavlink/mavlink_receiver.cpp | 3 +++ 3 files changed, 18 insertions(+) diff --git a/src/modules/mavlink/mavlink_log_handler.cpp b/src/modules/mavlink/mavlink_log_handler.cpp index 23a98431040..0689fb6ad29 100644 --- a/src/modules/mavlink/mavlink_log_handler.cpp +++ b/src/modules/mavlink/mavlink_log_handler.cpp @@ -122,6 +122,12 @@ void MavlinkLogHandler::state_idle() } } +void MavlinkLogHandler::close_files() +{ + close_current_entry(); + _state = LogHandlerState::Idle; +} + void MavlinkLogHandler::close_current_entry() { if (_current_entry.fp) { diff --git a/src/modules/mavlink/mavlink_log_handler.h b/src/modules/mavlink/mavlink_log_handler.h index 9634d7f9239..399a1e0d5b0 100644 --- a/src/modules/mavlink/mavlink_log_handler.h +++ b/src/modules/mavlink/mavlink_log_handler.h @@ -59,6 +59,15 @@ public: void send(); void handle_message(const mavlink_message_t *msg); + /** + * Close any open log file. Must be called from the thread that handles the + * log messages (the receiver thread): on NuttX a FILE belongs to the task + * group that opened it, and fclose() from another task (e.g. the destructor + * running in 'mavlink stop') frees it while it stays linked in the owner's + * stream list, which then frees it again on exit (double free). + */ + void close_files(); + /// True while LOG_DATA is streaming out. bool sending_data() const { return _state == LogHandlerState::SendingData; } diff --git a/src/modules/mavlink/mavlink_receiver.cpp b/src/modules/mavlink/mavlink_receiver.cpp index 8a939c31ebc..8dc0d861d8d 100644 --- a/src/modules/mavlink/mavlink_receiver.cpp +++ b/src/modules/mavlink/mavlink_receiver.cpp @@ -4283,6 +4283,9 @@ MavlinkReceiver::run() _tune_publisher->publish_next_tune(t); } } + + // Release files opened by this thread while still in its task group (see close_files()) + _mavlink_log_handler.close_files(); } MavlinkReceiver::FrameCheck MavlinkReceiver::check_frame(uint8_t framing, const mavlink_message_t &message)