From 11b846f6b7b9a3da7e8d6596ac6fa7ef2ead73c0 Mon Sep 17 00:00:00 2001 From: jabberrock <130935387+jabberrock@users.noreply.github.com> Date: Wed, 20 Nov 2024 04:16:52 -0800 Subject: [PATCH] Fix bounds checks in BMI270 driver in `bulk_read` (#362) Both i and bytes_to_read are size_t, which are unsigned long. `i - bytes_to_read` should have been `bytes_to_read - i` for how many bytes are left in the buffer. But since we're dealing with unsigned values, it's safer to only do additions and comparisons. --- src/sensors/softfusion/drivers/bmi270.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/sensors/softfusion/drivers/bmi270.h b/src/sensors/softfusion/drivers/bmi270.h index 7938e0ca..91bd6155 100644 --- a/src/sensors/softfusion/drivers/bmi270.h +++ b/src/sensors/softfusion/drivers/bmi270.h @@ -398,15 +398,18 @@ struct BMI270 { for (uint32_t i = 0u; i < bytes_to_read;) { const uint8_t header = getFromFifo(i, read_buffer); - if ((header & Fifo::ModeMask) == Fifo::SkipFrame - && (i - bytes_to_read) >= 1) { + if ((header & Fifo::ModeMask) == Fifo::SkipFrame) { + if (i + 1 > bytes_to_read) { + // incomplete frame, nothing left to process + break; + } getFromFifo(i, read_buffer); // skip 1 byte } else if ((header & Fifo::ModeMask) == Fifo::DataFrame) { const uint8_t required_length = (((header & Fifo::GyrDataBit) >> Fifo::GyrDataBit) + ((header & Fifo::AccelDataBit) >> Fifo::AccelDataBit)) * 6; - if (i - bytes_to_read < required_length) { + if (i + required_length > bytes_to_read) { // incomplete frame, will be re-read next time break; }