From 4677ae3534d39ec9d49b5e9353399bc56ff2f75b Mon Sep 17 00:00:00 2001 From: Pierre Kancir Date: Thu, 5 Nov 2026 17:11:08 +0100 Subject: [PATCH] AP_HAL_ChibiOS: stop F1 bdshot decode reading past its buffer When the buffer ran out before 21 bits, the last pass filled the remaining bits but still read buffer[i] with i at count or count+1. With a full buffer that is past the end of dma_buffer_copy. Only read the buffer for an index inside it. The bits check only ran for an index inside the buffer, so after the fill a second pass shifted by len - 1 with len 0. And when a transition had already taken bits past 21, the fill wrapped len so that bits came back to exactly 21 and the corrupt frame was decoded. Check bits first on every pass, so such a frame now gives INVALID_ERPM. Checked on the host against the old loop with 2 million generated frames, with ARM shift semantics for the old one: the results are the same except for those overshooting frames, and a full buffer of equal samples no longer reads buffer[23] of 22. Co-Authored-By: Claude Opus 5.5 --- libraries/AP_HAL_ChibiOS/RCOutput_iofirmware.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/libraries/AP_HAL_ChibiOS/RCOutput_iofirmware.cpp b/libraries/AP_HAL_ChibiOS/RCOutput_iofirmware.cpp index d762c1189a9a..36b79056ea06 100644 --- a/libraries/AP_HAL_ChibiOS/RCOutput_iofirmware.cpp +++ b/libraries/AP_HAL_ChibiOS/RCOutput_iofirmware.cpp @@ -386,19 +386,20 @@ uint32_t RCOutput::bdshot_decode_telemetry_packet_f1(dmar_uint_t* buffer, uint32 dmar_uint_t oldValue = buffer[1]; for (int32_t i = 0; i <= count+1; ) { + // checked first, so the fill below never runs with no bits left + if (bits >= 21U) { + break; + } if (i < count) { dmar_int_t diff = buffer[i] - oldValue; - if (bits >= 21U) { - break; - } len = (diff + TELEM_IC_SAMPLE/2U) / TELEM_IC_SAMPLE; + oldValue = buffer[i]; } else { len = 21U - bits; } value <<= len; value |= 1U << (len - 1U); - oldValue = buffer[i]; bits += len; i += (i%2 ? -1 : 3);